The copyright notice above and this permission notice must be
preserved complete on all complete or partial copies.

Any translation or derivative work of the Objective Caml
documentation and user's manual must be approved by the authors in
writing before distribution.

If you distribute the Objective Caml
documentation and user's manual in part, instructions for obtaining
the complete version of this manual must be included, and a
means for obtaining a complete version provided.

Small portions may be reproduced as illustrations for reviews or
quotes in other works without this permission notice if proper
citation is given.

This part of the manual is a tutorial introduction to the Objective
Caml language. A good familiarity with programming in a conventional
languages (say, Pascal or C) is assumed, but no prior exposure to
functional languages is required. The present chapter introduces the
core language. Chapter 3 deals with the
object-oriented features, and chapter 2 with the
module system.

For this overview of Caml, we use the interactive system, which
is started by running ocaml from the Unix shell, or by launching the
OCamlwin.exe application under Windows. This tutorial is presented
as the transcript of a session with the interactive system:
lines starting with # represent user input; the system responses are
printed below, without a leading #.

Under the interactive system, the user types Caml phrases, terminated
by ;;, in response to the # prompt, and the system compiles them
on the fly, executes them, and prints the outcome of evaluation.
Phrases are either simple expressions, or let definitions of
identifiers (either values or functions).

The Caml system computes both the value and the type for
each phrase. Even function parameters need no explicit type declaration:
the system infers their types from their usage in the
function. Notice also that integers and floating-point numbers are
distinct types, with distinct operators: + and * operate on
integers, but +. and *. operate on floats.

#1.0 * 2;;
This expression has type float but is here used with type int

Predefined data structures include tuples, arrays, and lists. General
mechanisms for defining your own data structures are also provided.
They will be covered in more details later; for now, we concentrate on lists.
Lists are either given in extension as a bracketed list of
semicolon-separated elements, or built from the empty list []
(pronounce ``nil'') by adding elements in front using the ::
(``cons'') operator.

As with all other Caml data structures, lists do not need to be
explicitly allocated and deallocated from memory: all memory
management is entirely automatic in Caml. Similarly, there is no
explicit handling of pointers: the Caml compiler silently introduces
pointers where necessary.

As with most Caml data structures, inspecting and destructuring lists
is performed by pattern-matching. List patterns have the exact same
shape as list expressions, with identifier representing unspecified
parts of the list. As an example, here is insertion sort on a list:

The type inferred for sort, 'a list -> 'a list, means that sort
can actually apply to lists of any type, and returns a list of the
same type. The type 'a is a type variable, and stands for any
given type. The reason why sort can apply to lists of any type is
that the comparisons (=, <=, etc.) are polymorphic in Caml:
they operate between any two values of the same type. This makes
sort itself polymorphic over all list types.

The sort function above does not modify its input list: it builds
and returns a new list containing the same elements as the input list,
in ascending order. There is actually no way in Caml to modify
in-place a list once it is built: we say that lists are immutable
data structures. Most Caml data structures are immutable, but a few
(most notably arrays) are mutable, meaning that they can be
modified in-place at any time.

Caml is a functional language: functions in the full mathematical
sense are supported and can be passed around freely just as any other
piece of data. For instance, here is a deriv function that takes any
float function as argument and returns an approximation of its
derivative function:

Functions that take other functions as arguments are called
``functionals'', or ``higher-order functions''. Functionals are
especially useful to provide iterators or similar generic operations
over a data structure. For instance, the standard Caml library
provides a List.map functional that applies a given function to each
element of a list, and returns the list of the results:

The declaration of a variant type lists all possible shapes for values
of that type. Each case is identified by a name, called a constructor,
which serves both for constructing values of the variant type and
inspecting them by pattern-matching. Constructor names are capitalized
to distinguish them from variable names (which must start with a
lowercase letter). For instance, here is a variant
type for doing mixed arithmetic (integers and floats):

This definition reads as follow: a binary tree containing values of
type 'a (an arbitrary type) is either empty, or is a node containing
one value of type 'a and two subtrees containing also values of type
'a, that is, two 'a btree.

Operations on binary trees are naturally expressed as recursive functions
following the same structure as the type definition itself. For
instance, here are functions performing lookup and insertion in
ordered binary trees (elements increase from left to right):

Though all examples so far were written in purely applicative style,
Caml is also equipped with full imperative features. This includes the
usual while and for loops, as well as mutable data structures such
as arrays. Arrays are either given in extension between [| and |]
brackets, or allocated and initialized with the Array.create
function, then filled up later by assignments. For instance, the
function below sums two vectors (represented as float arrays) componentwise.

Caml has no built-in notion of variable -- identifiers whose current
value can be changed by assignment. (The let binding is not an
assignment, it introduces a new identifier with a new scope.)
However, the standard library provides references, which are mutable
indirection cells (or one-element arrays), with operators ! to fetch
the current contents of the reference and := to assign the contents.
Variables can then be emulated by let-binding a reference. For
instance, here is an in-place insertion sort over arrays:

References are also useful to write functions that maintain a current
state between two calls to the function. For instance, the following
pseudo-random number generator keeps the last returned number in a
reference:

In some special cases, you may need to store a polymorphic function in
a data structure, keeping its polymorphism. Without user-provided
type annotations, this is not allowed, as polymorphism is only
introduced on a global level. However, you can give explicitly
polymorphic types to record fields.

Caml provides exceptions for signalling and handling exceptional
conditions. Exceptions can also be used as a general-purpose non-local
control structure. Exceptions are declared with the exception
construct, and signalled with the raise operator. For instance, the
function below for taking the head of a list uses an exception to
signal the case where an empty list is given.

Exceptions are used throughout the standard library to signal cases
where the library functions cannot complete normally. For instance,
the List.assoc function, which returns the data associated with a
given key in a list of (key, data) pairs, raises the predefined
exception Not_found when the key does not appear in the list:

The with part is actually a regular pattern-matching on the
exception value. Thus, several exceptions can be caught by one
try...with construct. Also, finalization can be performed by
trapping all exceptions, performing the finalization, then raising
again the exception:

We finish this introduction with a more complete example
representative of the use of Caml for symbolic processing: formal
manipulations of arithmetic expressions containing variables. The
following variant type describes the expressions we shall manipulate:

As shown in the examples above, the internal representation (also
called abstract syntax) of expressions quickly becomes hard to
read and write as the expressions get larger. We need a printer and a
parser to go back and forth between the abstract syntax and the concrete syntax, which in the case of expressions is the familiar
algebraic notation (e.g. 2*x+1).

For the printing function, we take into account the usual precedence
rules (i.e. * binds tighter than +) to avoid printing unnecessary
parentheses. To this end, we maintain the current operator precedence
and print parentheses around an operator only if its precedence is
less than the current precedence.

Parsing (transforming concrete syntax into abstract syntax) is usually
more delicate. Caml offers several tools to help write parsers:
on the one hand, Caml versions of the lexer generator Lex and the
parser generator Yacc (see chapter 12), which handle
LALR(1) languages using push-down automata; on the other hand, a
predefined type of streams (of characters or tokens) and
pattern-matching over streams, which facilitate the writing of
recursive-descent parsers for LL(1) languages. An example using
ocamllex and ocamlyacc is given in
chapter 12. Here, we will use stream parsers.
The syntactic support for stream parsers is provided by the Camlp4
preprocessor, which can be loaded into the interactive toplevel via
the #load directive below.

For the lexical analysis phase (transformation of the input text into
a stream of tokens), we use a ``generic'' lexer provided in the
standard library module Genlex. The make_lexer function takes a
list of keywords and returns a lexing function that ``tokenizes'' an
input stream of characters. Tokens are either identifiers, keywords,
or literals (integer, floats, characters, strings). Whitespace and
comments are skipped.

The parser itself operates by pattern-matching on the stream of
tokens. As usual with recursive descent parsers, we use several
intermediate parsing functions to reflect the precedence and
associativity of operators. Pattern-matching over streams is more
powerful than on regular data structures, as it allows recursive calls
to parsing functions inside the patterns, for matching sub-components of
the input stream. See the Camlp4 documentation for more details.

Answer: the generic lexer provided by Genlex recognizes negative
integer literals as one integer token. Hence, x-1 is read as
the token Ident "x" followed by the token Int(-1); this sequence
does not match any of the parser rules. On the other hand,
the second space in x - 1 causes the lexer to return the three
expected tokens: Ident "x", then Kwd "-", then Int(1).

All examples given so far were executed under the interactive system.
Caml code can also be compiled separately and executed
non-interactively using the batch compilers ocamlc or ocamlopt.
The source code must be put in a file with extension .ml. It
consists of a sequence of phrases, which will be evaluated at runtime
in their order of appearance in the source file. Unlike in interactive
mode, types and values are not printed automatically; the program must
call printing functions explicitly to produce some output. Here is a
sample standalone program to print Fibonacci numbers:

Sys.argv is an array of strings containing the command-line
parameters. Sys.argv.(1) is thus the first command-line parameter.
The program above is compiled and executed with the following shell
commands:

A primary motivation for modules is to package together related
definitions (such as the definitions of a data type and associated
operations over that type) and enforce a consistent naming scheme for
these definitions. This avoids running out of names or accidentally
confusing names. Such a package is called a structure and
is introduced by the struct...end construct, which contains an
arbitrary sequence of definitions. The structure is usually given a
name with the module binding. Here is for instance a structure
packaging together a type of priority queues and their operations:

Outside the structure, its components can be referred to using the
``dot notation'', that is, identifiers qualified by a structure name.
For instance, PrioQueue.insert in a value context is
the function insert defined inside the structure
PrioQueue. Similarly, PrioQueue.queue in a type context is the
type queue defined in PrioQueue.

Signatures are interfaces for structures. A signature specifies
which components of a structure are accessible from the outside, and
with which type. It can be used to hide some components of a structure
(e.g. local function definitions) or export some components with a
restricted type. For instance, the signature below specifies the three
priority queue operations empty, insert and extract, but not the
auxiliary function remove_top. Similarly, it makes the queue type
abstract (by not providing its actual representation as a concrete type).

Restricting the PrioQueue structure by this signature results in
another view of the PrioQueue structure where the remove_top
function is not accessible and the actual representation of priority
queues is hidden:

Functors are ``functions'' from structures to structures. They are used to
express parameterized structures: a structure A parameterized by a
structure B is simply a functor F with a formal parameter
B (along with the expected signature for B) which returns
the actual structure A itself. The functor F can then be
applied to one or several implementations B1 ...Bn
of B, yielding the corresponding structures
A1 ...An.

For instance, here is a structure implementing sets as sorted lists,
parameterized by a structure providing the type of the set elements
and an ordering function over this type (used to keep the sets
sorted):

As in the PrioQueue example, it would be good style to hide the
actual implementation of the type set, so that users of the
structure will not rely on sets being lists, and we can switch later
to another, more efficient representation of sets without breaking
their code. This can be achieved by restricting Set by a suitable
functor signature:

The problem here is that SET specifies the type element
abstractly, so that the type equality between element in the result
of the functor and t in its argument is forgotten. Consequently,
WrongStringSet.element is not the same type as string, and the
operations of WrongStringSet cannot be applied to strings.
As demonstrated above, it is important that the type element in the
signature SET be declared equal to Elt.t; unfortunately, this is
impossible above since SET is defined in a context where Elt does
not exist. To overcome this difficulty, Objective Caml provides a
with type construct over signatures that allows to enrich a signature
with extra type equalities:

Abstracting a type component in a functor result is a powerful
technique that provides a high degree of type safety, as we now
illustrate. Consider an ordering over character strings that is
different from the standard ordering implemented in the
OrderedString structure. For instance, we compare strings without
distinguishing upper and lower case.

Notice that the two types AbstractStringSet.set and
NoCaseStringSet.set are not compatible, and values of these
two types do not match. This is the correct behavior: even though both
set types contain elements of the same type (strings), both are built
upon different orderings of that type, and different invariants need
to be maintained by the operations (being strictly increasing for the
standard ordering and for the case-insensitive ordering). Applying
operations from AbstractStringSet to values of type
NoCaseStringSet.set could give incorrect results, or build
lists that violate the invariants of NoCaseStringSet.

All examples of modules so far have been given in the context of the
interactive system. However, modules are most useful for large,
batch-compiled programs. For these programs, it is a practical
necessity to split the source into several files, called compilation
units, that can be compiled separately, thus minimizing recompilation
after changes.

In Objective Caml, compilation units are special cases of structures
and signatures, and the relationship between the units can be
explained easily in terms of the module system. A compilation unit A
comprises two files:

the implementation file A.ml, which contains a sequence
of definitions, analogous to the inside of a struct...end
construct;

the interface file A.mli, which contains a sequence of
specifications, analogous to the inside of a sig...end
construct.

Both files define a structure named A as if
the following definition was entered at top-level:

The files defining the compilation units can be compiled separately
using the ocamlc -c command (the -c option means ``compile only, do
not try to link''); this produces compiled interface files (with
extension .cmi) and compiled object code files (with extension
.cmo). When all units have been compiled, their .cmo files are
linked together using the ocaml command. For instance, the following
commands compile and link a program composed of two compilation units
Aux and Main:

In particular, Main can refer to Aux: the definitions and
declarations contained in Main.ml and Main.mli can refer to
definition in Aux.ml, using the Aux.ident notation, provided
these definitions are exported in Aux.mli.

The order in which the .cmo files are given to ocaml during the
linking phase determines the order in which the module definitions
occur. Hence, in the example above, Aux appears first and Main can
refer to it, but Aux cannot refer to Main.

Notice that only top-level structures can be mapped to
separately-compiled files, but not functors nor module types.
However, all module-class objects can appear as components of a
structure, so the solution is to put the functor or module type
inside a structure, which can then be mapped to a file.

The class point below defines one instance variable x and two methods
get_x and move. The initial value of the instance variable is 0.
The variable x is declared mutable, so the method move can change
its value.

Note that the type of p is point. This is an abbreviation
automatically defined by the class definition above. It stands for the
object type <get_x : int; move : int -> unit>, listing the methods
of class point along with their types.

The evaluation of the body of a class only takes place at object
creation time. Therefore, in the following example, the instance
variable x is initialized to different values for two different
objects.

The parameter x_init is, of course, visible in the whole body of the
definition, including methods. For instance, the method get_offset
in the class below returns the position of the object relative to its
initial position.

Expressions can be evaluated and bound before defining the object body
of the class. This is useful to enforce invariants. For instance,
points can be automatically adjusted to the nearest point on a grid,
as follows:

However, the former pattern is generally more appropriate, since
the code for adjustment is part of the definition of the class and will be
inherited.

This ability provides class constructors as can be found in other
languages. Several constructors can be defined this way to build objects of
the same class but with different initialization patterns; an
alternative is to use initializers, as decribed below in section
3.4.

There is another, more direct way to create an object: create it
without going through a class.

The syntax is exactly the same as for class expressions, but the
result is a single object rather than a class. All the constructs
described in the rest of this section also apply to immediate objects.

Immediate objects have two weaknesses compared to classes: their types
are not abbreviated, and you cannot inherit from them. But these two
weaknesses can be advantages in some situations, as we will see
in sections 3.3 and 3.10.

A method or an initializer can send messages to self (that is,
the current object). For that, self must be explicitly bound, here to
the variable s (s could be any identifier, even though we will
often choose the name self.)

You can ignore the first two lines of the error message. What matters
is the last one: putting self into an external reference would make it
impossible to extend it afterwards.
We will see in section 3.12 a workaround to this
problem.
Note however that, since immediate objects are not extensible, the
problem does not occur with them.

Let-bindings within class definitions are evaluated before the object
is constructed. It is also possible to evaluate an expression
immediately after the object has been built. Such code is written as
an anonymous hidden method called an initializer. Therefore, is can
access self and the instance variables.

It is possible to declare a method without actually defining it, using
the keyword virtual. This method will be provided later in
subclasses. A class containing virtual methods must be flagged
virtual, and cannot be instantiated (that is, no object of this class
can be created). It still defines type abbreviations (treating virtual methods
as other methods.)

The annotation virtual here is only used to mention a method without
providing its definition. Since we didn't add the private
annotation, this makes the method public, keeping the original
definition.

The constraint on self's type is requiring a public move method, and
this is sufficient to override private.

One could think that a private method should remain private in a subclass.
However, since the method is visible in a subclass, it is always possible
to pick its code and define a method of the same name that runs that
code, so yet another (heavier) solution would be:

In addition to program documentation, class interfaces can be used to
constrain the type of a class. Both instance variables and concrete
private methods can be hidden by a class type constraint. Public and
virtual methods, however, cannot.

We illustrate inheritance by defining a class of colored points that
inherits from the class of points. This class has all instance
variables and all methods of class point, plus a new instance
variable c and a new method color.

A point and a colored point have incompatible types, since a point has
no method color. However, the function get_x below is a generic
function applying method get_x to any object p that has this
method (and possibly some others, which are represented by an ellipsis
in the type). Thus, it applies to both points and colored points.

Multiple inheritance is allowed. Only the last definition of a method
is kept: the redefinition in a subclass of a method that was visible in
the parent class overrides the definition in the parent class.
Previous definitions of a method can be reused by binding the related
ancestor. Below, super is bound to the ancestor printable_point.
The name super is a pseudo value identifier that can only be used to
invoke a super-class method, as in super#print.

A private method that has been hidden in the parent class is no longer
visible, and is thus not overridden. Since initializers are treated as
private methods, all initializers along the class hierarchy are evaluated,
in the order they are introduced.

The reason is that at least one of the methods has a polymorphic type
(here, the type of the value stored in the reference cell), thus
either the class should be parametric, or the method type should be
constrained to a monomorphic type. A monomorphic instance of the class could
be defined by:

On the other hand, a class for polymorphic references must explicitly
list the type parameters in its declaration. Class type parameters are
always listed between [ and ]. The type parameters must also be
bound somewhere in the class body by a type constraint.

Let us consider a more complex example: define a circle, whose center
may be any kind of point. We put an additional type
constraint in method move, since no free variables must remain
unaccounted for by the class type parameters.

An alternate definition of circle, using a constraint clause in
the class definition, is shown below. The type #point used below in
the constraint clause is an abbreviation produced by the definition
of class point. This abbreviation unifies with the type of any
object belonging to a subclass of class point. It actually expands to
< get_x : int; move : int -> unit; .. >. This leads to the following
alternate definition of circle, which has slightly stronger
constraints on its argument, as we now expect center to have a
method get_x.

The class colored_circle is a specialized version of class
circle that requires the type of the center to unify with
#colored_point, and adds a method color. Note that when specializing a
parameterized class, the instance of type parameter must always be
explicitly given. It is again written between [ and ].

Our iterator works, as shows its first use for summation. However,
since objects themselves are not polymorphic (only their constructors
are), using the fold method fixes its type for this individual object.
Our next attempt to use it as a string iterator fails.

The problem here is that quantification was wrongly located: this is
not the class we want to be polymorphic, but the fold method.
This can be achieved by giving an explicitly polymorphic type in the
method definition.

As you can see in the class type shown by the compiler, while
polymorphic method types must be fully explicit in class definitions
(appearing immediately after the method name), they can be left
implicit in class descriptions.

However, the type can be completely omitted in the class definition if
it is already known, through inheritance or type constraints on self.
Here is an example of method overriding.

Polymorphic methods are called in exactly the same way as normal
methods, but you should be aware of some limitations of type
inference. Namely, a polymorphic method can only be called if its
type is known at the call site. Otherwise, the method will be assumed
to be monomorphic, and given an incompatible type.

Another use of polymorphic methods is to allow some form of implicit
subtyping in method arguments. We have already seen in section
3.8 how some functions may be polymorphic in the
class of their argument. This can be extended to methods.

Note here the special syntax (#point0 as 'a) we have to use to
quantify the extensible part of #point0. As for the variable binder,
it can be omitted in class specifications. If you want polymorphism
inside object field it must be quantified independently.

Indeed, narrowing coercions would be unsafe, and could only be combined with
a type case, possibly raising a runtime error. However, there is no such
operation available in the language.

Be aware that subtyping and inheritance are not related. Inheritance is a
syntactic relation between classes while subtyping is a semantic relation
between types. For instance, the class of colored points could have been
defined directly, without inheriting from the class of points; the type of
colored points would remain unchanged and thus still be a subtype of
points.

The domain of a coercion can usually be omitted. For instance, one can
define:

In this case, the function colored_point_to_point is an instance of the
function to_point. This is not always true, however. The fully
explicit coercion is more precise and is sometimes unavoidable.
Consider, for example, the following class:

While class types c1 and c2 are different, both object types
c1 and c2 expand to the same object type (same method names and types).
Yet, when the domain of a coercion is left implicit and its co-domain
is an abbreviation of a known class type, then the class type, rather
than the object type, is used to derive the coercion function. This
allows to leave the domain implicit in most cases when coercing form a
subclass to its superclass.
The type of a coercion can always be seen as below:

Note the difference between the two coercions: in the second case, the type
#c2 = < m : 'a; .. > as 'a is polymorphically recursive (according
to the explicit recursion in the class type of c2); hence the
success of applying this coercion to an object of class c0.
On the other hand, in the first case, c1 was only expanded and
unrolled twice to obtain < m : < m : c1; .. >; .. > (remember #c1 = < m : c1; .. >), without introducing recursion.
You may also note that the type of to_c2 is #c2 -> c2 while
the type of to_c1 is more general than #c1 -> c1. This is not always true,
since there are class types for which some instances of #c are not subtypes
of c, as explained in section 3.16. Yet, for
parameterless classes the coercion (_ :> c) is always more general than
(_ : #c :> c).

A common problem may occur when one tries to define a coercion to a
class c while defining class c. The problem is due to the type
abbreviation not being completely defined yet, and so its subtypes are not
clearly known. Then, a coercion (_ :> c) or (_ : #c :> c) is taken to be
the identity function, as in

#function x -> (x :> 'a);;
- : 'a -> 'a = <fun>

As a consequence, if the coercion is applied to self, as in the
following example, the type of self is unified with the closed type
c (a closed object type is an object type without ellipsis). This
would constrain the type of self be closed and is thus rejected.
Indeed, the type of self cannot be closed: this would prevent any
further extension of the class. Therefore, a type error is generated
when the unification of this type with another type would result in a
closed object type.

However, the abbreviation #c' cannot be defined directly in a similar way.
It can only be defined by a class or a class-type definition.
This is because # sharp abbreviations carry an implicit anonymous
variable .. that cannot be explicitly named.
The closer you get to it is:

It is possible to write a version of class point without assignments
on the instance variables. The construct {< ... >} returns a copy of
``self'' (that is, the current object), possibly changing the value of
some instance variables.

While objects of either class will behave the same, objects of their
subclasses will be different. In a subclass of the latter, the method
move will
keep returning an object of the parent class. On the contrary, in a
subclass of the former, the method move will return an object of the
subclass.

Functional update is often used in conjunction with binary methods
as illustrated in section 5.2.1.

Objects can also be cloned, whether they are functional or imperative.
The library function Oo.copy makes a shallow copy of an object. That is,
it returns an object that is equal to the previous one. The
instance variables have been copied but their contents are shared.
Assigning a new value to an instance variable of the copy (using a method
call) will not affect instance variables of the original, and conversely.
A deeper assignment (for example if the instance variable if a reference cell)
will of course affect both the original and the copy.

The type of Oo.copy is the following:

#Oo.copy;;
- : (< .. > as 'a) -> 'a = <fun>

The keyword as in that type binds the type variable 'a to
the object type < .. >. Therefore, Oo.copy takes an object with
any methods (represented by the ellipsis), and returns an object of
the same type. The type of Oo.copy is different from type < .. > -> < .. > as each ellipsis represents a different set of methods.
Ellipsis actually behaves as a type variable.

Other generic comparissons such as (<, <=,...) can also be used on objects. The
relation < defines an unspecified but strict ordering on objets. The
ordering relationship between two objects is fixed once for all after the
two objects have been created and it is not affected by mutation of fields.

Cloning and override have a non empty intersection.
They are interchangeable when used within an object and without
overriding any field:

A binary method is a method which takes an argument of the same type
as self. The class comparable below is a template for classes with a
binary method leq of type 'a -> bool where the type variable 'a
is bound to the type of self. Therefore, #comparable expands to < leq : 'a -> bool; .. > as 'a. We see here that the binder as also
allows to write recursive types.

We then define a subclass money of comparable. The class money
simply wraps floats as comparable objects. We will extend it below with
more operations. There is a type constraint on the class parameter x
as the primitive <= is a polymorphic comparison function in
Objective Caml. The inherit clause ensures that the type of objects
of this class is an instance of #comparable.

Note that the type money1 is not a subtype of type
comparable, as the self type appears in contravariant position
in the type of method leq.
Indeed, an object m of class money has a method leq
that expects an argument of type money since it accesses
its value method. Considering m of type comparable would allow to
call method leq on m with an argument that does not have a method
value, which would be an error.

It is however possible to define functions that manipulate objects of
type either money or money2: the function min
will return the minimum of any two objects whose type unifies with
#comparable. The type of min is not the same as #comparable -> #comparable -> #comparable, as the abbreviation #comparable hides a
type variable (an ellipsis). Each occurrence of this abbreviation
generates a new variable.

More examples of binary methods can be found in sections
5.2.1 and 5.2.3.

Notice the use of functional update for method times.
Writing new money2 (k *. repr) instead of {< repr = k *. repr >}
would not behave well with inheritance: in a subclass money3 of money2
the times method would return an object of class money2 but not of class
money3 as would be expected.

The class money could naturally carry another binary method. Here is a
direct definition:

The above class money reveals a problem that often occurs with binary
methods. In order to interact with other objects of the same class, the
representation of money objects must be revealed, using a method such as
value. If we remove all binary methods (here plus and leq),
the representation can easily be hidden inside objects by removing the method
value as well. However, this is not possible as long as some binary
requires access to the representation on object of the same class but
different from self.

Here, the representation of the object is known only to a particular object.
To make it available to other objects of the same class, we are forced to
make it available to the whole world. However we can easily restrict the
visibility of the representation using the module system.

Another example of friend functions may be found in section
5.2.3. These examples occur when a group of objects (here
objects of the same class) and functions should see each others internal
representation, while their representation should be hidden from the
outside. The solution is always to define all friends in the same module,
give access to the representation and use a signature constraint to make the
representation abstract outside of the module.

Such annotations of the form name: are called labels. They are
meant to document the code, allow more checking, and give more
flexibility to function application.
You can give such names to arguments in your programs, by prefixing them
with a tilde ~.

Labels obey the same rules as other identifiers in Caml, that is you
cannot use a reserved keyword (like in or to) as label.

Formal parameters and arguments are matched according to their
respective labels1, the absence of label
being interpreted as the empty label.
This allows commuting arguments in applications. One can also
partially apply a function on any argument, creating a new function of
the remaining parameters.

An interesting feature of labeled arguments is that they can be made
optional. For optional parameters, the question mark ? replaces the
tilde ~ of non-optional ones, and the label is also prefixed by ?
in the function type.
Default values may be given for such optional parameters.

A function taking some optional arguments must also take at least one
non-labeled argument. This is because the criterion for deciding
whether an optional has been omitted is the application on a
non-labeled argument appearing after this optional argument in the
function type.

Optional parameters may also commute with non-optional or unlabelled
ones, as long as they are applied simultaneously. By nature, optional
arguments do not commute with unlabeled arguments applied
independently.

Optional arguments are actually implemented as option types. If
you do not give a default value, you have access to their internal
representation, type 'a option = None | Some of 'a. You can then
provide different behaviors when an argument is present or not.

It may also be useful to relay an optional argument from a function
call to another. This can be done by prefixing the applied argument
with ?. This question mark disables the wrapping of optional
argument in an option type.

The first case is simple: g is passed ~y and then ~x, but f
expects ~x and then ~y. This is correctly handled if we know the
type of g to be x:int -> y:int -> int in advance, but otherwise
this causes the above type clash. The simplest workaround is to apply
formal parameters in a standard order.

The second example is more subtle: while we intended the argument
bump to be of type ?step:int -> int -> int, it is inferred as
step:int -> int -> 'a.
These two types being incompatible (internally normal and optional
arguments are different), a type error occurs when applying bump_it
to the real bump.

We will not try here to explain in detail how type inference works.
One must just understand that there is not enough information in the
above program to deduce the correct type of g or bump. That is,
there is no way to know whether an argument is optional or not, or
which is the correct order, by looking only at how a function is
applied. The strategy used by the compiler is to assume that there are
no optional arguments, and that applications are done in the right
order.

The right way to solve this problem for optional parameters is to add
a type annotation to the argument bump.

In practive, such problems appear mostly when using objects whose
methods have optional arguments, so that writing the type of object
arguments is often a good idea.

Normally the compiler generates a type error if you attempt to pass to
a function a parameter whose type is different from the expected one.
However, in the specific case where the expected type is a non-labeled
function type, and the argument is a function expecting optional
parameters, the compiler will attempt to transform the argument to
have it match the expected type, by passing None for all optional
parameters.

This transformation is coherent with the intended semantics,
including side-effects. That is, if the application of optional
parameters shall produce side-effects, these are delayed until the
received function is really applied to an argument.

Like for names, choosing labels for functions is not an easy task. A
good labeling is a labeling which

makes programs more readable,

is easy to remember,

when possible, allows useful partial applications.

We explain here the rules we applied when labeling Objective Caml
libraries.

To speak in an ``object-oriented'' way, one can consider that each
function has a main argument, its object, and other arguments
related with its action, the parameters. To permit the
combination of functions through functionals in commuting label mode, the
object will not be labeled. Its role is clear by the function
itself. The parameters are labeled with names reminding either of
their nature or role. Best labels combine in their meaning nature and
role. When this is not possible the role is to prefer, since the nature will
often be given by the type itself. Obscure abbreviations should be
avoided.

This principle also applies to functions of several arguments whose
return type is a type variable, as long as the role of each argument
is not ambiguous. Labeling such functions may lead to awkward error
messages when one attempts to omit labels in an application, as we
have seen with ListLabels.fold_left.

Here are some of the label names you will find throughout the
libraries.

Label

Meaning

f:

a function to be applied

pos:

a position in a string or array

len:

a length

buf:

a string used as buffer

src:

the source of an operation

dst:

the destination of an operation

init:

the initial value for an iterator

cmp:

a comparison function, e.g.Pervasives.compare

mode:

an operation mode or a flag list

All these are only suggestions, but one shall keep in mind that the
choice of labels is essential for readability. Bizarre choices will
make the program harder to maintain.

In the ideal, the right function name with right labels shall be
enough to understand the function's meaning. Since one can get this
information with OCamlBrowser or the ocaml toplevel, the documentation
is only used when a more detailed specification is needed.

Variants as presented in section 1.4 are a
powerful tool to build data structures and algorithms. However they
sometimes lack flexibility when used in modular programming. This is
due to the fact every constructor reserves a name to be used with a
unique type. On cannot use the same name in another type, or consider
a value of some type to belong to some other type with more
constructors.

With polymorphic variants, this original assumption is removed. That
is, a variant tag does not belong to any type in particular, the type
system will just check that it is an admissible value according to its
use. You need not define a type before using a variant tag. A variant
type will be inferred independently for each of its uses.

Basic use

In programs, polymorphic variants work like usual ones. You just have
to prefix their names with a backquote character `.

[>`Off|`On] list means that to match this list, you should at
least be able to match `Off and `On, without argument.
[<`On|`Off|`Number of int] means that f may be applied to `Off,
`On (both without argument), or `Numbern where
n is an integer.
The > and < inside the variant type shows that they may still be
refined, either by defining more tags or allowing less. As such they
contain an implicit type variable. Both variant types appearing only
once in the type, the implicit type variables they constrain are not
shown.

The above variant types were polymorphic, allowing further refinement.
When writing type annotations, one will most often describe fixed
variant types, that is types that can be no longer refined. This is
also the case for type abbreviations. Such types do not contain < or
>, but just an enumeration of the tags and their associated types,
just like in a normal datatype definition.

Here we are seeing two phenomena. First, since this matching is open
(the last case catches any tag), we obtain the type [> `A | `B]
rather than [< `A | `B] in a closed matching. Then, since x is
returned as is, input and return types are identical. The notation as 'a denotes such type sharing. If we apply f to yet another tag
`E, it gets added to the list.

Here f1 and f2 both accept the variant tags `A and `B, but the
argument of `A is int for f1 and string for f2. In f's
type `C, only accepted by f1, disappears, but both argument types
appear for `A as int & string. This means that if we
pass the variant tag `A to f, its argument should be bothint and string. Since there is no such value, f cannot be
applied to `A, and `B is the only accepted input.

Even if a value has a fixed variant type, one can still give it a
larger type through coercions. Coercions are normally written with
both the source type and the destination type, but in simple cases the
source type may be omitted.

When an or-pattern composed of variant tags is wrapped inside an
alias-pattern, the alias is given a type containing only the tags
enumerated in the or-pattern. This allows for many useful idioms, like
incremental definition of functions.

To make this even more confortable, you may use type definitions as
abbreviations for or-patterns. That is, if you have defined type myvariant = [`Tag1 int | `Tag2 bool], then the pattern #myvariant is
equivalent to writing (`Tag1(_ : int) | `Tag2(_ : bool)).

After seeing the power of polymorphic variants, one may wonder why
they were added to core language variants, rather than replacing them.

The answer is two fold. One first aspect is that while being pretty
efficient, the lack of static type information allows for less
optimizations, and makes polymorphic variants slightly heavier than
core language ones. However noticeable differences would only
appear on huge data structures.

More important is the fact that polymorphic variants, while being
type-safe, result in a weaker type discipline. That is, core language
variants do actually much more than ensuring type-safety, they also
check that you use only declared constructors, that all constructors
present in a data-structure are compatible, and they enforce typing
constraints to their parameters.

For this reason, you must be more careful about making types explicit
when you use polymorphic variants. When you write a library, this is
easy since you can describe exact types in interfaces, but for simple
programs you are probably better off with core language variants.

Beware also that certain idioms make trivial errors very hard to find.
For instance, the following code is probably wrong but the compiler
has no way to see it.

This correspond to the commuting label mode
of Objective Caml 3.00 through 3.02, with some additional flexibility
on total applications. The so-called classic mode (-nolabels
options) is now deprecated for normal use.

In this chapter, we show some larger examples using objects, classes
and modules. We review many of the object features simultaneously on
the example of a bank account. We show how modules taken from the
standard library can be expressed as classes. Lastly, we describe a
programming pattern know of as virtual types through the example
of window managers.

In this section, we illustrate most aspects of Object and inheritance
by refining, debugging, and specializing the following
initial naive definition of a simple bank account. (We reuse the
module Euro defined at the end of chapter 3.)

We make the method interest private, since clearly it should not be
called freely from the outside. Here, it is only made accessible to subclasses
that will manage monthly or yearly updates of the account.

We should soon fix a bug in the current definition: the deposit method can
be used for withdrawing money by depositing negative amounts. We can
fix this directly:

This shows the use of modules to group several class definitions that can in
fact be thought of as a single unit. This unit would be provided by a bank
for both internal and external uses.
This is implemented as a functor that abstracts over the currency so that
the same code can be used to provide accounts in different currencies.

The class bank is the real implementation of the bank account (it
could have been inlined). This is the one that will be used for further
extensions, refinements, etc. Conversely, the client will only be given the client view.

Hence, the clients do not have direct access to the balance, nor the
history of their own accounts. Their only way to change their balance is
to deposit or withdraw money. It is important to give the clients
a class and not just the ability to create accounts (such as the
promotional discount account), so that they can
personalize their account.
For instance, a client may refine the deposit and withdraw methods
so as to do his own financial bookkeeping, automatically. On the
other hand, the function discount is given as such, with no
possibility for further personalization.

It is important that to provide the client's view as a functor
Client so that client accounts can still be build after a possible
specialization of the bank.
The functor Client may remain unchanged and be passed
the new definition to initialize a client's view of the extended account.

One may wonder whether it is possible to treat primitive types such as
integers and strings as objects. Although this is usually uninteresting
for integers or strings, there may be some situations where
this is desirable. The class money above is such an example.
We show here how to do it for strings.

However, the method copy returns an object of the class string,
and not an objet of the current class. Hence, if the class is further
extended, the method copy will only return an object of the parent
class.

As shown in the inferred type, the methods copy and sub now return
objects of the same type as the one of the class.

Another difficulty is the implementation of the method concat.
In order to concatenate a string with another string of the same class,
one must be able to access the instance variable externally. Thus, a method
repr returning s must be defined. Here is the correct definition of
strings:

Here, exposing the representation of strings is probably harmless. We do
could also hide the representation of strings as we hid the currency in the
class money of section 3.17.

Stacks

There is sometimes an alternative between using modules or classes for
parametric data types.
Indeed, there are situations when the two approaches are quite similar.
For instance, a stack can be straightforwardly implemented as a class:

However, writing a method for iterating over a stack is more
problematic. A method fold would have type
('b -> 'a -> 'b) -> 'b -> 'b. Here 'a is the parameter of the stack.
The parameter 'b is not related to the class 'a stack but to the
argument that will be passed to the method fold.
A naive approach is to make 'b an extra parameter of class stack:

A better solution is to use polymorphic methods, which were
introduced in Objective Caml version 3.05. Polymorphic methods makes
it possible to treat the type variable 'b in the type of fold as
universally quantified, giving fold the polymorphic type
Forall 'b. ('b -> 'a -> 'b) -> 'b -> 'b.
An explicit type declaration on the method fold is required, since
the type checker cannot infer the polymorphic type by itself.

Implementing sets leads to another difficulty. Indeed, the method
union needs to be able to access the internal representation of
another object of the same class.

This is another instance of friend functions as seen in section
3.17. Indeed, this is the same mechanism used in the module
Set in the absence of objects.

In the object-oriented version of sets, we only need to add an additional
method tag to return the representation of a set. Since sets are
parametric in the type of elements, the method tag has a parametric type
'a tag, concrete within
the module definition but abstract in its signature.
From outside, it will then be guaranteed that two objects with a method tag
of the same type will share the same representation.

The following example, known as the subject/observer pattern, is often
presented in the literature as a difficult inheritance problem with
inter-connected classes.
The general pattern amounts to the definition a pair of two
classes that recursively interact with one another.

The class observer has a distinguished method notify that requires
two arguments, a subject and an event to execute an action.

The difficulty usually relies in defining instances of the pattern above
by inheritance. This can be done in a natural and obvious manner in
Ocaml, as shown on the following example manipulating windows.

This document is intended as a reference manual for the Objective Caml
language. It lists the language constructs, and gives their precise
syntax and informal semantics. It is by no means a tutorial
introduction to the language: there is not a single example. A good
working knowledge of Caml is assumed.

No attempt has been made at mathematical rigor: words are employed
with their intuitive meaning, without further definition. As a
consequence, the typing rules have been left out, by lack of the
mathematical framework required to express them, while they are
definitely part of a full formal definition of the language.

Notations

The syntax of the language is given in BNF-like notation. Terminal
symbols are set in typewriter font (likethis).
Non-terminal symbols are set in italic font (likethat).
Square brackets [...] denote optional components. Curly brackets
{...} denotes zero, one or several repetitions of the enclosed
components. Curly bracket with a trailing plus sign {...}+
denote one or several repetitions of the enclosed components.
Parentheses (...) denote grouping.

The following characters are considered as blanks: space, newline,
horizontal tabulation, carriage return, line feed and form feed. Blanks are
ignored, but they separate adjacent identifiers, literals and
keywords that would otherwise be confused as one single identifier,
literal or keyword.

Comments

Comments are introduced by the two characters (*, with no
intervening blanks, and terminated by the characters *), with
no intervening blanks. Comments are treated as blank characters.
Comments do not occur inside string or character literals. Nested
comments are handled correctly.

Identifiers

ident

::=

(letter| _) { letter| 0...9| _| ' }

letter

::=

A ... Z | a ... z

Identifiers are sequences of letters, digits, _ (the underscore
character), and ' (the single quote), starting with a
letter or an underscore.
Letters contain at least the 52 lowercase and uppercase
letters from the ASCII set. The current implementation (except on
MacOS 9) also recognizes as letters all accented characters from the ISO
8859-1 (``ISO Latin 1'') set. All characters in an identifier are
meaningful. The current implementation accepts identifiers up to
16000000 characters in length.

Integer literals

integer-literal

::=

[-] (0...9) { 0...9| _ }

|

[-] (0x| 0X) (0...9| A...F| a...f)
{ 0...9| A...F| a...f| _ }

|

[-] (0o| 0O) (0...7) { 0...7| _ }

|

[-] (0b| 0B) (0...1) { 0...1| _ }

An integer literal is a sequence of one or more digits, optionally
preceded by a minus sign. By default, integer literals are in decimal
(radix 10). The following prefixes select a different radix:

Prefix

Radix

0x, 0X

hexadecimal (radix 16)

0o, 0O

octal (radix 8)

0b, 0B

binary (radix 2)

(The initial 0 is the digit zero; the O for octal is the letter O.)
The interpretation of integer literals that fall outside the range of
representable integer values is undefined.

Floating-point decimals consist in an integer part, a decimal part and
an exponent part. The integer part is a sequence of one or more
digits, optionally preceded by a minus sign. The decimal part is a
decimal point followed by zero, one or more digits.
The exponent part is the character e or E followed by an
optional + or - sign, followed by one or more digits.
The decimal part or the exponent part can be omitted, but not both to
avoid ambiguity with integer literals.
The interpretation of floating-point literals that fall outside the
range of representable floating-point values is undefined.

Character literals are delimited by ' (single quote) characters.
The two single quotes enclose either one character different from
' and \, or one of the escape sequences below:

Sequence

Character denoted

\\

backslash (\)

\"

double quote (")

\'

single quote (')

\n

linefeed (LF)

\r

carriage return (CR)

\t

horizontal tabulation (TAB)

\b

backspace (BS)

\ddd

the character with ASCII code ddd in decimal

\xhh

the character with ASCII code hh in hexadecimal

String literals

string-literal

::=

" { string-character } "

string-character

::=

regular-char-str

|

escape-sequence

String literals are delimited by " (double quote) characters.
The two double quotes enclose a sequence of either characters
different from " and \, or escape sequences from the
table given above for character literals.

To allow splitting long string literals across lines, the sequence
\newline blanks (a \ at end-of-line followed by any
number of blanks at the beginning of the next line) is ignored inside
string literals.

The current implementation places practically no restrictions on the
length of string literals.

Naming labels

To avoid ambiguities, naming labels cannot just be defined
syntactically as the sequence of the three tokens ~, ident and
:, and have to be defined at the lexical level.

label

::=

~ (a ... z) { letter| 0...9| _| ' } :

optlabel

::=

? (a ... z) { letter| 0...9| _| ' } :

Naming labels come in two flavours: label for normal arguments and
optlabel for optional ones. They are simply distinguished by their
first character, either ~ or ?.

Prefix and infix symbols

infix-symbol

::=

(= | < | > | @ | ^ | | | & |
+ | - | * | / | $ | %) { operator-char }

prefix-symbol

::=

(! | ? | ~) { operator-char }

operator-char

::=

! | $ | % | & | * | + | - | . |
/ | : | < | = | > | ? | @ |
^ | | | ~

Sequences of ``operator characters'', such as <=> or !!,
are read as a single token from the infix-symbol or prefix-symbol
class. These symbols are parsed as prefix and infix operators inside
expressions, but otherwise behave much as identifiers.

Keywords

The identifiers below are reserved as keywords, and cannot be employed
otherwise:

and as assert asr begin class
constraint do done downto else end
exception external false for fun function
functor if in include inherit initializer
land lazy let lor lsl lsr
lxor match method mod module mutable
new object of open or private
rec sig struct then to true
try type val virtual when while
with

Note that the following identifiers are keywords of the Camlp4
extensions and should be avoided for compatibility reasons.

parser << <: >> $ $$ $:

Ambiguities

Lexical ambiguities are resolved according to the ``longest match''
rule: when a character sequence can be decomposed into two tokens in
several different ways, the decomposition retained is the one with the
longest first token.

Line number directives

linenum-directive

::=

# {0 ... 9}+

|

# {0 ... 9}+" { string-character } "

Preprocessors that generate Caml source code can insert line number
directives in their output so that error messages produced by the
compiler contain line numbers and file names referring to the source
file before preprocessing, instead of after preprocessing.
A line number directive is composed of a # (sharp sign), followed by
a positive integer (the source line number), optionally followed by a
character string (the source file name).
Line number directives are treated as blank characters during lexical
analysis.

Integer values are integer numbers from -230 to 230-1, that
is -1073741824 to 1073741823. The implementation may support a
wider range of integer values: on 64-bit platforms, the current
implementation supports integers ranging from -262 to 262-1.

Floating-point numbers

Floating-point values are numbers in floating-point representation.
The current implementation uses double-precision floating-point
numbers conforming to the IEEE 754 standard, with 53 bits of mantissa
and an exponent ranging from -1022 to 1023.

Characters

Character values are represented as 8-bit integers between 0 and 255.
Character codes between 0 and 127 are interpreted following the ASCII
standard. The current implementation interprets character codes
between 128 and 255 following the ISO 8859-1 standard.

Character strings

String values are finite sequences of characters. The current
implementation supports strings containing up to 224 - 5
characters (16777211 characters); on 64-bit platforms, the limit is
257 - 9.

Record values are labeled tuples of values. The record value written
{ field1 = v1; ...; fieldn = vn } associates the value
vi to the record field fieldi, for i = 1 ... n. The current
implementation supports records with up to 222 - 1 fields
(4194303 fields).

Arrays are finite, variable-sized sequences of values of the same
type. The current implementation supports arrays containing to
222 - 1 elements (4194303 elements); on 64-bit platforms, the
limit is 254 - 1

Variant values are either a constant constructor, or a pair of a
non-constant constructor and a value. The former case is written
constr; the latter case is written constr(v), where v is said
to be the argument of the non-constant constructor constr.

The following constants are treated like built-in constant
constructors:

Constant

Constructor

false

the boolean false

true

the boolean true

()

the ``unit'' value

[]

the empty list

The current implementation limits each variant type to have at most
246 non-constant constructors.

Polymorphic variants are an alternate form of variant values, not
belonging explicitly to a predefined variant type, and following
specific typing rules. They can be either constant, written
`tag-name, or non-constant, written `tag-name (v).

Objects are composed of a hidden internal state which is a
record of instance variables, and a set of methods for accessing and
modifying these variables. The structure of an object is described by
the toplevel class that created it.

Identifiers are used to give names to several classes of language
objects and refer to these objects by name later:

value names (syntactic class value-name),

value constructors and exception constructors (class constr-name),

labels (label-name),

variant tags (tag-name),

type constructors (typeconstr-name),

record fields (field-name),

class names (class-name),

method names (method-name),

instance variable names (inst-var-name),

module names (module-name),

module type names (modtype-name).

These eleven name spaces are distinguished both by the context and by the
capitalization of the identifier: whether the first letter of the
identifier is in lowercase (written lowercase-ident below) or in
uppercase (written capitalized-ident). Underscore is considered a
lowercase letter for this purpose.

Naming objects

value-name

::=

lowercase-ident

|

(operator-name)

operator-name

::=

prefix-symbol | infix-op

infix-op

::=

infix-symbol

|

* | = | or | & | :=

|

mod | land | lor | lxor | lsl | lsr | asr

constr-name

::=

capitalized-ident

label-name

::=

lowercase-ident

tag-name

::=

capitalized-ident

typeconstr-name

::=

lowercase-ident

field-name

::=

lowercase-ident

module-name

::=

capitalized-ident

modtype-name

::=

ident

class-name

::=

lowercase-ident

inst-var-name

::=

lowercase-ident

method-name

::=

lowercase-ident

As shown above, prefix and infix symbols as well as some keywords can
be used as value names, provided they are written between parentheses.
The capitalization rules are summarized in the table below.

Name space

Case of first letter

Values

lowercase

Constructors

uppercase

Labels

lowercase

Variant tags

uppercase

Exceptions

uppercase

Type constructors

lowercase

Record fields

lowercase

Classes

lowercase

Instance variables

lowercase

Methods

lowercase

Modules

uppercase

Module types

any

Note on variant tags: the current implementation accepts
lowercase variant tags in addition to uppercase variant tags, but we
suggest you avoid lowercase variant tags for portability and
compatibility with future OCaml versions.

Referring to named objects

value-path

::=

value-name

|

module-path.value-name

constr

::=

constr-name

|

module-path.constr-name

typeconstr

::=

typeconstr-name

|

extended-module-path.typeconstr-name

field

::=

field-name

|

module-path.field-name

module-path

::=

module-name

|

module-path.module-name

extended-module-path

::=

module-name

|

extended-module-path.module-name

|

extended-module-path(extended-module-path)

modtype-path

::=

modtype-name

|

extended-module-path.modtype-name

class-path

::=

class-name

|

module-path.class-name

A named object can be referred to either by its name (following the
usual static scoping rules for names) or by an access path prefix.name,
where prefix designates a module and name is the name of an object
defined in that module. The first component of the path, prefix, is
either a simple module name or an access path name1.name2 ...,
in case the defining module is itself nested inside other modules.
For referring to type constructors or module types, the prefix can
also contain simple functor applications (as in the syntactic class
extended-module-path above), in case the defining module is the
result of a functor application.

Label names, tag names, method names and instance variable names need
not be qualified: the former three are global labels, while the latter
are local to a class.

The table below shows the relative precedences and associativity of
operators and non-closed type constructions. The constructions with
higher precedences come first.

Operator

Associativity

Type constructor application

--

*

--

->

right

as

--

Type expressions denote types in definitions of data types as well as
in type constraints over patterns and expressions.

Type variables

The type expression 'ident stands for the type variable named
ident. The type expression _ stands for an anonymous type variable.
In data type definitions, type variables are names for the
data type parameters. In type constraints, they represent unspecified
types that can be instantiated by any type to satisfy the type
constraint. In general the scope of a named type variable is the
whole enclosing definition; they can only be generalized when leaving
this scope. Anonymous variables have no such restriction.

Parenthesized types

The type expression (typexpr) denotes the same type as
typexpr.

Function types

The type expression typexpr1->typexpr2 denotes the type of
functions mapping arguments of type typexpr1 to results of type
typexpr2.

label-name:typexpr1->typexpr2 denotes the same function type, but
the argument is labeled label.

optlabeltypexpr1->typexpr2 denotes the type of functions
mapping an optional labeled argument of type typexpr1 to results of
type typexpr2. That is, the physical type of the function will be
typexpr1option->typexpr2.

Type constructors with no parameter, as in typeconstr, are type
expressions.

The type expression typexprtypeconstr, where typeconstr is a type
constructor with one parameter, denotes the application of the unary type
constructor typeconstr to the type typexpr.

The type expression (typexpr1,..., typexprn) typeconstr, where
typeconstr is a type constructor with n parameters, denotes the
application of the n-ary type constructor typeconstr to the types
typexpr1 through typexprn.

Aliased and recursive types

The type expression typexpras'ident denotes the same type as
typexpr, and also binds the type variable ident to type typexpr both
in typexpr and in the remaining part of the type. If the type variable
ident actually occurs in typexpr, a recursive type is created. Recursive
types for which there exists a recursive path that does not contain
an object or variant type constructor are rejected, except when the
-rectypes mode is selected.

If 'ident denotes an explicit polymorphic variable, and typexpr
denotes either an object or variant type, the row variable of typexpr
is captured by 'ident, and quantified upon.

Variant types

variant-type

::=

[ [ | ] tag-spec { |tag-spec } ]

|

[> [ tag-spec ] { |tag-spec } ]

|

[< [ | ] tag-spec-full { |tag-spec-full } [ > { `tag-name }+ ] ]

tag-spec

::=

`tag-name [ oftypexpr ]

|

typexpr

tag-spec-full

::=

`tag-name [ oftypexpr ] { &typexpr }

|

typexpr

Variant types describe the values a polymorphic variant may take.

The first case is an exact variant type: all possible tags are
known, with their associated types, and they can all be present.
Its structure is fully known.

The second case is an open variant type, describing a polymorphic
variant value: it gives the list of all tags the value could take,
with their associated types. This type is still compatible with a
variant type containing more tags. A special case is the unknown
type, which does not define any tag, and is compatible with any
variant type.

The third case is a closed variant type. It gives information about
all the possible tags and their associated types, and which tags are
known to potentially appear in values. The above exact variant type is
just an abbreviation for a closed variant type where all possible tags
are also potentially present.

In all three cases, tags may be either specified directly in the
`tag-name [...] form, or indirectly through a type
expression. In this last case, the type expression must expand to an
exact variant type, whose tag specifications are inserted in its
place.

Full specification of variant tags are only used for non-exact closed
types. They can be understood as a conjunctive type for the argument:
it is intended to have all the types enumerated in the
specification.

Such conjunctive constraints may be unsatisfiable. In such a case the
corresponding tag may not be used in a value of this type. This
does not mean that the whole type is not valid: one can still use
other available tags.

Object types

An object type
<method-type { ;method-type } >
is a record of method types.

Each method may have an explicit polymorphic type: { 'ident }+.typexpr. Explicit polymorphic variables have a local scope, and
an explicit polymorphic type can only be unified to an
equivalent one, with polymorphic variables at the same positions.

The type <method-type { ;method-type } ;..> is the
type of an object with methods and their associated types are described by
method-type1, ..., method-typen, and possibly some other
methods represented by the ellipsis. This ellipsis actually is
a special kind of type variable (also called row variable in the
literature) that stands for any number of extra method types.

#-types

The type #class-path is a special kind of abbreviation. This
abbreviation unifies with the type of any object belonging to a subclass
of class class-path.
It is handled in a special way as it usually hides a type variable (an
ellipsis, representing the methods that may be added in a subclass).
In particular, it vanishes when the ellipsis gets instantiated.
Each type expression #class-path defines a new type variable, so
type #class-path->#class-path is usually not the same as
type (#class-pathas'ident) ->'ident.

Use of #-types to abbreviate variant types is deprecated.
If t is an exact variant type then #t translates to [< t],
and #t[>`tag1 ...`tagk] translates to
[<t>`tag1 ...`tagk]

Variant and record types

There are no type expressions describing (defined) variant types nor
record types, since those are always named, i.e. defined before use
and referred to by name. Type definitions are described in
section 6.8.1.

The syntactic class of constants comprises literals from the four
base types (integers, floating-point numbers, characters, character
strings), and constant constructors from both normal and polymorphic
variants, as well as the special constants false, true, [],
and (), which behave like constant constructors.

The table below shows the relative precedences and associativity of
operators and non-closed pattern constructions. The constructions with
higher precedences come first.

Operator

Associativity

Constructor application

--

::

right

,

--

|

left

as

--

Patterns are templates that allow selecting data structures of a
given shape, and binding identifiers to components of the data
structure. This selection operation is called pattern matching; its
outcome is either ``this value does not match this pattern'', or
``this value matches this pattern, resulting in the following bindings
of names to values''.

Variable patterns

A pattern that consists in a value name matches any value,
binding the name to the value. The pattern _ also matches
any value, but does not bind any name.

Patterns are linear: a variable cannot appear several times in
a given pattern. In particular, there is no way to test for equality
between two parts of a data structure using only a pattern (but
when guards can be used for this purpose).

Constant patterns

A pattern consisting in a constant matches the values that
are equal to this constant.

Alias patterns

The pattern pattern1asvalue-name matches the same values as
pattern1. If the matching against pattern1 is successful,
the name name is bound to the matched value, in addition to the
bindings performed by the matching against pattern1.

Parenthesized patterns

The pattern (pattern1) matches the same values as
pattern1. A type constraint can appear in a
parenthesized pattern, as in (pattern1:typexpr). This
constraint forces the type of pattern1 to be compatible with
type.

``Or'' patterns

The pattern pattern1|pattern2 represents the logical ``or'' of
the two patterns pattern1 and pattern2. A value matches
pattern1|pattern2 either if it matches pattern1 or if it
matches pattern2. The two sub-patterns pattern1 and pattern2
must bind exactly the same identifiers to values having the same types.
Matching is performed from left to right.
More precisely,
in case some value v matches pattern1|pattern2, the bindings
performed are those of pattern1 when v matches pattern1.
Otherwise, value v matches pattern2 whose bindings are performed.

If the type [('a,'b,...)] typeconstr = [`tag1t1|
... |`tagntn] is defined, then the pattern #typeconstr
is a shorthand for the or-pattern (`tag1(_:t1)|
... |`tagn(_:tn)). It matches all values of type
#typeconstr.

The pattern {field1=pattern1; ... ;fieldn=patternn} matches records that define at least the fields
field1 through fieldn, and such that the value associated to
fieldi matches the pattern patterni, for i = 1,... , n.
The record value can define more fields than field1 ...fieldn; the values associated to these extra fields are not taken
into account for matching.

Array patterns

The pattern [|pattern1; ... ;patternn|]
matches arrays of length n such that the i-th array element
matches the pattern patterni, for i = 1,... , n.

The table below shows the relative precedences and associativity of
operators and non-closed constructions. The constructions with higher
precedence come first. For infix and prefix symbols, we write
``*...'' to mean ``any symbol starting with *''.

Expressions consisting in an access path evaluate to the value bound to
this path in the current evaluation environment. The path can
be either a value name or an access path to a value component of a module.

Parenthesized expressions

The expressions (expr) and beginexprend have the same
value as expr. Both constructs are semantically equivalent, but it
is good style to use begin ... end inside control structures:

if ... then begin ... ; ... end else begin ... ; ... end

and ( ... ) for the other grouping situations.

Parenthesized expressions can contain a type constraint, as in (expr:type). This constraint forces the type of expr to be
compatible with type.

Function application is denoted by juxtaposition of (possibly labeled)
expressions. The expression exprargument1 ... argumentn
evaluates the expression expr and those appearing in argument1
to argumentn. The expression expr must evaluate to a
functional value f, which is then applied to the values of
argument1, ..., argumentn.

The order in which the expressions expr, argument1, ...,
argumentn are evaluated is not specified.

Arguments and parameters are matched according to their respective
labels. Argument order is irrelevant, except among arguments with the
same label, or no label.

If a parameter is specified as optional (label prefixed by ?) in the
type of expr, the corresponding argument will be automatically
wrapped with the constructor Some, except if the argument itself is
also prefixed by ?, in which case it is passed as is.
If a non-labeled argument is passed, and its corresponding parameter
is preceded by one or several optional parameters, then these
parameters are defaulted, i.e. the value None will be
passed for them.
All other missing parameters (without corresponding argument), both
optional and non-optional, will be kept, and the result of the
function will still be a function of these missing parameters to the
body of f.

As a special case, if the function has a known arity, all the
arguments are unlabeled, and their number matches the number of
non-optional parameters, then labels are ignored and non-optional
parameters are matched in their definition order. Optional arguments
are defaulted.

In all cases but exact match of order and labels, without optional
parameters, the function type should be known at the application
point. This can be ensured by adding a type constraint. Principality
of the derivation can be checked in the -principal mode.

Function definition

Two syntactic forms are provided to define functions. The first form
is introduced by the keyword function:

function

pattern1

->

expr1

|

...

|

patternn

->

exprn

This expression evaluates to a functional value with one argument.
When this function is applied to a value v, this value is
matched against each pattern pattern1 to patternn.
If one of these matchings succeeds, that is, if the value v
matches the pattern patterni for some i,
then the expression expri associated to the selected pattern
is evaluated, and its value becomes the value of the function
application. The evaluation of expri takes place in an
environment enriched by the bindings performed during the matching.

If several patterns match the argument v, the one that occurs
first in the function definition is selected. If none of the patterns
matches the argument, the exception Match_failure is raised.

The other form of function definition is introduced by the keyword fun:

funparameter1 ... parametern->expr

This expression is equivalent to:

funparameter1-> ... funparametern->expr

Functions of the form funoptlabel(pattern=expr0)->expr are equivalent to

funoptlabelx->letpattern=matchxwithSomex->x|None->expr0inexpr

where x is a fresh variable. When expr0 will be evaluated is left
unspecified.

After these two transformations, expressions are of the form

fun [label1] pattern1-> ... fun [labeln] patternn->expr

If we ignore labels, which will only be meaningful at function
application, this is equivalent to

functionpattern1-> ... functionpatternn->expr

That is, the fun expression above evaluates to a curried function
with n arguments: after applying this function n times to the
values v1 ... vm, the values will be matched
in parallel against the patterns pattern1 ... patternn.
If the matching succeeds, the function returns the value of expr in
an environment enriched by the bindings performed during the matchings.
If the matching fails, the exception Match_failure is raised.

Guards in pattern-matchings

Cases of a pattern matching (in the function, fun, match and
try constructs) can include guard expressions, which are
arbitrary boolean expressions that must evaluate to true for the
match case to be selected. Guards occur just before the -> token and
are introduced by the when keyword:

function

pattern1 [whencond1]

->

expr1

|

...

|

patternn [whencondn]

->

exprn

Matching proceeds as described before, except that if the value
matches some pattern patterni which has a guard condi, then the
expression condi is evaluated (in an environment enriched by the
bindings performed during matching). If condi evaluates to true,
then expri is evaluated and its value returned as the result of the
matching, as usual. But if condi evaluates to false, the matching
is resumed against the patterns following patterni.

evaluates expr1 ... exprn in some unspecified order, then matches
their values against the patterns pattern1 ... patternn. If the
matchings succeed, expr is evaluated in the environment enriched by
the bindings performed during matching, and the value of expr is
returned as the value of the whole let expression. If one of the
matchings fails, the exception Match_failure is raised.

An alternate syntax is provided to bind variables to functional
values: instead of writing

letident=funparameter1 ... parameterm->expr

in a let expression, one may instead write

letidentparameter1 ... parameterm=expr

Recursive definitions of names are introduced by let rec:

letrecpattern1=expr1and ... andpatternn=exprninexpr

The only difference with the let construct described above is
that the bindings of names to values performed by the
pattern-matching are considered already performed when the expressions
expr1 to exprn are evaluated. That is, the expressions expr1
to exprn can reference identifiers that are bound by one of the
patterns pattern1, ..., patternn, and expect them to have the
same value as in expr, the body of the let rec construct.

The recursive definition is guaranteed to behave as described above if
the expressions expr1 to exprn are function definitions
(fun ... or function ...), and the patterns pattern1
... patternn are just value names, as in:

letrecname1=fun ...
and ...
andnamen=fun ...
inexpr

This defines name1 ... namen as mutually recursive functions
local to expr.

The behavior of other forms of let rec definitions is
implementation-dependent. The current implementation also supports
a certain class of recursive definitions of non-functional values,
as explained in section 7.3.

The expression expr1;expr2 evaluates expr1 first, then
expr2, and returns the value of expr2.

Conditional

The expression ifexpr1thenexpr2elseexpr3 evaluates to
the value of expr2 if expr1 evaluates to the boolean true,
and to the value of expr3 if expr1 evaluates to the boolean
false.

The elseexpr3 part can be omitted, in which case it defaults to
else().

Case expression

The expression

match

expr

with

pattern1

->

expr1

|

...

|

patternn

->

exprn

matches the value of expr against the patterns pattern1 to
patternn. If the matching against patterni succeeds, the
associated expression expri is evaluated, and its value becomes the
value of the whole match expression. The evaluation of
expri takes place in an environment enriched by the bindings
performed during matching. If several patterns match the value of
expr, the one that occurs first in the match expression is
selected. If none of the patterns match the value of expr, the
exception Match_failure is raised.

Boolean operators

The expression expr1&&expr2 evaluates to true if both
expr1 and expr2 evaluate to true; otherwise, it evaluates to
false. The first component, expr1, is evaluated first. The
second component, expr2, is not evaluated if the first component
evaluates to false. Hence, the expression expr1&&expr2 behaves
exactly as

ifexpr1thenexpr2elsefalse.

The expression expr1||expr2 evaluates to true if one of
expr1 and expr2 evaluates to true; otherwise, it evaluates to
false. The first component, expr1, is evaluated first. The
second component, expr2, is not evaluated if the first component
evaluates to true. Hence, the expression expr1||expr2 behaves
exactly as

ifexpr1thentrueelseexpr2.

The boolean operator & is synonymous for &&. The boolean operator
or is synonymous for ||.

Loops

The expression whileexpr1doexpr2done repeatedly
evaluates expr2 while expr1 evaluates to true. The loop
condition expr1 is evaluated and tested at the beginning of each
iteration. The whole while ... done expression evaluates to
the unit value ().

The expression forname=expr1toexpr2doexpr3done
first evaluates the expressions expr1 and expr2 (the boundaries)
into integer values n and p. Then, the loop body expr3 is
repeatedly evaluated in an environment where name is successively
bound to the values
n, n+1, ..., p-1, p.
The loop body is never evaluated if n > p.

The expression forname=expr1downtoexpr2doexpr3done
evaluates similarly, except that name is successively bound to the values
n, n-1, ..., p+1, p.
The loop body is never evaluated if n < p.

In both cases, the whole for expression evaluates to the unit
value ().

Exception handling

The expression

try

expr

with

pattern1

->

expr1

|

...

|

patternn

->

exprn

evaluates the expression expr and returns its value if the
evaluation of expr does not raise any exception. If the evaluation
of expr raises an exception, the exception value is matched against
the patterns pattern1 to patternn. If the matching against
patterni succeeds, the associated expression expri is evaluated,
and its value becomes the value of the whole try expression. The
evaluation of expri takes place in an environment enriched by the
bindings performed during matching. If several patterns match the value of
expr, the one that occurs first in the try expression is
selected. If none of the patterns matches the value of expr, the
exception value is raised again, thereby transparently ``passing
through'' the try construct.

The expression expr1, ... ,exprn evaluates to the
n-tuple of the values of expressions expr1 to exprn. The
evaluation order for the subexpressions is not specified.

Variants

The expression constrexpr evaluates to the variant value whose
constructor is constr, and whose argument is the value of expr.

For lists, some syntactic sugar is provided. The expression
expr1::expr2 stands for the constructor (::)
applied to the argument (expr1,expr2), and therefore
evaluates to the list whose head is the value of expr1 and whose tail
is the value of expr2. The expression [expr1; ... ;exprn] is equivalent to expr1:: ... ::exprn::[], and therefore evaluates to the list whose elements are the
values of expr1 to exprn.

Polymorphic variants

The expression `tag-nameexpr evaluates to the variant value whose
tag is tag-name, and whose argument is the value of expr.

Records

The expression {field1=expr1; ... ;fieldn=exprn} evaluates to the record value
{field1=v1; ... ;fieldn=vn},
where vi is the value of expri for i = 1,... , n.
The fields field1 to fieldn must all belong to the same record
types; all fields belonging to this record type must appear exactly
once in the record expression, though they can appear in any
order. The order in which expr1 to exprn are evaluated is not
specified.

The expression
{exprwithfield1=expr1; ... ;fieldn=exprn}
builds a fresh record with fields field1 ... fieldn equal to
expr1 ... exprn, and all other fields having the same value as
in the record expr. In other terms, it returns a shallow copy of
the record expr, except for the fields field1 ... fieldn,
which are initialized to expr1 ... exprn.

The expression expr1.field evaluates expr1 to a record
value, and returns the value associated to field in this record
value.

The expression expr1.field<-expr2 evaluates expr1 to a record
value, which is then modified in-place by replacing the value
associated to field in this record by the value of
expr2. This operation is permitted only if field has been
declared mutable in the definition of the record type. The whole
expression expr1.field<-expr2 evaluates to the unit value
().

Arrays

The expression [|expr1; ... ;exprn|] evaluates to
a n-element array, whose elements are initialized with the values of
expr1 to exprn respectively. The order in which these
expressions are evaluated is unspecified.

The expression expr1.(expr2) returns the value of element
number expr2 in the array denoted by expr1. The first element
has number 0; the last element has number n-1, where n is the
size of the array. The exception Invalid_argument is raised if the
access is out of bounds.

The expression expr1.(expr2)<-expr3 modifies in-place
the array denoted by expr1, replacing element number expr2 by
the value of expr3. The exception Invalid_argument is raised if
the access is out of bounds. The value of the whole expression is ().

Strings

The expression expr1.[expr2] returns the value of character
number expr2 in the string denoted by expr1. The first character
has number 0; the last character has number n-1, where n is the
length of the string. The exception Invalid_argument is raised if the
access is out of bounds.

The expression expr1.[expr2]<-expr3 modifies in-place
the string denoted by expr1, replacing character number expr2 by
the value of expr3. The exception Invalid_argument is raised if
the access is out of bounds. The value of the whole expression is ().

Symbols from the class infix-symbols, as well as the keywords
*, =, or and &, can appear in infix position (between two
expressions). Symbols from the class prefix-symbols
can appear in prefix position (in front of an expression).

Infix and prefix symbols do not have a fixed meaning: they are simply
interpreted as applications of functions bound to the names
corresponding to the symbols. The expression prefix-symbolexpr is
interpreted as the application (prefix-symbol)expr. Similarly, the expression expr1infix-symbolexpr2 is
interpreted as the application (infix-symbol)expr1expr2.

The table below lists the symbols defined in the initial environment
and their initial meaning. (See the description of the standard
library module Pervasive in chapter 20 for more
details). Their meaning may be changed at any time using
let(infix-op)name1name2= ...

Operator

Initial meaning

+

Integer addition.

- (infix)

Integer subtraction.

- (prefix)

Integer negation.

*

Integer multiplication.

/

Integer division.
Raise Division_by_zero if second argument is zero.

mod

Integer modulus. Raise
Division_by_zero if second argument is zero.

land

Bitwise logical ``and'' on integers.

lor

Bitwise logical ``or'' on integers.

lxor

Bitwise logical ``exclusive or'' on integers.

lsl

Bitwise logical shift left on integers.

lsr

Bitwise logical shift right on integers.

asr

Bitwise arithmetic shift right on integers.

+.

Floating-point addition.

-. (infix)

Floating-point subtraction.

-. (prefix)

Floating-point negation.

*.

Floating-point multiplication.

/.

Floating-point division.

**

Floating-point exponentiation.

@

List concatenation.

^

String concatenation.

!

Dereferencing (return the current
contents of a reference).

:=

Reference assignment (update the
reference given as first argument with the value of the second
argument).

When class-path evaluates to a class body, newclass-path
evaluates to an object containing the instance variables and
methods of this class.

When class-path evaluates to a class function, newclass-path
evaluates to a function expecting the same number of arguments and
returning a new object of this class.

Immediate object creation

Creating directly an object through the objectclass-bodyend
construct is operationally equivalent to defining locally a classmyclass=objectclass-bodyend ---see sections
6.9.2 and following for the syntax of class-body---
and immediately creating a single object from it by newmyclass.

The typing of immediate objects is slightly different from explicitely
defining a class in two respects. First, the inferred object type may
contain free type variables. Second, since the class body of an
immediate object will never be extended, its self type can be unified
with a closed object type.

Message sending

The expression expr#method-name invokes the method
method-name of the object denoted by expr.

If method-name is a polymorphic method, its type should be known at
the invocation site. This is true for instance if expr is the name
of a fresh object (letident = newclass-path ... ) or if
there is a type constraint. Principality of the derivation can be
checked in the -principal mode.

Accessing and modifying instance variables

The instance variables of a class are visible only in the body of the
methods defined in the same class or a class that inherits from the
class defining the instance variables. The expression inst-var-name
evaluates to the value of the given instance variable. The expression
inst-var-name<-expr assigns the value of expr to the instance
variable inst-var-name, which must be mutable. The whole expression
inst-var-name<-expr evaluates to ().

Coercion

The type of an object can be coerced (weakened) to a supertype.
The expression (expr:>typexpr) coerces the expression expr
to type typexpr.
The expression (expr:typexpr1:>typexpr2) coerces the
expression expr from type typexpr1 to type typexpr2.
The former operator will sometimes fail to coerce an expression expr
from a type t1 to a type t2 even if type t1 is a subtype of type
t2: in the current implementation it only expands two levels of
type abbreviations containing objects and/or variants, keeping only
recursion when it is explicit in the class type. In case of failure,
the latter operator should be used.

In a class definition, coercion to the type this class defines is the
identity, as this type abbreviation is not yet completely defined.

Object duplication

An object can be duplicated using the library function Oo.copy
(see
Module Oo). Inside a method, the expression
{<inst-var-name=expr { ;inst-var-name=expr } >}
returns a copy of self with the given instance variables replaced by
the values of the associated expressions; other instance variables
have the same value in the returned object as in self.

Type definitions bind type constructors to data types: either
variant types, record types, type abbreviations, or abstract data
types. They also bind the value constructors and record fields
associated with the definition.

type-definition

::=

typetypedef { andtypedef }

typedef

::=

[type-params] typeconstr-name [type-information]

type-information

::=

[type-equation] [type-representation] { type-constraint }

type-equation

::=

=typexpr

type-representation

::=

=constr-decl { |constr-decl }

|

={field-decl { ;field-decl } }

type-params

::=

type-param

|

(type-param { ,type-param } )

type-param

::=

'ident

|

+'ident

|

-'ident

constr-decl

::=

constr-name

|

constr-nameoftypexpr

field-decl

::=

field-name:poly-typexpr

|

mutablefield-name:poly-typexpr

type-constraint

::=

constraint'ident=typexpr

Type definitions are introduced by the type keyword, and
consist in one or several simple definitions, possibly mutually
recursive, separated by the and keyword. Each simple definition
defines one type constructor.

A simple definition consists in a lowercase identifier, possibly
preceded by one or several type parameters, and followed by an
optional type equation, then an optional type representation, and then
a constraint clause. The identifier is the name of the type
constructor being defined.

The optional type parameters are either one type variable 'ident,
for type constructors with one parameter, or a list of type variables
('ident1,...,'identn), for type constructors with several
parameters. Each type parameter may be prefixed by a variance
constraint + (resp. -) indicating that the parameter is
covariant (resp. contravariant). These type parameters can appear in
the type expressions of the right-hand side of the definition,
restricted eventually by a variance constraint ; i.e. a
covariant parameter may only appear on the right side of a functional
arrow (more precisely, follow the left branch of an even number of
arrows), and a convariant parameter only the left side (left branch of
an odd number of arrows).

The optional type equation =typexpr makes the defined type
equivalent to the type expression typexpr on the right of the =
sign: one can be substituted for the other during typing.
If no type equation is given, a new type is generated: the defined type
is incompatible with any other type.

The optional type representation describes the data structure
representing the defined type, by giving the list of associated
constructors (if it is a variant type) or associated fields (if it is
a record type). If no type representation is given, nothing is
assumed on the structure of the type besides what is stated in the
optional type equation.

The type representation =constr-decl { |constr-decl }
describes a variant type. The constructor declarations
constr-decl1, ..., constr-decln describe the constructors
associated to this variant type. The constructor
declaration constr-nameoftypexpr declares the name
constr-name as a non-constant constructor, whose
argument has type typexpr. The constructor declaration constr-name
declares the name constr-name as a constant
constructor. Constructor names must be capitalized.

The type representation ={field-decl { ;field-decl } }
describes a record type. The field declarations field-decl1, ...,
field-decln describe the fields associated to this record type.
The field declaration field-name:poly-typexpr declares
field-name as a field whose argument has type poly-typexpr.
The field declaration mutablefield-name:poly-typexpr
behaves similarly; in addition, it allows physical modification over
the argument to this field.
Immutable fields are covariant, but mutable fields are neither
covariant nor contravariant.
Both mutable and immutable field may have an explicitly polymorphic
type. The polymorphism of the contents is statically checked whenever
a record value is created or modified. Extracted values may have their
types instanciated.

The two components of a type definition, the optional equation and the
optional representation, can be combined independently, giving
rise to four typical situations:

Abstract type: no equation, no representation.

When appearing in a module signature, this definition specifies
nothing on the type constructor, besides its number of parameters:
its representation is hidden and it is assumed incompatible with any
other type.

Type abbreviation: an equation, no representation.

This defines the type constructor as an abbreviation for the type
expression on the right of the = sign.

New variant type or record type: no equation, a representation.

This generates a new type constructor and defines associated
constructors or fields, through which values of that type can be
directly built or inspected.

Re-exported variant type or record type: an equation,
a representation.

In this case, the type constructor is defined as an abbreviation for
the type expression given in the equation, but in addition the
constructors or fields given in the representation remain attached to
the defined type constructor. The type expression in the equation part
must agree with the representation: it must be of the same kind
(record or variant) and have exactly the same constructors or fields,
in the same order, with the same arguments.

The type variables appearing as type parameters can optionally be
prefixed by + or - to indicate that the type constructor is
covariant or contravariant with respect to this parameter. This
variance information is used to decide subtyping relations when
checking the validity of >: coercions (see section 6.7.5).

For instance, type +'a t declares t as an abstract type that is
covariant in its parameter; this means that if the type t is a
subtype of the type s, then t t is a subtype of s t. Similarly, type -'a t declares that the abstract type t is
contravariant in its parameter: if t is subtype of s, then
s t is subtype of t t. If no + or - variance
annotation is given, the type constructor is assumed invariant in the
corresponding parameter. For instance, the abstract type declaration
type 'a t means that t t is neither a subtype nor a
supertype of s t if t is subtype of s.

The variance indicated by the + and - annotations on parameters
are required only for abstract types. For abbreviations, variant
types or record types, the variance properties of the type constructor
are inferred from its definition, and the variance annotations are
only checked for conformance with the definition.

The construct constraint'ident=typexpr allows to specify
type parameters. Any actual type argument corresponding to the type
parameter ident has to be an instance of typexpr (more precisely,
ident and typexpr are unified). Type variables of typexpr can
appear in the type equation and the type declaration.

Exception definitions add new constructors to the built-in variant
type exn of exception values. The constructors are declared as
for a definition of a variant type.

The form exceptionconstr-name [oftypexpr]
generates a new exception, distinct from all other exceptions in the system.
The form exceptionconstr-name=constr
gives an alternate name to an existing exception.

Class types are the class-level equivalent of type expressions: they
specify the general shape and type properties of classes.

class-type

::=

|

class-body-type

|

[[?]label-name:] typexpr->class-type

class-body-type

::=

object [(typexpr)] {class-field-spec} end

|

class-path

|

[typexpr {,typexpr} ]class-path

class-field-spec

::=

inheritclass-type

|

val [mutable] inst-var-name:typexpr

|

method [private] method-name:poly-typexpr

|

method [private] virtualmethod-name:poly-typexpr

|

constrainttypexpr=typexpr

Simple class expressions

The expression class-path is equivalent to the class type bound to
the name class-path. Similarly, the expression
[typexpr1, ... typexprn]class-path is equivalent to
the parametric class type bound to the name class-path, in which
type parameters have been instanciated to respectively typexpr1,
...typexprn.

Class function type

The class type expression typexpr->class-type is the type of
class functions (functions from values to classes) that take as
argument a value of type typexpr and return as result a class of
type class-type.

Class body type

The class type expression
object [(typexpr)] {class-field-spec} end
is the type of a class body. It specifies its instance variables and
methods. In this type, typexpr is matched against the self type, therefore
providing a binding for the self type.

A class body will match a class body type if it provides definitions
for all the components specified in the class type, and these
definitions meet the type requirements given in the class type.
Furthermore, all methods either virtual or public present in the class
body must also be present in the class type (on the other hand, some
instance variables and concrete private methods may be omitted). A
virtual method will match a concrete method, which makes it possible
to forget its implementation. An immutable instance variable will match a
mutable instance variable.

Inheritance

The inheritance construct inheritclass-type allows to include
methods and instance variables from other classes types.
The instance variable and method types from this class type are added
into the current class type.

Instance variable specification

A specification of an instance variable is written
val [mutable] inst-var-name:typexpr, where inst-var-name
is the name of the instance variable and typexpr its expected type.
The flag mutable indicates whether this instance variable can be
physically modified.

An instance variable specification will hide any previous
specification of an instance variable of the same name.

Method specification

The specification of a method is written
method [private] method-name:poly-typexpr, where
method-name is the name of the method and poly-typexpr its
expected type, possibly polymorphic. The flag private indicates
whether the method can be accessed from outside the class.

The polymorphism may be left implicit in method specifications: any
type variable which is not bound to a class parameter and does not
appear elsewhere inside the class specification will be assumed to be
polymorphic, and made explicit in the resulting method type.
Writing an explicit polymorphic type will disable this behaviour.

Several specification for the same method must have compatible types.
Any non-private specification of a method forces it to be public.

Virtual method specification

Virtual method specification is written method [private]
virtualmethod-name:poly-typexpr, where method-name is the
name of the method and poly-typexpr its expected type.

Constraints on type parameters

The construct constrainttypexpr1=typexpr2 forces the two
type expressions to be equals. This is typically used to specify type
parameters: they can be that way be bound to a specified type
expression.

Class expressions are the class-level equivalent of value expressions:
they evaluate to classes, thus providing implementations for the
specifications expressed in class types.

class-expr

::=

class-path

|

[typexpr {,typexpr} ]class-path

|

(class-expr)

|

(class-expr:class-type)

|

class-expr {argument}+

|

fun {parameter}+->class-expr

|

let [rec] let-binding {andlet-binding} inclass-expr

|

object [(pattern [:typexpr] )] { class-field } end

class-field

::=

inheritclass-expr [asvalue-name]

|

val [mutable] inst-var-name [:typexpr] =expr

|

method [private] method-name {parameter} [:typexpr] =expr

|

method [private] method-name:poly-typexpr=expr

|

method [private] virtualmethod-name:poly-typexpr

|

constrainttypexpr=typexpr

|

initializerexpr

Simple class expressions

The expression class-path evaluates to the class bound to the name
class-path. Similarly, the expression
[typexpr1, ... typexprn]class-path
evaluates to the parametric class bound to the name class-path,
in which type parameters have been instanciated to respectively
typexpr1, ...typexprn.

The expression (class-expr) evaluates to the same module as
class-expr.

The expression (class-expr:class-type) checks that
class-type match the type of class-expr (that is, that the
implementation class-expr meets the type specification
class-type). The whole expression evaluates to the same class as
class-expr, except that all components not specified in
class-type are hidden and can no longer be accessed.

Class application

Class application is denoted by juxtaposition of (possibly labeled)
expressions. Evaluation works as for expression application.

Class function

The expression fun [[?]label-name:] pattern->class-expr evaluates
to a function from values to classes.
When this function is applied to a value v, this value is
matched against the pattern pattern and the result is the result of
the evaluation of class-expr in the extended environment.

Conversion from functions with default values to functions with
patterns only works identically for class functions as for normal
functions.

The expression

funparameter1 ... parametern->class-expr

is a short form for

funparameter1-> ... funparametern->expr

Local definitions

The let and let rec constructs bind value names locally,
as for the core language expressions.

Class body

The expression
object(pattern [:typexpr] ) { class-field } end denotes
a class body. This is the prototype for an object : it lists the
instance variables and methods of an objet of this class.

A class body is a class value: it is not evaluated at once. Rather,
its components are evaluated each time an object is created.

In a class body, the pattern (pattern [:typexpr] ) is
matched against self, therefore provinding a binding for self and self
type. Self can only be used in method and initializers.

Self type cannot be a closed object type, so that the class remains
extensible.

Inheritance

The inheritance construct inheritclass-expr allows to reuse
methods and instance variables from other classes. The class
expression class-expr must evaluate to a class body. The instance
variables, methods and initializers from this class body are added
into the current class. The addition of a method will override any
previously defined methods of the same name.

An ancestor can be bound by prepending the construct asvalue-name
to the inheritance construct above. value-name is not a true
variable and can only be used to select a method, i.e. in an expression
value-name#method-name. This gives access to the
method method-name as it was defined in the parent class even if it is
redefined in the current class.
The scope of an ancestor binding is limited to the current class.
The ancestor method may be called from a subclass but only indirectly.

Instance variable definition

The definition val [mutable] inst-var-name=expr adds an
instance variable inst-var-name whose initial value is the value of
expression expr. Several variables of the same name can be defined
in the same class.
The flag mutable allows physical modification of this variable by
methods.

An instance variables can only be used in the following methods and
initializers of the class.

Method definition

Method definition is written methodmethod-name=expr. The
definition of a method overrides any previous definition of this
method. The method will be public (that is, not private) if any of
the definition states so.

A private method, methodprivatemethod-name=expr, is a
method that can only be invoked on self (from other methods of the
current class as well as of subclasses of the current class). This
invocation is performed using the expression
value-name#method-name, where value-name is directly bound to
self at the beginning of the class definition. Private methods do
not appear in object types. A method may have both public and private
definitions, but as soon as there is a public one, all subsequent
definitions will be made public.

Methods may have an explicitly polymorphic type, allowing them to be
used polymorphically in programs (even for the same object). The
explicit declaration may be done in one of three ways: (1) by giving an
explicit polymorphic type in the method definition, immediately after
the method name, i.e.method [private] method-name: {'ident}+.typexpr=expr; (2) by a forward declaration of the explicit polymorphic type
through a virtual method definition; (3) by importing such a
declaration through inheritance and/or constraining the type of self.

Some special expressions are available in method bodies for
manipulating instance variables and duplicating self:

expr

::=

...

|

inst-var-name<-expr

|

{< [ inst-var-name=expr { ;inst-var-name=expr } ] >}

The expression inst-var-name<-expr modifies in-place the current
object by replacing the value associated to inst-var-name by the
value of expr. Of course, this instance variable must have been
declared mutable.

The expression
{< [ inst-var-name=expr { ;inst-var-name=expr } ] >}
evaluates to a copy of the current object in which the values of
instance variables inst-var-name1, ..., inst-var-namen have
been replaced by the values of the corresponding expressions expr1,
..., exprn.

Virtual method definition

Method specification is written method [private] virtualmethod-name:poly-typexpr. It specifies whether the method is
public or private, and gives its type. If the method is intended to be
polymorphic, the type should be explicit.

Constraints on type parameters

The construct constrainttypexpr1=typexpr2 forces the two
type expressions to be equals. This is typically used to specify type
parameters: they can be that way be bound to a specified type
expression.

Initializers

A class initializer initializerexpr specifies an expression that
will be evaluated when an object will be created from the class, once
all the instance variables have been initialized.

A class definition classclass-binding { andclass-binding } is
recursive. Each class-binding defines a class-name that can be
used in the whole expression except for inheritance. It can also be
used for inheritance, but only in the definitions that follow its own.

A class binding binds the class name class-name to the value of
expression class-expr. It also binds the class type class-name to
the type of the class, and defines two type abbreviations :
class-name and #class-name. The first one is the type of
objects of this class, while the second is more general as it unifies
with the type of any object belonging to a subclass (see
section 6.4).

Virtual class

A class must be flagged virtual if one of its methods is virtual (that
is, appears in the class type, but is not actually defined).
Objects cannot be created from a virtual class.

Type parameters

The class type parameters correspond to the ones of the class type and
of the two type abbreviations defined by the class binding. They must
be bound to actual types in the class definition using type
constraints. So that the abbreviations are well-formed, type
variables of the inferred type of the class must either be type
parameters or be bound in the constraint clause.

A class type definition classclass-name=class-body-type
defines an abbreviation class-name for the class body type
class-body-type. As for class definitions, two type abbreviations
class-name and #class-name are also defined. The definition can
be parameterized by some type parameters. If any method in the class
type body is virtual, the definition must be flagged virtual.

Two class type definitions match if they have the same type parameters
and the types they expand to match.

Signatures are type specifications for structures. Signatures
sig ... end are collections of type specifications for value
names, type names, exceptions, module names and module type names. A
structure will match a signature if the structure provides definitions
(implementations) for all the names specified in the signature (and
possibly more), and these definitions meet the type requirements given
in the signature.

For compatibility with Caml Light, an optional ;; is allowed after each
specification in a signature. The ;; has no semantic meaning.

Value specifications

A specification of a value component in a signature is written
valvalue-name:typexpr, where value-name is the name of the
value and typexpr its expected type.

The form externalvalue-name:typexpr=external-declaration
is similar, except that it requires in addition the name to be
implemented as the external function specified in external-declaration
(see chapter 18).

Type specifications

A specification of one or several type components in a signature is
written typetypedef { andtypedef } and consists of a sequence
of mutually recursive definitions of type names.

Each type definition in the signature specifies an optional type
equation =typexp and an optional type representation
=constr-decl ... or ={label-decl ... }.
The implementation of the type name in a matching structure must
be compatible with the type expression specified in the equation (if
given), and have the specified representation (if given). Conversely,
users of that signature will be able to rely on the type equation
or type representation, if given. More precisely, we have the
following four situations:

Abstract type: no equation, no representation.

Names that are defined as abstract types in a signature can be
implemented in a matching structure by any kind of type definition
(provided it has the same number of type parameters). The exact
implementation of the type will be hidden to the users of the
structure. In particular, if the type is implemented as a variant type
or record type, the associated constructors and fields will not be
accessible to the users; if the type is implemented as an
abbreviation, the type equality between the type name and the
right-hand side of the abbreviation will be hidden from the users of the
structure. Users of the structure consider that type as incompatible
with any other type: a fresh type has been generated.

Type abbreviation: an equation =typexp, no representation.

The type name must be implemented by a type compatible with typexp.
All users of the structure know that the type name is
compatible with typexp.

New variant type or record type: no equation, a representation.

The type name must be implemented by a variant type or record type
with exactly the constructors or fields specified. All users of the
structure have access to the constructors or fields, and can use them
to create or inspect values of that type. However, users of the
structure consider that type as incompatible with any other type: a
fresh type has been generated.

Re-exported variant type or record type: an equation,
a representation.

This case combines the previous two: the representation of the type is
made visible to all users, and no fresh type is generated.

Exception specification

The specification exceptionconstr-decl in a signature requires the
matching structure to provide an exception with the name and arguments
specified in the definition, and makes the exception available to all
users of the structure.

Class specifications

A specification of one or several classes in a signature is written
classclass-spec { andclass-spec } and consists of a sequence
of mutually recursive definitions of class names.

A specification of one or several classe types in a signature is
written classtypeclasstype-def { andclasstype-def } and
consists of a sequence of mutually recursive definitions of class type
names. Class type specifications are described more precisely in
section 6.9.5.

Module specifications

A specification of a module component in a signature is written
modulemodule-name:module-type, where module-name is the
name of the module component and module-type its expected type.
Modules can be nested arbitrarily; in particular, functors can appear
as components of structures and functor types as components of
signatures.

A module type component of a signature can be specified either as a
manifest module type or as an abstract module type.

An abstract module type specification
moduletypemodtype-name allows the name modtype-name to be
implemented by any module type in a matching signature, but hides the
implementation of the module type to all users of the signature.

A manifest module type specification
moduletypemodtype-name=module-type
requires the name modtype-name to be implemented by the module type
module-type in a matching signature, but makes the equality between
modtype-name and module-type apparent to all users of the signature.

Opening a module path

The expression openmodule-path in a signature does not specify
any components. It simply affects the parsing of the following items
of the signature, allowing components of the module denoted by
module-path to be referred to by their simple names name instead of
path accesses module-path.name. The scope of the open
stops at the end of the signature expression.

Including a signature

The expression includemodule-type in a signature performs textual
inclusion of the components of the signature denoted by module-type.
It behaves as if the components of the included signature were copied
at the location of the include. The module-type argument must
refer to a module type that is a signature, not a functor type.

The module type expression
functor(module-name:module-type1)->module-type2
is the type of functors (functions from modules to modules) that take
as argument a module of type module-type1 and return as result a
module of type module-type2. The module type module-type2 can
use the name module-name to refer to type components of the actual
argument of the functor. No restrictions are placed on the type of the
functor argument; in particular, a functor may take another functor as
argument (``higher-order'' functor).

Assuming module-type denotes a signature, the expression
module-typewithmod-constraint { andmod-constraint } denotes
the same signature where type equations have been added to some of the
type specifications, as described by the constraints following the
with keyword. The constraint type [type-parameters] typeconstr=typexp adds the type equation =typexp to the specification
of the type component named typeconstr of the constrained signature.
The constraint modulemodule-path=extended-module-path adds
type equations to all type components of the sub-structure denoted by
module-path, making them equivalent to the corresponding type
components of the structure denoted by extended-module-path.

For instance, if the module type name S is bound to the signature

sig type t module M: (sig type u end) end

then S with type t=int denotes the signature

sig type t=int module M: (sig type u end) end

and S with module M = N denotes the signature

sig type t module M: (sig type u=N.u end) end

A functor taking two arguments of type S that share their t component
is written

functor (A: S) (B: S with type t = A.t) ...

Constraints are added left to right. After each constraint has been
applied, the resulting signature must be a subtype of the signature
before the constraint was applied. Thus, the with operator can
only add information on the type components of a signature, but never
remove information.

The expression module-path evaluates to the module bound to the name
module-path.

The expression (module-expr) evaluates to the same module as
module-expr.

The expression (module-expr:module-type) checks that the
type of module-expr is a subtype of module-type, that is, that all
components specified in module-type are implemented in
module-expr, and their implementation meets the requirements given
in module-type. In other terms, it checks that the implementation
module-expr meets the type specification module-type. The whole
expression evaluates to the same module as module-expr, except that
all components not specified in module-type are hidden and can no
longer be accessed.

Structures struct ... end are collections of definitions for
value names, type names, exceptions, module names and module type
names. The definitions are evaluated in the order in which they appear
in the structure. The scope of the bindings performed by the
definitions extend to the end of the structure. As a consequence, a
definition may refer to names bound by earlier definitions in the same
structure.

For compatibility with toplevel phrases (chapter 9)
and with Caml Light, an optional ;; is allowed after each
definition in a structure. The ;; has no semantic meaning. Also for
compatibility, ;;expr is allowed as a component of a structure,
meaning let_=expr, i.e. evaluate expr for its side-effects.

Value definitions

A value definition let [rec] let-binding { andlet-binding }
bind value names in the same way as a let ... in ... expression
(see section 6.7.1). The value names appearing in the
left-hand sides of the bindings are bound to the corresponding values
in the right-hand sides.

A definition of one or several type components is written
typetypedef { andtypedef } and consists of a sequence
of mutually recursive definitions of type names.

Exception definitions

Exceptions are defined with the syntax exceptionconstr-decl
or exceptionconstr-name=constr.

Class definitions

A definition of one or several classes is written classclass-binding { andclass-binding } and consists of a sequence of
mutually recursive definitions of class names. Class definitions are
described more precisely in section 6.9.3.

Class type definitions

A definition of one or several classes is written
classtypeclasstype-def { andclasstype-def } and consists of
a sequence of mutually recursive definitions of class type names.
Class type definitions are described more precisely in
section 6.9.5.

Module definitions

The basic form for defining a module component is
modulemodule-name=module-expr, which evaluates module-expr and binds
the result to the name module-name.

A definition for a module type is written
moduletypemodtype-name=module-type.
It binds the name modtype-name to the module type denoted by the
expression module-type.

Opening a module path

The expression openmodule-path in a structure does not define any
components nor perform any bindings. It simply affects the parsing of
the following items of the structure, allowing components of the
module denoted by module-path to be referred to by their simple names
name instead of path accesses module-path.name. The scope of
the open stops at the end of the structure expression.

Including the components of another structure

The expression include module-expr in a structure re-exports in
the current structure all definitions of the structure denoted by
module-expr. For instance, if the identifier S is bound to the
module

struct type t = int let x = 2 end

the module expression

struct include S let y = (x + 1 : t) end

is equivalent to the module expression

struct type t = int let x = 2 let y = (x + 1 : t) end

The difference between open and include is that open
simply provides short names for the components of the opened
structure, without defining any components of the current structure,
while include also adds definitions for the components of the
included structure.

The expression functor(module-name:module-type)->module-expr evaluates to a functor that takes as argument modules of
the type module-type1, binds module-name to these modules,
evaluates module-expr in the extended environment, and returns the
resulting modules as results. No restrictions are placed on the type of the
functor argument; in particular, a functor may take another functor as
argument (``higher-order'' functor).

Functor application

The expression module-expr1(module-expr2) evaluates
module-expr1 to a functor and module-expr2 to a module, and
applies the former to the latter. The type of module-expr2 must
match the type expected for the arguments of the functor module-expr1.

Compilation units bridge the module system and the separate
compilation system. A compilation unit is composed of two parts: an
interface and an implementation. The interface contains a sequence of
specifications, just as the inside of a sig ... end
signature expression. The implementation contains a sequence of
definitions, just as the inside of a struct ... end module
expression. A compilation unit also has a name unit-name, derived
from the names of the files containing the interface and the
implementation (see chapter 8 for more details). A
compilation unit behaves roughly as the module definition

moduleunit-name:sigunit-interfaceend=structunit-implementationend

A compilation unit can refer to other compilation units by their
names, as if they were regular modules. For instance, if U is a
compilation unit that defines a type t, other compilation units can
refer to that type under the name U.t; they can also refer to U as
a whole structure. Except for names of other compilation units, a unit
interface or unit implementation must not have any other free variables.
In other terms, the type-checking and compilation of an interface or
implementation proceeds in the initial environment

name1:siginterface1end ...
namen:siginterfacenend

where name1 ... namen are the names of the other
compilation units available in the search path (see
chapter 8 for more details) and interface1 ...
interfacen are their respective interfaces.

An integer literal can be followed by one of the letters l, L or n
to indicate that this integer has type int32, int64 or nativeint
respectively, instead of the default type int for integer literals.
The library modules Int32[Int32],
Int64[Int64] and Nativeint[Nativeint]
provide operations on these integer types.

Streams and stream parsers are no longer part of the Objective Caml
language, but available through a Camlp4 syntax extension. See the
Camlp4 reference manual for more information. Objective Caml programs
that use streams and stream parsers can be compiled with the
-pp camlp4o option to ocamlc and ocamlopt. For interactive use,
run ocaml and issue the #load "camlp4o.cma";; command.

As mentioned in section 6.7.1, the let rec binding
construct, in addition to the definition of recursive functions,
also supports a certain class of recursive definitions of
non-functional values, such as

letrecname1=1::name2andname2=2::name1inexpr

which binds name1 to the cyclic list 1::2::1::2::..., and
name2 to the cyclic list 2::1::2::1::...Informally, the class of accepted definitions consists of those
definitions where the defined names occur only inside function
bodies or as argument to a data constructor.

More precisely, consider the expression:

letrecname1=expr1and ... andnamen=exprninexpr

It will be accepted if each one of expr1 ... exprn is
statically constructive with respect to name1 ... namen and
not immediately linked to any of name1 ... namen

An expression e is said to be statically constructive
with respect to the variables name1 ... namen if at least
one of the following conditions is true:

e has no free occurrence of any of name1 ... namen

e is a variable

e has the form fun ... -> ...

e has the form function ... -> ...

e has the form lazy( ... )

e has one of the following forms, where each one of
expr1 ... exprm is statically constructive with respect to
name1 ... namen, and expr0 is statically constructive with
respect to name1 ... namen, xname1 ... xnamem:

Objective Caml supports the assert construct to check debugging assertions.
The expression assertexpr evaluates the expression expr and
returns () if expr evaluates to true. Otherwise, the exception
Assert_failure is raised with the source file name and the
location of expr as arguments. Assertion
checking can be turned off with the -noassert compiler option.

As a special case, assert false is reduced to
raise (Assert_failure ...), which is polymorphic (and
is not turned off by the -noassert option).

The expression lazyexpr returns a value v of type Lazy.t that
encapsulates the computation of expr. The argument expr is not
evaluated at this point in the program. Instead, its evaluation will
be performed the first time Lazy.force is applied to the value
v, returning the actual value of expr. Subsequent applications
of Lazy.force to v do not evaluate expr again.
For more information, see the description of module Lazy in the
standard library (see
Module Lazy).

The expression
letmodulemodule-name=module-exprinexpr
locally binds the module expression module-expr to the identifier
module-name during the evaluation of the expression expr.
It then returns the value of expr. For example:

Private types are variant or record types. Values of
these types can be de-structured normally in pattern-matching or via
the expr.field notation for record accesses. However, values of
these types cannot be constructed directly by constructor application
or record construction. Moreover, assignment on a mutable field of a
private record type is not allowed.

The typical use of private types is in the export signature of a
module, to ensure that construction of values of the private type always
go through the functions provided by the module, while still allowing
pattern-matching outside the defining module. For example:

This is an experimental extension of Objective Caml: the class of
recursive definitions accepted, as well as its dynamic semantics are
not final and subject to change in future releases.

Currently, the compiler requires that all dependency cycles between
the recursively-defined module identifiers go through at least one
``safe'' module. A module is ``safe'' if all value definitions that
it contains have function types ty1->ty2. Evaluation of a
recursive module definition proceeds by building initial values for
the safe modules involved, binding all (functional) values to
funx->raiseUndefined_recursive_module. The defining
module expressions are then evaluated, and the initial values
for the safe modules are replaced by the values thus computed. If a
function component of a safe module is applied during this computation
(which corresponds to an ill-founded recursive definition), the
Undefined_recursive_module exception is raised.

This chapter describes the Objective Caml batch compiler ocamlc,
which compiles Caml source files to bytecode object files and link
these object files to produce standalone bytecode executable files.
These executable files are then run by the bytecode interpreter
ocamlrun.

The ocamlc command has a command-line interface similar to the one of
most C compilers. It accepts several types of arguments and processes them
sequentially:

Arguments ending in .mli are taken to be source files for
compilation unit interfaces. Interfaces specify the names exported by
compilation units: they declare value names with their types, define
public data types, declare abstract data types, and so on. From the
file x.mli, the ocamlc compiler produces a compiled interface
in the file x.cmi.

Arguments ending in .ml are taken to be source files for compilation
unit implementations. Implementations provide definitions for the
names exported by the unit, and also contain expressions to be
evaluated for their side-effects. From the file x.ml, the ocamlc
compiler produces compiled object bytecode in the file x.cmo.

If the interface file x.mli exists, the implementation
x.ml is checked against the corresponding compiled interface
x.cmi, which is assumed to exist. If no interface
x.mli is provided, the compilation of x.ml produces a
compiled interface file x.cmi in addition to the compiled
object code file x.cmo. The file x.cmi produced
corresponds to an interface that exports everything that is defined in
the implementation x.ml.

Arguments ending in .cmo are taken to be compiled object bytecode. These
files are linked together, along with the object files obtained
by compiling .ml arguments (if any), and the Objective Caml standard
library, to produce a standalone executable program. The order in
which .cmo and .ml arguments are presented on the command line is
relevant: compilation units are initialized in that order at
run-time, and it is a link-time error to use a component of a unit
before having initialized it. Hence, a given x.cmo file must come
before all .cmo files that refer to the unit x.

Arguments ending in .cma are taken to be libraries of object bytecode.
A library of object bytecode packs in a single file a set of object
bytecode files (.cmo files). Libraries are built with ocamlc -a
(see the description of the -a option below). The object files
contained in the library are linked as regular .cmo files (see
above), in the order specified when the .cma file was built. The
only difference is that if an object file contained in a library is
not referenced anywhere in the program, then it is not linked in.

Arguments ending in .c are passed to the C compiler, which generates
a .o object file. This object file is linked with the program if the
-custom flag is set (see the description of -custom below).

Arguments ending in .o or .a (.obj or .lib under Windows)
are assumed to be C object files and libraries. They are passed to the
C linker when linking in -custom mode (see the description of
-custom below).

Arguments ending in .so (.dll under Windows)
are assumed to be C shared libraries (DLLs). During linking, they are
searched for external C functions referenced from the Caml code,
and their names are written in the generated bytecode executable.
The run-time system ocamlrun then loads them dynamically at program
start-up time.

The output of the linking phase is a file containing compiled bytecode
that can be executed by the Objective Caml bytecode interpreter:
the command named ocamlrun. If caml.out is the name of the file
produced by the linking phase, the command

ocamlrun caml.out arg1arg2 ... argn

executes the compiled code contained in caml.out, passing it as
arguments the character strings arg1 to argn.
(See chapter 10 for more details.)

On most systems, the file produced by the linking
phase can be run directly, as in:

./caml.out arg1arg2 ... argn

The produced file has the executable bit set, and it manages to launch
the bytecode interpreter by itself.

Build a library (.cma file) with the object files (.cmo files)
given on the command line, instead of linking them into an executable
file. The name of the library must be set with the -o option.

If -custom, -cclib or -ccopt options are passed on the command
line, these options are stored in the resulting .cma library. Then,
linking with this library automatically adds back the -custom,
-cclib and -ccopt options as if they had been provided on the
command line, unless the -noautolink option is given.

-c

Compile only. Suppress the linking phase of the
compilation. Source code files are turned into compiled files, but no
executable file is produced. This option is useful to
compile modules separately.

-ccccomp

Use ccomp as the C linker called by ocamlc -custom
and as the C compiler for compiling .c source files.

-cclib-llibname

Pass the -llibname option to the C linker when linking in
``custom runtime'' mode (see the -custom option). This causes the
given C library to be linked with the program.

-ccoptoption

Pass the given option to the C compiler and linker, when linking in
``custom runtime'' mode (see the -custom option). For instance,
-ccopt -Ldir causes the C linker to search for C libraries in
directory dir.

-custom

Link in ``custom runtime'' mode. In the default linking mode, the
linker produces bytecode that is intended to be executed with the
shared runtime system, ocamlrun. In the custom runtime mode, the
linker produces an output file that contains both the runtime system
and the bytecode for the program. The resulting file is larger, but it
can be executed directly, even if the ocamlrun command is not
installed. Moreover, the ``custom runtime'' mode enables static
linking of Caml code with user-defined C functions, as described in
chapter 18.
Unix:

Never use the strip command on executables produced by ocamlc -custom.
This would remove the bytecode part of the executable.

-dllib-llibname

Arrange for the C shared library dlllibname.so
(dlllibname.dll under Windows) to be loaded dynamically
by the run-time system ocamlrun at program start-up time.

-dllpathdir

Adds the directory dir to the run-time search path for shared
C libraries. At link-time, shared libraries are searched in the
standard search path (the one corresponding to the -I option).
The -dllpath option simply stores dir in the produced
executable file, where ocamlrun can find it and exploit it as
described in section 10.3.

-dtypes

Dump detailed type information. The information for file x.ml
is put into file x.annot. In case of a type error, dump
all the information inferred by the type-checker before the error.
The x.annot file can be used with the emacs commands given in
emacs/caml-types.el to display types interactively.

-g

Add debugging information while compiling and linking. This option is
required in order to be able to debug the program with ocamldebug
(see chapter 16).

-i

Cause the compiler to print all defined names (with their inferred
types or their definitions) when compiling an implementation (.ml
file). No compiled files (.cmo and .cmi files) are produced.
This can be useful to check the types inferred by the
compiler. Also, since the output follows the syntax of interfaces, it
can help in writing an explicit interface (.mli file) for a file:
just redirect the standard output of the compiler to a .mli file,
and edit that file to remove all declarations of unexported names.

-Idirectory

Add the given directory to the list of directories searched for
compiled interface files (.cmi), compiled object code files
(.cmo), libraries (.cma), and C libraries specified with
-cclib -lxxx. By default, the current directory is
searched first, then the standard library directory. Directories added
with -I are searched after the current directory, in the order in
which they were given on the command line, but before the standard
library directory.

If the given directory starts with +, it is taken relative to the
standard library directory. For instance, -I +labltk adds the
subdirectory labltk of the standard library to the search path.

-implfilename

Compile the file filename as an implementation file, even if its
extension is not .ml.

-intffilename

Compile the file filename as an interface file, even if its
extension is not .mli.

-linkall

Force all modules contained in libraries to be linked in. If this
flag is not given, unreferenced modules are not linked in. When
building a library (-a flag), setting the -linkall flag forces all
subsequent links of programs involving that library to link all the
modules contained in the library.

-make-runtime

Build a custom runtime system (in the file specified by option -o)
incorporating the C object files and libraries given on the command
line. This custom runtime system can be used later to execute
bytecode executables produced with the
ocamlc -use-runtimeruntime-name option.
See section 18.1.6 for more information.

-noassert

Turn assertion checking off: assertions are not compiled.
This flag has no effect when linking already compiled files.

-noautolink

When linking .cma libraries, ignore -custom, -cclib and -ccopt
options potentially contained in the libraries (if these options were
given when building the libraries). This can be useful if a library
contains incorrect specifications of C libraries or C options; in this
case, during linking, set -noautolink and pass the correct C
libraries and options on the command line.

-nolabels

Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.

-oexec-file

Specify the name of the output file produced by the linker. The
default output name is a.out, in keeping with the Unix tradition. If
the -a option is given, specify the name of the library produced.
If the -output-obj option is given, specify the name of the output
file produced.

-output-obj

Cause the linker to produce a C object file instead of a bytecode
executable file. This is useful to wrap Caml code as a C library,
callable from any C program. See chapter 18,
section 18.7.5. The name of the output object file is
camlprog.o by default; it can be set with the -o option.

-pack

Build a bytecode object file (.cmo file) and its associated compiled
interface (.cmi) that combines the object
files given on the command line, making them appear as sub-modules of
the output .cmo file. The name of the output .cmo file must be
given with the -o option. For instance,

ocamlc -pack -o p.cmo a.cmo b.cmo c.cmo

generates compiled files p.cmo and p.cmi describing a compilation
unit having three sub-modules A, B and C, corresponding to the
contents of the object files a.cmo, b.cmo and c.cmo. These
contents can be referenced as P.A, P.B and P.C in the remainder
of the program.

-ppcommand

Cause the compiler to call the given command as a preprocessor
for each source file. The output of command is redirected to
an intermediate file, which is compiled. If there are no compilation
errors, the intermediate file is deleted afterwards. The name of this
file is built from the basename of the source file with the extension
.ppi for an interface (.mli) file and .ppo for an implementation
(.ml) file.

-principal

Check information path during type-checking, to make sure that all
types are derived in a principal way. When using labelled arguments
and/or polymorphic methods, this flag is required to ensure future
versions of the compiler will be able to infer types correctly, even
if internal algorithms change.
All programs accepted in -principal mode are also accepted in
default mode with equivalent types, but different binary signatures,
and this may slow down type checking; yet this is a good idea to
use it once before publishing source code.

-rectypes

Allow arbitrary recursive types during type-checking. By default,
only recursive types where the recursion goes through an object type
are supported.

-thread

Compile or link multithreaded programs, in combination with the
system threads library described in chapter 24.

-unsafe

Turn bound checking off on array and string accesses (the v.(i) and
s.[i] constructs). Programs compiled with -unsafe are therefore
slightly faster, but unsafe: anything can happen if the program
accesses an array or string outside of its bounds.

-use-runtimeruntime-name

Generate a bytecode executable file that can be executed on the custom
runtime system runtime-name, built earlier with
ocamlc -make-runtimeruntime-name.
See section 18.1.6 for more information.

-v

Print the version number of the compiler and the location of the
standard library directory, then exit.

-verbose

Print all external commands before they are executed, in particular
invocations of the C compiler and linker in -custom mode. Useful to
debug C library problems.

-version

Print the version number of the compiler in short form (e.g. 3.06),
then exit.

-vmthread

Compile or link multithreaded programs, in combination with the
VM-level threads library described in chapter 24.

-wwarning-list

Enable or disable warnings according to the argument
warning-list. The argument is a string of one or several
characters, with the following meaning for each character:

A/a

enable/disable all warnings.

C/c

enable/disable warnings for suspicious comments.

D/d

enable/disable warnings for deprecated features.

E/e

enable/disable warnings for fragile pattern matchings
(matchings that would remain complete if additional constructors are
added to a variant type involved).

Turn the warnings indicated in the argument warning-list into
errors. The compiler will stop on an error as soon as one of these
warnings is emitted, instead of going on. The warning-list
is a string of one or several characters, with the same meaning as for
the -w option: an uppercase character turns the corresponding
warning into an error, a lowercase character leaves it as a warning.
The default setting is -warn-error a (all warnings are not treated
as errors).

This short section is intended to clarify the relationship between the
names of the modules corresponding to compilation units and the names
of the files that contain their compiled interface and compiled
implementation.

The compiler always derives the module name by taking the capitalized
base name of the source file (.ml or .mli file). That is, it
strips the leading directory name, if any, as well as the .ml or
.mli suffix; then, it set the first letter to uppercase, in order to
comply with the requirement that module names must be capitalized.
For instance, compiling the file mylib/misc.ml provides an
implementation for the module named Misc. Other compilation units
may refer to components defined in mylib/misc.ml under the names
Misc.name; they can also do open Misc, then use unqualified
names name.

The .cmi and .cmo files produced by the compiler have the same
base name as the source file. Hence, the compiled files always have
their base name equal (modulo capitalization of the first letter) to
the name of the module they describe (for .cmi files) or implement
(for .cmo files).

When the compiler encounters a reference to a free module identifier
Mod, it looks in the search path for a file named Mod.cmi or mod.cmi
and loads the compiled interface
contained in that file. As a consequence, renaming .cmi files is not
advised: the name of a .cmi file must always correspond to the name
of the compilation unit it implements. It is admissible to move them
to another directory, if their base name is preserved, and the correct
-I options are given to the compiler. The compiler will flag an
error if it loads a .cmi file that has been renamed.

Compiled bytecode files (.cmo files), on the other hand, can be
freely renamed once created. That's because the linker never attempts
to find by itself the .cmo file that implements a module with a
given name: it relies instead on the user providing the list of .cmo
files by hand.

This section describes and explains the most frequently encountered
error messages.

Cannot find file filename

The named file could not be found in the current directory, nor in the
directories of the search path. The filename is either a
compiled interface file (.cmi file), or a compiled bytecode file
(.cmo file). If filename has the format mod.cmi, this
means you are trying to compile a file that references identifiers
from module mod, but you have not yet compiled an interface for
module mod. Fix: compile mod.mli or mod.ml
first, to create the compiled interface mod.cmi.

If filename has the format mod.cmo, this
means you are trying to link a bytecode object file that does not
exist yet. Fix: compile mod.ml first.

If your program spans several directories, this error can also appear
because you haven't specified the directories to look into. Fix: add
the correct -I options to the command line.

Corrupted compiled interface filename

The compiler produces this error when it tries to read a compiled
interface file (.cmi file) that has the wrong structure. This means
something went wrong when this .cmi file was written: the disk was
full, the compiler was interrupted in the middle of the file creation,
and so on. This error can also appear if a .cmi file is modified after
its creation by the compiler. Fix: remove the corrupted .cmi file,
and rebuild it.

This expression has type t1, but is used with type t2

This is by far the most common type error in programs. Type t1 is
the type inferred for the expression (the part of the program that is
displayed in the error message), by looking at the expression itself.
Type t2 is the type expected by the context of the expression; it
is deduced by looking at how the value of this expression is used in
the rest of the program. If the two types t1 and t2 are not
compatible, then the error above is produced.

In some cases, it is hard to understand why the two types t1 and
t2 are incompatible. For instance, the compiler can report that
``expression of type foo cannot be used with type foo'', and it
really seems that the two types foo are compatible. This is not
always true. Two type constructors can have the same name, but
actually represent different types. This can happen if a type
constructor is redefined. Example:

This result in the error message ``expression C of type foo cannot
be used with type foo''.

The type of this expression, t, contains type variables
that cannot be generalized

Type variables ('a, 'b, ...) in a type t can be in either
of two states: generalized (which means that the type t is valid
for all possible instantiations of the variables) and not generalized
(which means that the type t is valid only for one instantiation
of the variables). In a let binding let name = expr,
the type-checker normally generalizes as many type variables as
possible in the type of expr. However, this leads to unsoundness
(a well-typed program can crash) in conjunction with polymorphic
mutable data structures. To avoid this, generalization is performed at
let bindings only if the bound expression expr belongs to the
class of ``syntactic values'', which includes constants, identifiers,
functions, tuples of syntactic values, etc. In all other cases (for
instance, expr is a function application), a polymorphic mutable
could have been created and generalization is therefore turned off for
all variables occuring in contravariant or non-variant branches of the
type. For instance, if the type of a non-value is 'a list the
variable is generalizable (list is a covariant type constructor),
but not in 'a list -> 'a list (the left branch of -> is
contravariant) or 'a ref (ref is non-variant).

Non-generalized type variables in a type cause no difficulties inside
a given structure or compilation unit (the contents of a .ml file,
or an interactive session), but they cannot be allowed inside
signatures nor in compiled interfaces (.cmi file), because they
could be used inconsistently later. Therefore, the compiler
flags an error when a structure or compilation unit defines a value
name whose type contains non-generalized type variables. There
are two ways to fix this error:

Add a type constraint or a .mli file to give a monomorphic
type (without type variables) to name. For instance, instead of
writing

This error appears when trying to link an incomplete or incorrectly
ordered set of files. Either you have forgotten to provide an
implementation for the compilation unit named mod on the command line
(typically, the file named mod.cmo, or a library containing
that file). Fix: add the missing .ml or .cmo file to the command
line. Or, you have provided an implementation for the module named
mod, but it comes too late on the command line: the
implementation of mod must come before all bytecode object files
that reference mod. Fix: change the order of .ml and .cmo
files on the command line.

Of course, you will always encounter this error if you have mutually
recursive functions across modules. That is, function Mod1.f calls
function Mod2.g, and function Mod2.g calls function Mod1.f.
In this case, no matter what permutations you perform on the command
line, the program will be rejected at link-time. Fixes:

This error appears when trying to link code that calls external
functions written in C. As explained in
chapter 18, such code must be linked with C libraries that
implement the required f C function. If the C libraries in
question are not shared libraries (DLLs), the code must be linked in
``custom runtime'' mode. Fix: add the required C libraries to the
command line, and possibly the -custom option.

This chapter describes the toplevel system for Objective Caml, that permits interactive use of the Objective Caml system
through a read-eval-print loop. In this mode, the system repeatedly
reads Caml phrases from the input, then typechecks, compile and
evaluate them, then prints the inferred type and result value, if
any. The system prints a # (sharp) prompt before reading each
phrase.

Input to the toplevel can span several lines. It is terminated by ;; (a
double-semicolon). The toplevel input consists in one or several
toplevel phrases, with the following syntax:

toplevel-input

::=

{ toplevel-phrase } ;;

toplevel-phrase

::=

definition

|

expr

|

#identdirective-argument

definition

::=

let [rec] let-binding { andlet-binding }

|

externalvalue-name:typexpr=external-declaration

|

type-definition

|

exception-definition

|

modulemodule-name [ :module-type ] =module-expr

|

moduletypemodtype-name=module-type

|

openmodule-path

directive-argument

::=

nothing

|

string-literal

|

integer-literal

|

value-path

A phrase can consist of a definition, similar to those found in
implementations of compilation units or in struct ... end
module expressions. The definition can bind value names, type names,
an exception, a module name, or a module type name. The toplevel
system performs the bindings, then prints the types and values (if
any) for the names thus defined.

A phrase may also consist in a open directive (see
section 6.11), or a value expression
(section 6.7). Expressions are simply evaluated,
without performing any bindings, and the value of the expression is
printed.

Finally, a phrase can also consist in a toplevel directive,
starting with # (the sharp sign). These directives control the
behavior of the toplevel; they are listed below in
section 9.2.

options are described below.
objects are filenames ending in .cmo or .cma; they are
loaded into the interpreter immediately after options are set.
scriptfile is any file name not ending in .cmo or .cma.

If no scriptfile is given on the command line, the toplevel system
enters interactive mode: phrases are read on standard input, results
are printed on standard output, errors on standard error. End-of-file
on standard input terminates ocaml (see also the #quit directive
in section 9.2).

On start-up (before the first phrase is read), if the file
.ocamlinit exists in the current directory,
its contents are read as a sequence of Objective Caml phrases
and executed as per the #use directive
described in section 9.2.
The evaluation outcode for each phrase are not displayed.
If the current directory does not contain an .ocamlinit file, but
the user's home directory (environment variable HOME) does, the
latter is read and executed as described below.

The toplevel system does not perform line editing, but it can
easily be used in conjunction with an external line editor such as
ledit, ocaml2 or rlwrap
(see the
Caml Hump).
Another option is to use ocaml under Gnu Emacs, which gives the
full editing power of Emacs (command run-caml from library inf-caml).

At any point, the parsing, compilation or evaluation of the current
phrase can be interrupted by pressing ctrl-C (or, more precisely,
by sending the INTR signal to the ocaml process). The toplevel
then immediately returns to the # prompt.

If scriptfile is given on the command-line to ocaml, the toplevel
system enters script mode: the contents of the file are read as a
sequence of Objective Caml phrases and executed, as per the #use
directive (section 9.2). The outcome of the
evaluation is not printed. On reaching the end of file, the ocaml
command exits immediately. No commands are read from standard input.
Sys.argv is transformed, ignoring all Objective Caml parameters, and
starting with the script file name in Sys.argv.(0).

In script mode, the first line of the script is ignored if it starts
with #!. Thus, it should be possible to make the script
itself executable and put as first line #!/usr/local/bin/ocaml,
thus calling the toplevel system automatically when the script is
run. However, ocaml itself is a #! script on most installations
of Objective Caml, and Unix kernels usually do not handle nested #!
scripts. A better solution is to put the following as the first line
of the script:

#!/usr/local/bin/ocamlrun /usr/local/bin/ocaml

Windows:

In addition to the text-only command ocaml.exe, which works exactly
as under Unix (see above), a graphical user interface for the
toplevel is available under the name ocamlwin.exe. It should be
launched from the Windows file manager or program manager.
This interface provides a text window in which commands can be entered
and edited, and the toplevel responses are printed.

The following command-line options are recognized by the ocaml command.

-Idirectory

Add the given directory to the list of directories searched for
source and compiled files. By default, the current directory is
searched first, then the standard library directory. Directories added
with -I are searched after the current directory, in the order in
which they were given on the command line, but before the standard
library directory.

If the given directory starts with +, it is taken relative to the
standard library directory. For instance, -I +labltk adds the
subdirectory labltk of the standard library to the search path.

Directories can also be added to the search path once
the toplevel is running with the #directory directive
(section 9.2).

-nolabels

Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.

-principal

Check information path during type-checking, to make sure that all
types are derived in a principal way. All programs accepted in
-principal mode are also accepted in default mode with equivalent
types.

-rectypes

Allow arbitrary recursive types during type-checking. By default,
only recursive types where the recursion goes through an object type
are supported.

-unsafe

See the corresponding option for ocamlc, chapter 8.
Turn bound checking off on array and string accesses (the v.(i) and
s.[i] constructs). Programs compiled with -unsafe are therefore
slightly faster, but unsafe: anything can happen if the program
accesses an array or string outside of its bounds.

-wwarning-list

Enable or disable warnings according to the argument warning-list.

Unix:

The following environment variables are also consulted:

LC_CTYPE

If set to iso_8859_1, accented characters (from the
ISO Latin-1 character set) in string and character literals are
printed as is; otherwise, they are printed as decimal escape sequences
(\ddd).

TERM

When printing error messages, the toplevel system
attempts to underline visually the location of the error. It
consults the TERM variable to determines the type of output terminal
and look up its capabilities in the terminal database.

The following directives control the toplevel behavior, load files in
memory, and trace program execution.

Note: all directives start with a # (sharp) symbol. This #
must be typed before the directive, and must not be confused with the
# prompt displayed by the interactive loop. For instance,
typing #quit;; will exit the toplevel loop, but typing quit;;
will result in an ``unbound value quit'' error.

#quit;;

Exit the toplevel loop and terminate the ocaml command.

#labels bool;;

Ignore labels in function types if argument is false, or switch back
to default behaviour (commuting style) if argument is true.

#warnings "warning-list";;

Enable or disable warnings according to the argument.

#directory "dir-name";;

Add the given directory to the list of directories searched for
source and compiled files.

#cd "dir-name";;

Change the current working directory.

#load "file-name";;

Load in memory a bytecode object file (.cmo file) produced by
the batch compiler ocamlc.

#use "file-name";;

Read, compile and execute source phrases from the given file.
This is textual inclusion: phrases are processed just as if
they were typed on standard input. The reading of the file stops at
the first error encountered.

#install_printer printer-name;;

This directive registers the function named printer-name (a
value path) as a printer for values whose types match the argument
type of the function. That is, the toplevel loop will call
printer-name when it has such a value to print.

The printing function printer-name should have type
Format.formatter->t->unit, where t is the
type for the values to be printed, and should output its textual
representation for the value of type t on the given formatter,
using the functions provided by the Format library. For backward
compatibility, printer-name can also have type
t->unit and should then output on the standard
formatter, but this usage is deprecated.

#remove_printer printer-name;;

Remove the named function from the table of toplevel printers.

#trace function-name;;

After executing this directive, all calls to the function named
function-name will be ``traced''. That is, the argument and the
result are displayed for each call, as well as the exceptions escaping
out of the function, raised either by the function itself or by
another function it calls. If the function is curried, each argument
is printed as it is passed to the function.

#untrace function-name;;

Stop tracing the given function.

#untrace_all;;

Stop tracing all functions traced so far.

#print_depth n;;

Limit the printing of values to a maximal depth of n.
The parts of values whose depth exceeds n are printed as ...
(ellipsis).

#print_length n;;

Limit the number of value nodes printed to at most n.
Remaining parts of values are printed as ... (ellipsis).

Toplevel phrases can refer to identifiers defined in compilation units
with the same mechanisms as for separately compiled units: either by
using qualified names (Modulename.localname), or by using
the open construct and unqualified names (see section 6.3).

However, before referencing another compilation unit, an
implementation of that unit must be present in memory.
At start-up, the toplevel system contains implementations for all the
modules in the the standard library. Implementations for user modules
can be entered with the #load directive described above. Referencing
a unit for which no implementation has been provided
results in the error ``Reference to undefined global `...' ''.

Note that entering open Mod merely accesses the compiled
interface (.cmi file) for Mod, but does not load the
implementation of Mod, and does not cause any error if no
implementation of Mod has been loaded. The error
``reference to undefined global Mod'' will occur only when
executing a value or module definition that refers to Mod.

This section describes and explains the most frequently encountered
error messages.

Cannot find file filename

The named file could not be found in the current directory, nor in the
directories of the search path.

If filename has the format mod.cmi, this
means you have referenced the compilation unit mod, but its
compiled interface could not be found. Fix: compile mod.mli or
mod.ml first, to create the compiled interface mod.cmi.

If filename has the format mod.cmo, this
means you are trying to load with #load a bytecode object file that
does not exist yet. Fix: compile mod.ml first.

If your program spans several directories, this error can also appear
because you haven't specified the directories to look into. Fix: use
the #directory directive to add the correct directories to the
search path.

The ocamlrun command comprises three main parts: the bytecode
interpreter, that actually executes bytecode files; the memory
allocator and garbage collector; and a set of C functions that
implement primitive operations such as input/output.

The usage for ocamlrun is:

ocamlrun options bytecode-executable arg1 ... argn

The first non-option argument is taken to be the name of the file
containing the executable bytecode. (That file is searched in the
executable path as well as in the current directory.) The remaining
arguments are passed to the Caml program, in the string array
Sys.argv. Element 0 of this array is the name of the
bytecode executable file; elements 1 to n are the remaining
arguments arg1 to argn.

As mentioned in chapter 8, the bytecode executable files
produced by the ocamlc command are self-executable, and manage to
launch the ocamlrun command on themselves automatically. That is,
assuming caml.out is a bytecode executable file,

caml.out arg1 ... argn

works exactly as

ocamlrun caml.out arg1 ... argn

Notice that it is not possible to pass options to ocamlrun when
invoking caml.out directly.

Windows:

Under several versions of Windows, bytecode executable files are
self-executable only if their name ends in .exe. It is recommended
to always give .exe names to bytecode executables, e.g. compile
with ocamlc -o myprog.exe ... rather than ocamlc -o myprog ....

When the program aborts due to an uncaught exception, print a detailed
``back trace'' of the execution, showing where the exception was
raised and which function calls were outstanding at this point. The
back trace is printed only if the bytecode executable contains
debugging information, i.e. was compiled and linked with the -g
option to ocamlc set. This is equivalent to setting the b flag
in the OCAMLRUNPARAM environment variable (see below).

The directory containing the Objective Caml standard
library. (If OCAMLLIB is not set, CAMLLIB will be used instead.)
Used to locate the ld.conf configuration file for
dynamic loading (see section 10.3). If not set,
default to the library directory specified when compiling Objective Caml.

OCAMLRUNPARAM

Set the runtime system options
and garbage collection parameters.
(If OCAMLRUNPARAM is not set, CAMLRUNPARAM will be used instead.)
This variable must be a sequence of parameter specifications.
A parameter specification is an option letter followed by an =
sign, a decimal number (or an hexadecimal number prefixed by 0x),
and an optional multiplier. There are
nine options, six of which correspond to the fields of the
control record documented in
Module Gc.

b

(backtrace) Trigger the printing of a stack backtrace
when an uncaught exception aborts the program.
This option takes no argument.

p

(parser trace) Turn on debugging support for
ocamlyacc-generated parsers. When this option is on,
the pushdown automaton that executes the parsers prints a
trace of its actions. This option takes no argument.

s

(minor_heap_size) Size of the minor heap. (in words)

i

(major_heap_increment) Default size increment for the
major heap. (in words)

o

(space_overhead) The major GC speed setting.

O

(max_overhead) The heap compaction trigger setting.

v

(verbose) What GC messages to print to stderr. This
is a sum of values selected from the following:

The multiplier is k, M, or G, for multiplication by 210,
220, and 230 respectively.
For example, on a 32-bit machine, under bash the command

export OCAMLRUNPARAM='b,s=256k,v=0x015'

tells a subsequent ocamlrun to print backtraces for uncaught exceptions,
set its initial minor heap size to 1 megabyte and
print a message at the start of each major GC cycle, when the heap
size changes, and when compaction is triggered.

CAMLRUNPARAM

If OCAMLRUNPARAM is not found in the
environment, then CAMLRUNPARAM will be used instead. If
CAMLRUNPARAM is not found, then the default values will be used.

On platforms that support dynamic loading, ocamlrun can link
dynamically with C shared libraries (DLLs) providing additional C primitives
beyond those provided by the standard runtime system. The names for
these libraries are provided at link time as described in
section 18.1.4), and recorded in the bytecode executable
file; ocamlrun, then, locates these libraries and resolves references
to their primitives when the bytecode executable program starts.

The ocamlrun command searches shared libraries in the following
directories, in the order indicated:

Directories specified on the ocamlrun command line with the
-I option.

Directories specified at link-time via the -dllpath option to
ocamlc. (These directories are recorded in the bytecode executable
file.)

Directories specified in the file ld.conf. This file resides
in the Objective Caml standard library directory, and lists directory
names (one per line) to be searched. Typically, it contains only one
line naming the stublibs subdirectory of the Objective Caml standard
library directory. Users can add there the names of other directories
containing frequently-used shared libraries; however, for consistency
of installation, we recommend that shared libraries are installed
directly in the system stublibs directory, rather than adding lines
to the ld.conf file.

Default directories searched by the system dynamic loader.
Under Unix, these generally include /lib and /usr/lib, plus the
directories listed in the file /etc/ld.so.conf and the environment
variable LD_LIBRARY_PATH. Under Windows, these include the Windows
system directories, plus the directories listed in the PATH
environment variable.

This section describes and explains the most frequently encountered
error messages.

filename: no such file or directory

If filename is the name of a self-executable bytecode file, this
means that either that file does not exist, or that it failed to run
the ocamlrun bytecode interpreter on itself. The second possibility
indicates that Objective Caml has not been properly installed on your
system.

Cannot exec ocamlrun

(When launching a self-executable bytecode file.) The ocamlrun
could not be found in the executable path. Check that Objective Caml
has been properly installed on your system.

Cannot find the bytecode file

The file that ocamlrun is trying to execute (e.g. the file given as
first non-option argument to ocamlrun) either does not exist, or is
not a valid executable bytecode file.

Truncated bytecode file

The file that ocamlrun is trying to execute is not a valid executable
bytecode file. Probably it has been truncated or mangled since
created. Erase and rebuild it.

Uncaught exception

The program being executed contains a ``stray'' exception. That is,
it raises an exception at some point, and this exception is never
caught. This causes immediate termination of the program. The name of
the exception is printed, along with its string and integer arguments
(arguments of more complex types are not correctly printed).
To locate the context of the uncaught exception, compile the program
with the -g option and either run it again under the ocamldebug
debugger (see chapter 16), or run it with ocamlrun -b
or with the OCAMLRUNPARAM environment variable set to b=1.

Out of memory

The program being executed requires more memory than available. Either
the program builds excessively large data structures; or the program
contains too many nested function calls, and the stack overflows. In
some cases, your program is perfectly correct, it just requires more
memory than your machine provides. In other cases, the ``out of
memory'' message reveals an error in your program: non-terminating
recursive function, allocation of an excessively large array or
string, attempts to build an infinite list or other data structure,
...

To help you diagnose this error, run your program with the -v option
to ocamlrun, or with the OCAMLRUNPARAM environment variable set to
v=63. If it displays lots of ``Growing stack...''
messages, this is probably a looping recursive function. If it
displays lots of ``Growing heap...'' messages, with the heap size
growing slowly, this is probably an attempt to construct a data
structure with too many (infinitely many?) cells. If it displays few
``Growing heap...'' messages, but with a huge increment in the
heap size, this is probably an attempt to build an excessively large
array or string.

The native-code compiler is only available on certain platforms.
It produces code that runs faster than the bytecode produced by
ocamlc, at the cost of increased compilation time and executable code
size. Compatibility with the bytecode compiler is extremely high: the
same source code should run identically when compiled with ocamlc and
ocamlopt.

It is not possible to mix native-code object files produced by ocamlc
with bytecode object files produced by ocamlopt: a program must be
compiled entirely with ocamlopt or entirely with ocamlc. Native-code
object files produced by ocamlopt cannot be loaded in the toplevel
system ocaml.

The ocamlopt command has a command-line interface very close to that
of ocamlc. It accepts the same types of arguments, and processes them
sequentially:

Arguments ending in .mli are taken to be source files for
compilation unit interfaces. Interfaces specify the names exported by
compilation units: they declare value names with their types, define
public data types, declare abstract data types, and so on. From the
file x.mli, the ocamlopt compiler produces a compiled interface
in the file x.cmi. The interface produced is identical to that
produced by the bytecode compiler ocamlc.

Arguments ending in .ml are taken to be source files for compilation
unit implementations. Implementations provide definitions for the
names exported by the unit, and also contain expressions to be
evaluated for their side-effects. From the file x.ml, the ocamlopt
compiler produces two files: x.o, containing native object code,
and x.cmx, containing extra information for linking and
optimization of the clients of the unit. The compiled implementation
should always be referred to under the name x.cmx (when given
a .o file, ocamlopt assumes that it contains code compiled from C,
not from Caml).

The implementation is checked against the interface file x.mli
(if it exists) as described in the manual for ocamlc
(chapter 8).

Arguments ending in .cmx are taken to be compiled object code. These
files are linked together, along with the object files obtained
by compiling .ml arguments (if any), and the Caml standard
library, to produce a native-code executable program. The order in
which .cmx and .ml arguments are presented on the command line is
relevant: compilation units are initialized in that order at
run-time, and it is a link-time error to use a component of a unit
before having initialized it. Hence, a given x.cmx file must come
before all .cmx files that refer to the unit x.

Arguments ending in .cmxa are taken to be libraries of object code.
Such a library packs in two files (lib.cmxa and lib.a)
a set of object files (.cmx/.o files). Libraries are build with
ocamlopt -a (see the description of the -a option below). The object
files contained in the library are linked as regular .cmx files (see
above), in the order specified when the library was built. The only
difference is that if an object file contained in a library is not
referenced anywhere in the program, then it is not linked in.

Arguments ending in .c are passed to the C compiler, which generates
a .o object file. This object file is linked with the program.

Arguments ending in .o, .a or .so (.obj, .lib and .dll
under Windows) are assumed to be C object files and
libraries. They are linked with the program.

The output of the linking phase is a regular Unix executable file. It
does not need ocamlrun to run.

Build a library (.cmxa/.a file) with the object files (.cmx/.o
files) given on the command line, instead of linking them into an
executable file. The name of the library can be set with the -o
option. The default name is library.cmxa.

If -cclib or -ccopt options are passed on the command
line, these options are stored in the resulting .cmxa library. Then,
linking with this library automatically adds back the
-cclib and -ccopt options as if they had been provided on the
command line, unless the -noautolink option is given.

-c

Compile only. Suppress the linking phase of the
compilation. Source code files are turned into compiled files, but no
executable file is produced. This option is useful to
compile modules separately.

-ccccomp

Use ccomp as the C linker called to build the final executable
and as the C compiler for compiling .c source files.

-cclib-llibname

Pass the -llibname option to the linker. This causes the given
C library to be linked with the program.

-ccoptoption

Pass the given option to the C compiler and linker. For instance,
-ccopt -Ldir causes the C linker to search for C libraries in
directory dir.

-compact

Optimize the produced code for space rather than for time. This
results in slightly smaller but slightly slower programs. The default is to
optimize for speed.

-dtypes

Dump detailed type information. The information for file x.ml
is put into file x.annot. In case of a type error, dump
all the information inferred by the type-checker before the error.
The x.annot file can be used with the emacs commands given in
emacs/caml-types.el to display types interactively.

-i

Cause the compiler to print all defined names (with their inferred
types or their definitions) when compiling an implementation (.ml
file). No compiled files (.cmo and .cmi files) are produced.
This can be useful to check the types inferred by the
compiler. Also, since the output follows the syntax of interfaces, it
can help in writing an explicit interface (.mli file) for a file:
just redirect the standard output of the compiler to a .mli file,
and edit that file to remove all declarations of unexported names.

-Idirectory

Add the given directory to the list of directories searched for
compiled interface files (.cmi), compiled object code files
(.cmx), and libraries (.cmxa). By default, the current directory
is searched first, then the standard library directory. Directories
added with -I are searched after the current directory, in the order
in which they were given on the command line, but before the standard
library directory.

If the given directory starts with +, it is taken relative to the
standard library directory. For instance, -I +labltk adds the
subdirectory labltk of the standard library to the search path.

-inlinen

Set aggressiveness of inlining to n, where n is a positive
integer. Specifying -inline 0 prevents all functions from being
inlined, except those whose body is smaller than the call site. Thus,
inlining causes no expansion in code size. The default aggressiveness,
-inline 1, allows slightly larger functions to be inlined, resulting
in a slight expansion in code size. Higher values for the -inline
option cause larger and larger functions to become candidate for
inlining, but can result in a serious increase in code size.

-linkall

Forces all modules contained in libraries to be linked in. If this
flag is not given, unreferenced modules are not linked in. When
building a library (-a flag), setting the -linkall flag forces all
subsequent links of programs involving that library to link all the
modules contained in the library.

-noassert

Turn assertion checking off: assertions are not compiled.
This flag has no effect when linking already compiled files.

-noautolink

When linking .cmxa libraries, ignore -cclib and -ccopt
options potentially contained in the libraries (if these options were
given when building the libraries). This can be useful if a library
contains incorrect specifications of C libraries or C options; in this
case, during linking, set -noautolink and pass the correct C
libraries and options on the command line.

-nolabels

Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.

-oexec-file

Specify the name of the output file produced by the linker. The
default output name is a.out, in keeping with the Unix tradition. If
the -a option is given, specify the name of the library produced.
If the -output-obj option is given, specify the name of the output
file produced.

-output-obj

Cause the linker to produce a C object file instead of an executable
file. This is useful to wrap Caml code as a C library,
callable from any C program. See chapter 18,
section 18.7.5. The name of the output object file is
camlprog.o by default; it can be set with the -o option.

-p

Generate extra code to write profile information when the program is
executed. The profile information can then be examined with the
analysis program gprof. (See chapter 17 for more
information on profiling.) The -p option must be given both at
compile-time and at link-time. Linking object files not compiled with
-p is possible, but results in less precise profiling.

Unix:

See the Unix manual page for gprof(1) for more
information about the profiles.

Full support for gprof is only available for certain platforms
(currently: Intel x86/Linux and Alpha/Digital Unix).
On other platforms, the -p option will result in a less precise
profile (no call graph information, only a time profile).

Windows:

The -p option does not work under Windows.

-pack

Build an object file (.cmx/.o file) and its associated compiled
interface (.cmi) that combines the .cmx object
files given on the command line, making them appear as sub-modules of
the output .cmx file. The name of the output .cmx file must be
given with the -o option. For instance,

ocamlopt -pack -o p.cmx a.cmx b.cmx c.cmx

generates compiled files p.cmx, p.o and p.cmi describing a
compilation unit having three sub-modules A, B and C,
corresponding to the contents of the object files a.cmx, b.cmx and
c.cmx. These contents can be referenced as P.A, P.B and P.C
in the remainder of the program.

Unix:

The -pack option is available only under platforms that
provide the GNU Binutils tools nm and objcopy.

-ppcommand

Cause the compiler to call the given command as a preprocessor
for each source file. The output of command is redirected to
an intermediate file, which is compiled. If there are no compilation
errors, the intermediate file is deleted afterwards. The name of this
file is built from the basename of the source file with the extension
.ppi for an interface (.mli) file and .ppo for an implementation
(.ml) file.

-principal

Check information path during type-checking, to make sure that all
types are derived in a principal way. All programs accepted in
-principal mode are also accepted in default mode with equivalent
types, but different binary signatures.

-rectypes

Allow arbitrary recursive types during type-checking. By default,
only recursive types where the recursion goes through an object type
are supported.

-S

Keep the assembly code produced during the compilation. The assembly
code for the source file x.ml is saved in the file x.s.

-thread

Compile or link multithreaded programs, in combination with the
system threads library described in chapter 24.

-unsafe

Turn bound checking off on array and string accesses (the v.(i) and
s.[i] constructs). Programs compiled with -unsafe are therefore
faster, but unsafe: anything can happen if the program accesses an
array or string outside of its bounds.

-v

Print the version number of the compiler and the location of the
standard library directory, then exit.

-verbose

Print all external commands before they are executed, in particular
invocations of the assembler, C compiler, and linker.

-version

Print the version number of the compiler in short form (e.g. 3.06),
then exit.

-wwarning-list

Enable or disable warnings according to the argument
warning-list. The argument is a string of one or several
characters, with the following meaning for each character:

enable/disable warnings for statements that do not have
type unit (e.g. expr1; expr2 when expr1 does not
have type unit).

U/u

enable/disable warnings for unused (redundant) match cases.

V/v

enable/disable warnings for hidden instance variables.

X/x

enable/disable all other warnings.

The default setting is -w Al (all warnings but labels enabled).

-warn-errorwarning-list

Turn the warnings indicated in the argument warning-list into
errors. The compiler will stop on an error as soon as one of these
warnings is emitted, instead of going on. The warning-list
is a string of one or several characters, with the same meaning as for
the -w option: an uppercase character turns the corresponding
warning into an error, a lowercase character leaves it as a warning.
The default setting is -warn-error a (all warnings are not treated
as errors).

-where

Print the location of the standard library.

Options for the IA32 architecture

Use the IA32 instructions to compute
trigonometric and exponential functions, instead of calling the
corresponding library routines. The functions affected are:
atan, atan2, cos, log, log10, sin, sqrt, and tan.
The resulting code runs faster, but the range of supported arguments
and the precision of the result can be reduced. In particular,
trigonometric operations cos, sin, tan have their range reduced to
[-264, 264].

Options for the Sparc architecture

The Sparc code generator supports the following additional options:

-march=v8

Generate SPARC version 8 code.

-march=v9

Generate SPARC version 9 code.

The default is to generate code for SPARC version 7, which runs on all
SPARC processors.

Executables generated by ocamlopt are native, statically-linked,
stand-alone executable files that can be invoked directly. They do
not depend on the ocamlrun bytecode runtime system.

During execution of an ocamlopt-generated executable,
the following environment variables are also consulted:

OCAMLRUNPARAM

Same usage as in ocamlrun
(see section 10.2), except that option l
is ignored (the operating system's stack size limit
is used instead) and option b is ignored (stack backtraces on
uncaught exceptions are not printed).

CAMLRUNPARAM

If OCAMLRUNPARAM is not found in the
environment, then CAMLRUNPARAM will be used instead. If
CAMLRUNPARAM is not found, then the default values will be used.

This section lists the known incompatibilities between the bytecode
compiler and the native-code compiler. Except on those points, the two
compilers should generate code that behave identically.

The following operations abort the program (via an hardware trap
or fatal Unix signal) instead of raising an exception:

stack overflow (except on IA32/Linux);

on the Alpha processor only, floating-point operations involving
infinite or denormalized numbers (all other processors supported by
ocamlopt treat these numbers correctly, as per the IEEE 754 standard).

In particular, notice that stack overflow caused by excessively deep
recursion is reported by most Unix kernels as a ``segmentation
violation'' signal.

Signals are detected only when the program performs an
allocation in the heap. That is, if a signal is delivered while in a
piece of code that does not allocate, its handler will not be called
until the next heap allocation.

The best way to avoid running into those incompatibilities is to never trap the Stack_overflow exception, thus treating it
as a fatal error both with the bytecode compiler and with the
native-code compiler.

This chapter describes two program generators: ocamllex, that
produces a lexical analyzer from a set of regular expressions with
associated semantic actions, and ocamlyacc, that produces a parser
from a grammar with associated semantic actions.

These program generators are very close to the well-known lex and
yacc commands that can be found in most C programming environments.
This chapter assumes a working knowledge of lex and yacc: while
it describes the input syntax for ocamllex and ocamlyacc and the
main differences with lex and yacc, it does not explain the basics
of writing a lexer or parser description in lex and yacc. Readers
unfamiliar with lex and yacc are referred to ``Compilers:
principles, techniques, and tools'' by Aho, Sethi and Ullman
(Addison-Wesley, 1986), or ``Lex & Yacc'', by Levine, Mason and
Brown (O'Reilly, 1992).

The ocamllex command produces a lexical analyzer from a set of regular
expressions with attached semantic actions, in the style of
lex. Assuming the input file is lexer.mll, executing

ocamllex lexer.mll

produces Caml code for a lexical analyzer in file lexer.ml.
This file defines one lexing function per entry point in the lexer
definition. These functions have the same names as the entry
points. Lexing functions take as argument a lexer buffer, and return
the semantic attribute of the corresponding entry point.

Lexer buffers are an abstract data type implemented in the standard
library module Lexing. The functions Lexing.from_channel,
Lexing.from_string and Lexing.from_function create
lexer buffers that read from an input channel, a character string, or
any reading function, respectively. (See the description of module
Lexing in chapter 20.)

When used in conjunction with a parser generated by ocamlyacc, the
semantic actions compute a value belonging to the type token defined
by the generated parsing module. (See the description of ocamlyacc
below.)

Specify the name of the output file produced by ocamllex.
Default is lexer.ml, ocamllex being invoked as
ocamllexlexer.mll.

-ml

Output code that does not use the Caml built-in automata
interpreter. Instead, the automaton is encoded by Caml functions.
This option is useful for debugging ocamllex, using it for
production lexers is not recommended.

The header and trailer sections are arbitrary Caml
text enclosed in curly braces. Either or both can be omitted. If
present, the header text is copied as is at the beginning of the
output file and the trailer text at the end. Typically, the
header section contains the open directives required
by the actions, and possibly some auxiliary functions used in the
actions.

Between the header and the entry points, one can give names to
frequently-occurring regular expressions. This is written
letident=regexp.
In regular expressions that follow this declaration, the identifier
ident can be used as shorthand for regexp.

The names of the entry points must be valid identifiers for Caml
values (starting with a lowercase letter).
Similarily, the arguments arg1...
argn must be valid identifiers for Caml.
Each entry point becomes a
Caml function that takes n+1 arguments,
the extra implicit last argument being of type Lexing.lexbuf.
Characters are read from the Lexing.lexbuf argument and matched
against the regular expressions provided in the rule, until a prefix
of the input matches one of the rule. The corresponding action is
then evaluated and returned as the result of the function.

If several regular expressions match a prefix of the input, the
``longest match'' rule applies: the regular expression that matches
the longest prefix of the input is selected. In case of tie, the
regular expression that occurs earlier in the rule is selected.

However, if lexer rules are introduced with the shortest keyword in
place of the parse keyword, then the ``shortest match'' rule applies:
the shortest prefix of the input is selected. In case of tie, the
regular expression that occurs earlier in the rule is still selected.
This feature is not intended for use in ordinary lexical analyzers, it
may facilitate the use of ocamllex as a simple text processing tool.

The regular expressions are in the style of lex, with a more
Caml-like syntax.

'char'

A character constant, with the same syntax as Objective Caml character
constants. Match the denoted character.

_

(Underscore.) Match any character.

eof

Match the end of the lexer input.Note: On some systems, with interactive input, an end-of-file
may be followed by more characters. However, ocamllex will not
correctly handle regular expressions that contain eof followed by
something else.

"string"

A string constant, with the same syntax as Objective Caml string
constants. Match the corresponding sequence of characters.

[character-set]

Match any single character belonging to the given
character set. Valid character sets are: single
character constants 'c'; ranges of characters
'c1'-'c2' (all characters between c1 and c2,
inclusive); and the union of two or more character sets, denoted by
concatenation.

[^character-set]

Match any single character not belonging to the given character set.

regexp1#regexp2

(Difference of character sets).
Regular expressions regexp1 and regexp2 must be character sets
defined with [... ] (or a a single character expression or
underscore _).
Match the difference of the two specified character sets.

regexp*

(Repetition.) Match the concatenation of zero or more
strings that match regexp.

regexp+

(Strict repetition.) Match the concatenation of one or more
strings that match regexp.

regexp?

(Option.) Match either the empty string, or a string matching regexp.

regexp1|regexp2

(Alternative.) Match any string that matches either regexp1 or regexp2

regexp1regexp2

(Concatenation.) Match the concatenation of two strings, the first
matching regexp1, the second matching regexp2.

(regexp)

Match the same strings as regexp.

ident

Reference the regular expression bound to ident by an earlier
letident=regexp definition.

regexpasident

Bind the substring matched by regexp to identifier ident.

Concerning the precedences of operators, * and + have
highest precedence, followed by ?, then concatenation, then
| (alternation), then as.

The actions are arbitrary Caml expressions. They are evaluated in
a context where the identifiers defined by using the as construct
are bound to subparts of the matched string.
Additionally, lexbuf is bound to the current lexer
buffer. Some typical uses for lexbuf, in conjunction with the
operations on lexer buffers provided by the Lexing standard library
module, are listed below.

Lexing.lexeme lexbuf

Return the matched string.

Lexing.lexeme_char lexbuf n

Return the nth
character in the matched string. The first character corresponds to n = 0.

Lexing.lexeme_start lexbuf

Return the absolute position in the input text of the beginning of the
matched string. The first character read from the input text has
position 0.

Lexing.lexeme_end lexbuf

Return the absolute position in the input text of the end of the
matched string. The first character read from the input text has
position 0.

entrypoint [exp1... expn] lexbuf

(Where entrypoint is the name of another entry point in the same
lexer definition.) Recursively call the lexer on the given entry point.
Notice that lexbuf is the last argument.
Useful for lexing nested comments, for example.

The as construct is similar to ``groups'' as provided by
numerous regular expression packages.
The type of these variables can be string, char, string option
or char option.

We first consider the case of linear patterns, that is the case when
all as bound variables are distinct.
In regexpasident, the type of ident normally is string (or
string option) except
when regexp is a character constant, an underscore, a string
constant of length one, a character set specification, or an
alternation of those. Then, the type of ident is char (or char option).
Option types are introduced when overall rule matching does not
imply matching of the bound sub-pattern. This is in particular the
case of (regexpasindent)? and of
regexp1|(regexp2asident).

There is no linearity restriction over as bound variables.
When a variable is bound more than once, the previous rules are to be
extended as follows:

A variable is a char variable when all its occurrences bind
char occurrences in the previous sense.

A variable is an option variable when the overall expression
can be matched without binding this variable.

For instance, in
('a' as x) | ( 'a' (_ as x) ) the variable x is of type
char, whereas in
("ab" as x) | ( 'a' (_ as x) ? ) the variable x is of type
string option.

In some cases, a sucessful match may not yield a unique set of bindings.
For instance the matching of aba by the regular expression
(('a'|"ab") as x) (("ba"|'a') as y) may result in binding
either
x to "ab" and y to "a", or
x to "a" and y to "ba".
The automata produced ocamllex on such ambiguous regular
expressions will select one of the possible resulting sets of
bindings.
The selected set of bindings is purposely left unspecified.

The ocamlyacc command produces a parser from a context-free grammar
specification with attached semantic actions, in the style of yacc.
Assuming the input file is grammar.mly, executing

ocamlyacc options grammar.mly

produces Caml code for a parser in the file grammar.ml,
and its interface in file grammar.mli.

The generated module defines one parsing function per entry point in
the grammar. These functions have the same names as the entry points.
Parsing functions take as arguments a lexical analyzer (a function
from lexer buffers to tokens) and a lexer buffer, and return the
semantic attribute of the corresponding entry point. Lexical analyzer
functions are usually generated from a lexer specification by the
ocamllex program. Lexer buffers are an abstract data type
implemented in the standard library module Lexing. Tokens are values from
the concrete type token, defined in the interface file
grammar.mli produced by ocamlyacc.

The header and the trailer sections are Caml code that is copied
as is into file grammar.ml. Both sections are optional. The header
goes at the beginning of the output file; it usually contains
open directives and auxiliary functions required by the semantic
actions of the rules. The trailer goes at the end of the output file.

Declare the given symbols as tokens (terminal symbols). These symbols
are added as constant constructors for the token concrete type.

%token<type>symbol ... symbol

Declare the given symbols as tokens with an attached attribute of the
given type. These symbols are added as constructors with arguments of
the given type for the token concrete type. The type part is
an arbitrary Caml type expression, except that all type
constructor names must be fully qualified (e.g. Modname.typename)
for all types except standard built-in types, even if the proper
open directives (e.g. open Modname) were given in the
header section. That's because the header is copied only to the .ml
output file, but not to the .mli output file, while the type part
of a %token declaration is copied to both.

%startsymbol ... symbol

Declare the given symbols as entry points for the grammar. For each
entry point, a parsing function with the same name is defined in the
output module. Non-terminals that are not declared as entry points
have no such parsing function. Start symbols must be given a type with
the %type directive below.

%type<type>symbol ... symbol

Specify the type of the semantic attributes for the given symbols.
This is mandatory for start symbols only. Other nonterminal symbols
need not be given types by hand: these types will be inferred when
running the output files through the Objective Caml compiler (unless the
-s option is in effect). The type part is an arbitrary Caml
type expression, except that all type constructor names must be
fully qualified, as explained above for %token.

%leftsymbol ... symbol

%rightsymbol ... symbol

%nonassocsymbol ... symbol

Associate precedences and associativities to the given symbols. All
symbols on the same line are given the same precedence. They have
higher precedence than symbols declared before in a %left,
%right or %nonassoc line. They have lower precedence
than symbols declared after in a %left, %right or
%nonassoc line. The symbols are declared to associate to the
left (%left), to the right (%right), or to be
non-associative (%nonassoc). The symbols are usually tokens.
They can also be dummy nonterminals, for use with the %prec
directive inside the rules.

The precedence declarations are used in the following way to
resolve reduce/reduce and shift/reduce conflicts:

Tokens and rules have precedences. By default, the precedence
of a rule is the precedence of its rightmost terminal. You
can override this default by using the %prec directive in the rule.

A reduce/reduce conflict
is resolved in favor of the first rule (in the order given by the
source file), and ocamlyacc outputs a warning.

A shift/reduce conflict
is resolved by comparing the precedence of the rule to be
reduced with the precedence of the token to be shifted. If the
precedence of the rule is higher, then the rule will be reduced;
if the precedence of the token is higher, then the token will
be shifted.

A shift/reduce conflict between a rule and a token with the
same precedence will be resolved using the associativity: if the
token is left-associative, then the parser will reduce; if the
token is right-associative, then the parser will shift. If the
token is non-associative, then the parser will declare a syntax
error.

When a shift/reduce conflict cannot be resolved using the above
method, then ocamlyacc will output a warning and the parser will
always shift.

Rules can also contain the %prec symbol directive in the
right-hand side part, to override the default precedence and
associativity of the rule with the precedence and associativity of the
given symbol.

Semantic actions are arbitrary Caml expressions, that
are evaluated to produce the semantic attribute attached to
the defined nonterminal. The semantic actions can access the
semantic attributes of the symbols in the right-hand side of
the rule with the $ notation: $1 is the attribute for the
first (leftmost) symbol, $2 is the attribute for the second
symbol, etc.

The rules may contain the special symbol error to indicate
resynchronization points, as in yacc.

Actions occurring in the middle of rules are not supported.

Nonterminal symbols are like regular Caml symbols, except that they
cannot end with ' (single quote).

Error recovery is supported as follows: when the parser reaches an
error state (no grammar rules can apply), it calls a function named
parse_error with the string "syntax error" as argument. The default
parse_error function does nothing and returns, thus initiating error
recovery (see below). The user can define a customized parse_error
function in the header section of the grammar file.

The parser also enters error recovery mode if one of the grammar
actions raises the Parsing.Parse_error exception.

In error recovery mode, the parser discards states from the
stack until it reaches a place where the error token can be shifted.
It then discards tokens from the input until it finds three successive
tokens that can be accepted, and starts processing with the first of
these. If no state can be uncovered where the error token can be
shifted, then the parser aborts by raising the Parsing.Parse_error
exception.

Refer to documentation on yacc for more details and guidance in how
to use error recovery.

Generate a description of the parsing tables and a report on conflicts
resulting from ambiguities in the grammar. The description is put in
file grammar.output.

-bprefix

Name the output files prefix.ml, prefix.mli,
prefix.output, instead of the default naming convention.

At run-time, the ocamlyacc-generated parser can be debugged by
setting the p option in the OCAMLRUNPARAM environment variable
(see section 10.2). This causes the pushdown
automaton executing the parser to print a trace of its action (tokens
shifted, rules reduced, etc). The trace mentions rule numbers and
state numbers that can be interpreted by looking at the file
grammar.output generated by ocamlyacc -v.

The deterministic automata generated by ocamllex are limited to at
most 32767 transitions. The message above indicates that your lexer
definition is too complex and overflows this limit. This is commonly
caused by lexer definitions that have separate rules for each of the
alphabetic keywords of the language, as in the following example.

The deterministic automata generated by ocamllex maintains a table of
positions inside the scanned lexer buffer. The size of this table is
limited to at most 255 cells. This error should not show up in normal
situations.

The ocamldep command scans a set of Objective Caml source files
(.ml and .mli files) for references to external compilation units,
and outputs dependency lines in a format suitable for the make
utility. This ensures that make will compile the source files in the
correct order, and recompile those files that need to when a source
file is modified.

The typical usage is:

ocamldep options *.mli *.ml > .depend

where *.mli *.ml expands to all source files in the current
directory and .depend is the file that should contain the
dependencies. (See below for a typical Makefile.)

Dependencies are generated both for compiling with the bytecode
compiler ocamlc and with the native-code compiler ocamlopt.

Add the given directory to the list of directories searched for
source files. If a source file foo.ml mentions an external
compilation unit Bar, a dependency on that unit's interface
bar.cmi is generated only if the source for bar is found in the
current directory or in one of the directories specified with -I.
Otherwise, Bar is assumed to be a module from the standard library,
and no dependencies are generated. For programs that span multiple
directories, it is recommended to pass ocamldep the same -I options
that are passed to the compiler.

-native

Generate dependencies for a pure native-code program (no bytecode
version). When an implementation file (.ml file) has no explicit
interface file (.mli file), ocamldep generates dependencies on the
bytecode compiled file (.cmo file) to reflect interface changes.
This can cause unnecessary bytecode recompilations for programs that
are compiled to native-code only. The flag -native causes
dependencies on native compiled files (.cmx) to be generated instead
of on .cmo files. (This flag makes no difference if all source files
have explicit .mli interface files.)

Add the given directory to the list of directories searched for
source and compiled files. By default, only the standard library
directory is searched. The standard library can also be changed by
setting the OCAMLLIB environment variable.

-nolabels

Ignore non-optional labels in types. Labels cannot be used in
applications, and parameter order becomes strict.

-oldui

Old multi-window interface. The default is now more like Smalltalk's
class browser.

-rectypes

Allow arbitrary recursive types during type-checking. By default,
only recursive types where the recursion goes through an object type
are supported.

-wwarning-list

Enable or disable warnings according to the argument warning-list.

Most options can also be modified inside the application by the Modules - Path editor and Compiler - Preferences commands.
They are inherited when you start a toplevel shell.

Modules - Path editor changes the load path. Modules
- Reset cache rescans the load path and resets the module cache.
Do it if you recompile some interface, or get confused about what is
in the cache.

Modules - Search symbol allows to search a symbol either
by its name, like the bottom line of the viewer, or, more
interestingly, by its type. Exact type searches for a type
with exactly the same information as the pattern (variables match
only variables). Included type allows to give only partial
information: the actual type may take more arguments and return more
results, and variables in the pattern match anything. In both cases,
argument and tuple order is irrelevant1,
and unlabeled arguments in the pattern match any label.

The Search entry just below the menu bar allows one to
search for an identifier in all modules (wildcards ``?'' and ``*''
allowed). If you choose the type option, the search is done by type
inclusion (cf. Search Symbol - Included type).

The Close all button is there to dismiss the windows
created by the Detach button.
By double-clicking on it you will quit the browser.

You select a module in the leftmost box by either cliking on it or
pressing return when it is selected. Fast access is available in all
boxes pressing the first few letter of the desired name.
Double-clicking / double-return displays the whole signature for the
module.

Defined identifiers inside the module are displayed in a box to the
right of the previous one. If you click on one, this will either
display its contents in another box (if this is a sub-module) or
display the signature for this identifier below.

Signatures are clickable. Double clicking with the left mouse
button on an identifier in a signature brings you to its signature.
A single click on the right button pops up a menu displaying the
type declaration for the selected identifier. Its title, when
selectable, also brings you to its signature.

At the bottom, a series of buttons, depending on the context.

Detach copies the currently displayed signature in a new window,
to keep it.

Impl and Intf bring you to the implementation or
interface of the currently displayed signature, if it is available.

You can edit files with it, if you're not yet used to emacs. Otherwise
you can use it as a browser, making occasional corrections.

The Edit menu contains commands for jump (C-g), search (C-s),
and sending the current phrase (or selection if some text is selected)
to a sub-shell (M-x). For this last option, you may choose the shell
via a dialog.

Essential functions are in the Compiler menu.

Preferences opens a dialog to set internals of the editor
and type-checker.

Lex adds colors according to lexical categories.

Typecheck verifies typing, and memorizes to let one see an
expression's type by double-clicking on it. This is also valid for
interfaces. If an error occurs, the part of the interface preceding
the error is computed.

After typechecking, pressing the right button pops up a menu giving
the type of the pointed expression, and eventually allowing to
follow some links.

Clear errors dismisses type-checker error messages and warnings.

Signature shows the signature of the current file
(after type checking).

To avoid
combinatorial explosion of the search space, optional arguments in
the actual type are ignored in the actual if (1) there are too many
of them, and (2) they do not appear explicitly in the pattern.

This chapter describes OCamldoc, a tool that generates documentation from
special comments embedded in source files. The comments used by OCamldoc
are of the form (**...*) and follow the format described
in section 15.2.

OCamldoc can produce documentation in various formats: HTML, LATEX,
TeXinfo, Unix man pages, and dot dependency graphs. Moreover,
users can add their own custom generators, as explained in
section 15.3.

In this chapter, we use the word element to refer to any of the
following parts of an OCaml source file: a type declaration, a value,
a module, an exception, a module type, a type constructor, a record
field, a class, a class type, a class method, a class value or a class
inheritance clause.

The following options determine the format for the generated
documentation.

-html

Generate documentation in HTML default format. The generated HTML pages
are stored in the current directory, or in the directory specified
with the -d option. You can customize the style of the
generated pages by editing the generated style.css file, or by providing
your own style sheet using option -css-style.
The file style.css is not generated if it already exists.

-latex

Generate documentation in LATEX default format. The generated
LATEX document is saved in file ocamldoc.out, or in the file
specified with the -o option. The document uses the style file
ocamldoc.sty. This file is generated when using the -latex option,
if it does not already exist.
You can change this file to customize the style of your LATEX documentation.

-texi

Generate documentation in TeXinfo default format. The generated
LATEX document is saved in file ocamldoc.out, or in the file
specified with the -o option.

-man

Generate documentation as a set of Unix man pages. The generated pages
are stored in the current directory, or in the directory specified
with the -d option.

-dot

Generate a dependency graph for the toplevel modules, in a format suitable
for displaying and processing by dot. The dot tool is available from
http://www.research.att.com/sw/tools/graphviz/.
The textual representation of the graph is written to the file
ocamldoc.out, or to the file specified with the -o option.
Use dot ocamldoc.out to display it.

-gfile.cm[o,a]

Dynamically load the given file, which defines a custom documentation
generator. See section 15.4.1. This
option is supported by the ocamldoc command, but not by its
native-code version ocamldoc.opt.
If the given file is a simple one and does not exist in
the current directory, then ocamldoc looks for it in the custom
generators default directory, and in the directories specified with
optional -i options.

-customdir

Display the custom generators default directory.

-idirectory

Add the given directory to the path where to look for custom generators.

General options

-ddir

Generate files in directory dir, rather than in the current directory.

-dumpfile

Dump collected information into file. This information can be
read with the -load option in a subsequent invocation of ocamldoc.

-hidemodules

Hide the given complete module names in the generated documentation
modules is a list of complete module names are separated
by ',', without blanks. For instance: Pervasives,M2.M3.

-inv-merge-ml-mli

Inverse implementations and interfaces when merging. All elements
in implementation files are kept, and the -m option
indicates which parts of the comments in interface files are merged
with the comments in implementation files.

-keep-code

Always keep the source code for values, methods and instance variables,
when available.
The source code is always kept when a .ml
file is given, but is by default discarded when a .mli is given.
This option allows to always keep the source code.

-loadfile

Load information from file, which has been produced by
ocamldoc -dump. Several -load options can be given.

-mflags

Specify merge options between interfaces and implementations.
(see section 15.1.2 for details).
flags can be one or several of the following characters:

Colorize the OCaml code enclosed in [ ] and \{[ ]\}, using colors
to emphasize keywords, etc. If the code fragments are not
syntactically correct, no color is added.

-index-only

Generate only index files.

Options for generating LATEX files

The following options apply in conjunction with the -latex option:

-latex-value-prefixprefix

Give a prefix to use for the labels of the values in the generated LATEX document.
The default prefix is the empty string. You can also use the options
-latex-type-prefix, -latex-exception-prefix, -latex-module-prefix,
-latex-module-type-prefix, -latex-class-prefix, -latex-class-type-prefix,
-latex-attribute-prefix and -latex-method-prefix.

These options are useful when you have, for example, a type and a value with
the same name. If you do not specify prefixes, LATEX will complain about
multiply defined labels.

-latextitlen,style

Associate style number n to the given LATEX sectioning command
style, e.g. section or subsection. (LATEX only.) This is
useful when including the generated document in another LATEX document,
at a given sectioning level. The default association is 1 for section,
2 for subsection, 3 for subsubsection, 4 for paragraph and 5 for
subparagraph.

-noheader

Suppress header in generated documentation.

-notoc

Do not generate a table of contents.

-notrailer

Suppress trailer in generated documentation.

-sepfiles

Generate one .tex file per toplevel module, instead of the global
ocamldoc.out file.

Options for generating TeXinfo files

The following options apply in conjunction with the -texi option:

-esc8

Escape accented characters in Info files.

-info-entry

Specify Info directory entry.

-info-section

Specify section of Info directory.

-noheader

Suppress header in generated documentation.

-noindex

Do not build index for Info files.

-notrailer

Suppress trailer in generated documentation.

Options for generating dot graphs

The following options apply in conjunction with the -dot option:

-dot-colorscolors

Specify the colors to use in the generated dot code.
When generating module dependencies, ocamldoc uses different colors
for modules, depending on the directories in which they reside.
When generating types dependencies, ocamldoc uses different colors
for types, depending on the modules in which they are defined.
colors is a list of color names separated by ',', as
in Red,Blue,Green. The available colors are the ones supported by
the dot tool.

-dot-include-all

Include all modules in the dot output, not only modules given
on the command line or loaded with the -load option.

-dot-reduce

Perform a transitive reduction of the dependency graph before
outputting the dot code. This can be useful if there are
a lot of transitive dependencies that clutter the graph.

Information on a module can be extracted either from the .mli or .ml
file, or both, depending on the files given on the command line.
When both .mli and .ml files are given for the same module,
information extracted from these files is merged according to the
following rules:

Only elements (values, types, classes, ...) declared in the .mli
file are kept. In other terms, definitions from the .ml file that are
not exported in the .mli file are not documented.

Descriptions of elements and descriptions in @-tags are handled
as follows. If a description for the same element or in the same
@-tag of the same element is present in both files, then the
description of the .ml file is concatenated to the one in the .mli file,
if the corresponding -m flag is given on the command line.
If a description is present in the .ml file and not in the
.mli file, the .ml description is kept.
In either case, all the information given in the .mli file is kept.

Comments containing documentation material are called special
comments and are written between (** and *). Special comments
must start exactly with (**. Comments beginning with ( and more
than two * are ignored.

OCamldoc can associate comments to some elements of the language
encountered in the source files. The association is made according to
the locations of comments with respect to the language elements. The
locations of comments in .mli and .ml files are different.

Comments in .mli files

A special comment is associated to an element if it is placed before or
after the element.
A special comment before an element is associated to this element if :

There is no blank line or another special comment between the special
comment and the element. However, a regular comment can occur between
the special comment and the element.

The special comment is not already associated to the previous element.

The special comment is not the first one of a toplevel module.

A special comment after an element is associated to this element if
there is no blank line or comment between the special comment and the
element.

There are two exceptions: for type constructors and record fields in
type definitions, the associated comment can only be placed after the
constructor or field definition, without blank lines or other comments
between them.

The following sample interface file foo.mli illustrates the
placement rules for comments in .mli files.

(** The first special comment of the file is the comment associated
with the whole module.*)
(** Special comments can be placed between elements and are kept
by the OCamldoc tool, but are not associated to any element.
@-tags in these comments are ignored.*)
(*******************************************************************)
(** Comments like the one above, with more than two asterisks,
are ignored. *)
(** The comment for function f. *)
val f : int -> int -> int
(** The continuation of the comment for function f. *)
(** Comment for exception My_exception, even with a simple comment
between the special comment and the exception.*)
(* Hello, I'm a simple comment :-) *)
exception My_exception of (int -> int) * int
(** Comment for type weather *)
type weather =
| Rain of int (** The comment for construtor Rain *)
| Sun (** The comment for constructor Sun *)
(** Comment for type weather2 *)
type weather2 =
| Rain of int (** The comment for construtor Rain *)
| Sun (** The comment for constructor Sun *)
(** I can continue the comment for type weather2 here
because there is already a comment associated to the last constructor.*)
(** The comment for type my_record *)
type my_record = {
val foo : int ; (** Comment for field foo *)
val bar : string ; (** Comment for field bar *)
}
(** Continuation of comment for type my_record *)
(** Comment for foo *)
val foo : string
(** This comment is associated to foo and not to bar. *)
val bar : string
(** This comment is assciated to bar. *)
(** The comment for class my_class *)
class my_class :
object
(** A comment to describe inheritance from cl *)
inherit cl
(** The comment for attribute tutu *)
val mutable tutu : string
(** The comment for attribute toto. *)
val toto : int
(** This comment is not attached to titi since
there is a blank line before titi, but is kept
as a comment in the class. *)
val titi : string
(** Comment for method toto *)
method toto : string
(** Comment for method m *)
method m : float -> int
end
(** The comment for the class type my_class_type *)
class type my_class_type =
object
(** The comment for variable x. *)
val mutable x : int
(** The commend for method m. *)
method m : int -> int
end
(** The comment for module Foo *)
module Foo =
struct
(** The comment for x *)
val x : int
(** A special comment that is kept but not associated to any element *)
end
(** The comment for module type my_module_type. *)
module type my_module_type =
sig
(** The comment for value x. *)
val x : int
(** The comment for module M. *)
module M =
struct
(** The comment for value y. *)
val y : int
(* ... *)
end
end

Comments in .ml files

A special comment is associated to an element if it is placed before
the element and there is no blank line between the comment and the
element. Meanwhile, there can be a simple comment between the special
comment and the element. There are two exceptions, for type
constructors and record fields in type definitions, whose associated
comment must be placed after the constructor or field definition,
without blank line between them.

The following example of file toto.ml shows where to place comments
in a .ml file.

The inside of documentation comments (**...*) consists of
free-form text with optional formatting annotations, followed by
optional tags giving more specific information about parameters,
version, authors, ... The tags are distinguished by a leading @
character. Thus, a documentation comment has the following shape:

(** The comment begins with a description, which is text formatted
according to the rules described in the next section.
The description continues until the first non-escaped '@' character.
@author Mr Smith
@param x description for parameter x
*)

Some elements support only a subset of all @-tags. Tags that are not
relevant to the documented element are simply ignored. For instance,
all tags are ignored when documenting type constructors, record
fields, and class inheritance clauses. Similarly, a @param tag on a
class instance variable is ignored.

Here is the BNF grammar for the simple markup language used to format
text descriptions.

text ::= (text_element)+text_element ::=

| {[0-9]+ text}

format text as a section header;
the integer following { indicates the sectioning level.

| {[0-9]+:label text}

same, but also associate the name label to the current point.
This point can be referenced by its fully-qualified label in a
{! command, just like any other element.

| {b text}

set text in bold.

| {i text}

set text in italic.

| {e text}

emphasize text.

| {C text}

center text.

| {L text}

left align text.

| {R text}

right align text.

| {ul list}

build a list.

| {ol list}

build an enumerated list.

| {{:string}text}

put a link to the given address
(given as a string) on the given text.

| [string]

set the given string in source code style.

| {[string]}

set the given string in preformatted
source code style.

| {v string v}

set the given string in verbatim style.

| {% string %}

take the given string
as raw LATEX code.

| {!string}

insert a reference to the element named
string. string must be a fully qualified element name,
for example Foo.Bar.t. The kind of the referenced element can be forced
(useful when various elements have the same qualified name) with the following
syntax: {!kind: Foo.Bar.t} where kind can be
module, modtype, class, classtype, val,
type, exception, attribute, method or section.

| {!modules: string string ...}

insert an index table
for the given module names. Used in HTML only.

| {!indexlist}

insert a table of links to the various indexes
(types, values, modules, ...). Used in HTML only.

| {^ text}

set text in superscript.

| {_ text}

set text in subscript.

| escaped_string

typeset the given string as is;
special characters ('{', '}', '[', ']' and '@')
must be escaped by a '\'

The same shortcut is available for enumerated lists, using '+'
instead of '-'.
Note that only one list can be defined by this shortcut in nested lists.

In the description of a value, type, exception, module, module type, class
or class type, the first sentence is sometimes used in indexes, or
when just a part of the description is needed. The first sentence
is composed of the first characters of the description, until

The folowing table gives the list of predefined @-tags, with their
syntax and meaning.

@author string

The author of the element. One author by @author tag.
There may be several @author tags for the same element.

@deprecated text

The text should describe when the element was
deprecated, what to use as a replacement, and possibly the reason
for deprecation.

@param id text

Associate the given description (text) to the
given parameter name id. This tag is used for functions,
methods, classes and functors.

@raise Exc text

Explain that the element may raise
the exception Exc.

@return text

Describe the return value and
its possible values. This tag is used for functions
and methods.

@see <url> text

Add a reference to the URL between '<' and '>'
with the given text as comment.

@see 'filename' text

Add a reference to the given file name
(written between single quotes), with the given text as comment.

@see "document name" text

Add a reference to the given
document name (written between double quotes), with the given text
as comment.

@since string

Indicates when the element was introduced.

@version string

The version number for the element.

Custom tags

You can use custom tags in the documentation comments, but they will
have no effect if the generator used does not handle them. To use a
custom tag, for example foo, just put @foo with some text in your
comment, as in:

(** My comment to show you a custom tag.
@foo this is the text argument to the [foo] custom tag.
*)

To handle custom tags, you need to define a custom generator,
as explained in section 15.3.2.

generation of documentation, through a documentation generator,
which is an object of class Odoc_args.class_generator.

Users can provide their own documentation generator to be used during
step 2 instead of the default generators.
All the information retrieved during the analysis step is available through
the Odoc_info module, which gives access to all the types and functions
representing the elements found in the given modules, with their associated
description.

The files you can used to define custom generators are installed in the
ocamldoc sub-directory of the OCaml standard library.

A generator class is a class of type Odoc_args.doc_generator.
It has only one methodgenerator : Odoc_info.Module.t_module list -> unit
This method will be called with the list of analysed and possibly
merged Odoc_info.t_module structures.
Of course the class can have other methods, but the object of this
class must be coerced to Odoc_args.doc_generator before being
passed to the functionOdoc_args.set_doc_generator : Odoc_args.doc_generator -> unit
which installs the new documentation generator.

The following example shows how to define and install a new documentation generator.
See the odoc_fhtml generator (in the Ocamldoc Hump) for a complete example.

Making a custom generator handle custom tags (see
15.2.5) is very simple.

For HTML

Here is how to develop a HTML generator handling your custom tags.

The class Odoc_html.html inherits
from the class Odoc_html.info, containing a field tag_functions which is a
list pairs composed of a custom tag (e.g. 'foo') and a function taking a text
and returning HTML code (of type string).
To handle a new tag bar, create a HTML generator class from the existing one
and complete the tag_functions field:

Another method of the class Odoc_html.info will look for the
function associated to a custom tag and apply it to the text given to
the tag. If no function is associated to a custom tag, then the method
prints a warning message on stderr.

For other generators

As for the HTML custom generator, you can define a new LATEX(resp. man) generator by inheriting from the class
Odoc_latex.latex (resp. Odoc_man.man) and
adding your own tag handler to the field tag_functions.

The command line analysis is performed after loading the module containing the
documentation generator, thus allowing command line options to be added to the
list of existing ones. Adding an option can be done with the functionOdoc_args.add_option : string * Arg.spec * string -> unit
Note: Existing command line options can be redefined using this function.

Let custom.ml be the file defining a new generator class.
Compilation of custom.ml can be performed by the following command :ocamlc -I +ocamldoc -c custom.ml
The file custom.cmo is created and can be used this way :ocamldoc -g custom.cmo other-options source-files
It is important not to give the -html or any other option selecting a
built in generator to ocamldoc,
which would result in using this generator instead of the one you just loaded.

Defining a custom generator class in several files

It is possible to define a generator class in several modules, which
are defined in several files file1.ml[i], file2.ml[i], ...,
fileN.ml[i]. A .cma library file must
be created, including all these files.
The following commands create the custom.cma file from files file1.ml[i], ...,
fileN.ml[i] :ocamlc -I +ocamldoc -c file1.ml[i]
ocamlc -I +ocamldoc -c file2.ml[i]
...
ocamlc -I +ocamldoc -c fileN.ml[i]
ocamlc -o custom.cma -a file1.cmo file2.cmo ... fileN.cmo
Then, the following command uses custom.cma as custom generator:ocamldoc -g custom.cma other-options source-files
Again, it is important not to give the -html or any other option selecting a
built in generator to ocamldoc,
which would result in using this generator instead of the one you just loaded.

Before the debugger can be used, the program must be compiled and
linked with the -g option: all .cmo and .cma files that are part
of the program should have been created with ocamlc -g, and they
must be linked together with ocamlc -g.

Compiling with -g entails no penalty on the running time of
programs: object files and bytecode executable files are bigger and
take longer to produce, but the executable files run at
exactly the same speed as if they had been compiled without -g.

A debugger command is a single line of input. It starts with a command
name, which is followed by arguments depending on this name. Examples:

run
goto 1000
set arguments arg1 arg2

A command name can be truncated as long as there is no ambiguity. For
instance, go 1000 is understood as goto 1000, since there are no
other commands whose name starts with go. For the most frequently
used commands, ambiguous abbreviations are allowed. For instance, r
stands for run even though there are others commands starting with
r. You can test the validity of an abbreviation using the help command.

If the previous command has been successful, a blank line (typing just
RET) will repeat it.

Events are ``interesting'' locations in the source code, corresponding
to the beginning or end of evaluation of ``interesting''
sub-expressions. Events are the unit of single-stepping (stepping goes
to the next or previous event encountered in the program execution).
Also, breakpoints can only be set at events. Thus, events play the
role of line numbers in debuggers for conventional languages.

During program execution, a counter is incremented at each event
encountered. The value of this counter is referred as the current
time. Thanks to reverse execution, it is possible to jump back and
forth to any time of the execution.

Here is where the debugger events (written §§) are located in
the source code:

Following a function application:

(f arg)§§

On entrance to a function:

fun x y z -> §§ ...

On each case of a pattern-matching definition (function,
match...with construct, try...with construct):

function pat1 -> §§ expr1
| ...
| patN -> §§ exprN

Between subexpressions of a sequence:

expr1; §§ expr2; §§ ...; §§ exprN

In the two branches of a conditional expression:

if cond then §§ expr1 else §§ expr2

At the beginning of each iteration of a loop:

while cond do §§ body done
for i = a to b do §§ body done

Exceptions: A function application followed by a function return is replaced
by the compiler by a jump (tail-call optimization). In this case, no
event is put after the function application.

The debugger starts executing the debugged program only when needed.
This allows setting breapoints or assigning debugger variables before
execution starts. There are several ways to start execution:

run

Run the program until a breakpoint is hit, or the program
terminates.

step 0

Load the program and stop on the first event.

goto time

Load the program and execute it until the
given time. Useful when you already know approximately at what time
the problem appears. Also useful to set breakpoints on function values
that have not been computed at time 0 (see section 16.5).

The execution of a program is affected by certain information it
receives when the debugger starts it, such as the command-line
arguments to the program and its working directory. The debugger
provides commands to specify this information (set arguments and cd).
These commands must be used before program execution starts. If you try
to change the arguments or the working directory after starting your
program, the debugger will kill the program (after asking for confirmation).

You can jump directly to a given time, without stopping on
breakpoints, using the goto command.

As you move through the program, the debugger maintains an history of
the successive times you stop at. The last command can be used to
revisit these times: each last command moves one step back through
the history. That is useful mainly to undo commands such as step
and next.

goto time

Jump to the given time.

last [count]

Go back to the latest time recorded in the execution history. With an
argument, do it count times.

A breakpoint causes the program to stop whenever a certain point in
the program is reached. It can be set in several ways using the
break command. Breakpoints are assigned numbers when set, for
further reference. The most comfortable way to set breakpoints is
through the Emacs interface (see section 16.10).

break

Set a breakpoint at the current position in the program execution. The
current position must be on an event (i.e., neither at the beginning,
nor at the end of the program).

break function

Set a breakpoint at the beginning of function. This works only
when the functional value of the identifier function has been
computed and assigned to the identifier. Hence this command cannot be
used at the very beginning of the program execution, when all
identifiers are still undefined; use gototime to advance
execution until the functional value is available.

break @ [module] line

Set a breakpoint in module module (or in the current module if
module is not given), at the first event of line line.

break @ [module] line column

Set a breakpoint in module module (or in the current module if
module is not given), at the event closest to line line,
column column.

break @ [module] #character

Set a breakpoint in module module at the event closest to
character number character.

break address

Set a breakpoint at the code address address.

delete [breakpoint-numbers]

Delete the specified breakpoints. Without argument, all breakpoints
are deleted (after asking for confirmation).

Each time the program performs a function application, it saves the
location of the application (the return address) in a block of data
called a stack frame. The frame also contains the local variables of
the caller function. All the frames are allocated in a region of
memory called the call stack. The command backtrace (or bt)
displays parts of the call stack.

At any time, one of the stack frames is ``selected'' by the debugger; several
debugger commands refer implicitly to the selected frame. In particular,
whenever you ask the debugger for the value of a local variable, the
value is found in the selected frame. The commands frame, up and down
select whichever frame you are interested in.

When the program stops, the debugger automatically selects the
currently executing frame and describes it briefly as the frame
command does.

frame

Describe the currently selected stack frame.

frameframe-number

Select a stack frame by number and describe it. The frame currently
executing when the program stopped has number 0; its caller has number
1; and so on up the call stack.

backtrace [count], bt [count]

Print the call stack. This is useful to see which sequence of function
calls led to the currently executing frame. With a positive argument,
print only the innermost count frames.
With a negative argument, print only the outermost -count frames.

up [count]

Select and display the stack frame just ``above'' the selected frame,
that is, the frame that called the selected frame. An argument says how
many frames to go up.

down [count]

Select and display the stack frame just ``below'' the selected frame,
that is, the frame that was called by the selected frame. An argument
says how many frames to go down.

The debugger can print the current value of simple expressions. The
expressions can involve program variables: all the identifiers that
are in scope at the selected program point can be accessed.

Expressions that can be printed are a subset of Objective Caml
expressions, as described by the following grammar:

expr

::=

lowercase-ident

|

{ capitalized-ident. } lowercase-ident

|

*

|

$integer

|

expr.lowercase-ident

|

expr.(integer)

|

expr.[integer]

|

!expr

|

(expr)

The first two cases refer to a value identifier, either unqualified or
qualified by the path to the structure that define it.
* refers to the result just computed (typically, the value of a
function application), and is valid only if the selected event is an
``after'' event (typically, a function application).
$integer refer to a previously printed value. The remaining four
forms select part of an expression: respectively, a record field, an
array element, a string element, and the current contents of a
reference.

print variables

Print the values of the given variables. print can be abbreviated as
p.

display variables

Same as print, but limit the depth of printing to 1. Useful to
browse large data structures without printing them in full.
display can be abbreviated as d.

When printing a complex expression, a name of the form $integer
is automatically assigned to its value. Such names are also assigned
to parts of the value that cannot be printed because the maximal
printing depth is exceeded. Named values can be printed later on
with the commands p $integer or d $integer.
Named values are valid only as long as the program is stopped. They
are forgotten as soon as the program resumes execution.

A shell is used to pass the arguments to the debugged program. You can
therefore use wildcards, shell variables, and file redirections inside
the arguments. To debug programs that read from standard input, it is
recommended to redirect their input from a file (using
set arguments < input-file), otherwise input to the program and
input to the debugger are not properly separated, and inputs are not
properly replayed when running the program backwards.

The debugger searches for source files and compiled interface files in
a list of directories, the search path. The search path initially
contains the current directory . and the standard library directory.
The directory command adds directories to the path.

Whenever the search path is modified, the debugger will clear any
information it may have cached about the files.

directorydirectorynames

Add the given directories to the search path. These directories are
added at the front, and will therefore be searched first.

Each time a program is started in the debugger, it inherits its working
directory from the current working directory of the debugger. This
working directory is initially whatever it inherited from its parent
process (typically the shell), but you can specify a new working
directory in the debugger with the cd command or the -cd
command-line option.

In some cases, you may want to turn reverse execution off. This speeds
up the program execution, and is also sometimes useful for interactive
programs.

Normally, the debugger takes checkpoints of the program state from
time to time. That is, it makes a copy of the current state of the
program (using the Unix system call fork). If the variable
checkpoints is set to off, the debugger will not take any
checkpoints.

The debugger communicate with the program being debugged through a
Unix socket. You may need to change the socket name, for example if
you need to run the debugger on a machine and your program on another.

set socketsocket

Use socket for communication with the program. socket can be
either a file name, or an Internet port specification
host:port, where host is a host name or an Internet
address in dot notation, and port is a port number on the host.

On the debugged program side, the socket name is passed through the
CAML_DEBUG_SOCKET environment variable.

Several variables enables to fine-tune the debugger. Reasonable
defaults are provided, and you should normally not have to change them.

set processcountcount

Set the maximum number of checkpoints to count. More checkpoints
facilitate going far back in time, but use more memory and create more
Unix processes.

As checkpointing is quite expensive, it must not be done too often. On
the other hand, backward execution is faster when checkpoints are
taken more often. In particular, backward single-stepping is more
responsive when many checkpoints have been taken just before the
current time. To fine-tune the checkpointing strategy, the debugger
does not take checkpoints at the same frequency for long displacements
(e.g. run) and small ones (e.g. step). The two variables bigstep
and smallstep contain the number of events between two checkpoints
in each case.

set bigstepcount

Set the number of events between two checkpoints for long displacements.

set smallstepcount

Set the number of events between two checkpoints for small
displacements.

The following commands display information on checkpoints and events:

info checkpoints

Print a list of checkpoints.

info events [module]

Print the list of events in the given module (the current module, by default).

Just as in the toplevel system (section 9.2),
the user can register functions for printing values of certain types.
For technical reasons, the debugger cannot call printing functions
that reside in the program being debugged. The code for the printing
functions must therefore be loaded explicitly in the debugger.

load_printer "file-name"

Load in the debugger the indicated .cmo or .cma object file. The
file is loaded in an environment consisting only of the Objective Caml
standard library plus the definitions provided by object files
previously loaded using load_printer. If this file depends on other
object files not yet loaded, the debugger automatically loads them if
it is able to find them in the search path. The loaded file does not
have direct access to the modules of the program being debugged.

install_printer printer-name

Register the function named printer-name (a
value path) as a printer for objects whose types match the argument
type of the function. That is, the debugger will call
printer-name when it has such an object to print.
The printing function printer-name must use the Format library
module to produce its output, otherwise its output will not be
correctly located in the values printed by the toplevel loop.

The value path printer-name must refer to one of the functions
defined by the object files loaded using load_printer. It cannot
reference the functions of the program being debugged.

The most user-friendly way to use the debugger is to run it under Emacs.
See the file emacs/README in the distribution for information on how
to load the Emacs Lisp files for Caml support.

The Caml debugger is started under Emacs by the command M-x camldebug, with argument the name of the executable file
progname to debug. Communication with the debugger takes place
in an Emacs buffer named *camldebug-progname*. The editing
and history facilities of Shell mode are available for interacting
with the debugger.

In addition, Emacs displays the source files containing the current
event (the current position in the program execution) and highlights
the location of the event. This display is updated synchronously with
the debugger action.

The following bindings for the most common debugger commands are
available in the *camldebug-progname* buffer:

C-c C-s

(command step): execute the program one step forward.

C-c C-k

(command backstep): execute the program one step backward.

C-c C-n

(command next): execute the program one step
forward, skipping over function calls.

Before profiling an execution, the program must be compiled in
profiling mode, using the ocamlcp front-end to the ocamlc compiler
(see chapter 8). When compiling modules separately,
ocamlcp must be used when compiling the modules (production
of .cmo files), and can also be used (though this is not strictly
necessary) when linking them together.

Note

If a module (.ml file) doesn't have a corresponding
interface (.mli file), then compiling it with ocamlcp will produce
object files (.cmi and .cmo) that are not compatible with the ones
produced by ocamlc, which may lead to problems (if the .cmi or
.cmo is still around) when switching between profiling and
non-profiling compilations. To avoid this problem, you should always
have a .mli file for each .ml file.

Note

To make sure your programs can be compiled in
profiling mode, avoid using any identifier that begins with
__ocaml_prof.

The amount of profiling information can be controlled through the -p
option to ocamlcp, followed by one or several letters indicating which
parts of the program should be profiled:

a

all options

f

function calls : a count point is set at the beginning of
function bodies

i

if ...then ...else ... : count points are set in
both then branch and else branch

l

while, for loops: a count point is set at the beginning of
the loop body

m

match branches: a count point is set at the beginning of the
body of each branch

t

try ...with ... branches: a count point is set at the
beginning of the body of each branch

Calling ocamlcp without the -p option defaults to -p fm, meaning
that only function calls and pattern matching are profiled.

Note: Due to the implementation of streams and stream patterns as
syntactic sugar, it is hard to predict what parts of stream expressions
and patterns will be profiled by a given flag. To profile a program with
streams, we recommend using ocamlcp -p a.

Running a bytecode executable file that has been compiled with ocamlcp
records the execution counts for the specified parts of the program
and saves them in a file called ocamlprof.dump in the current directory.

The ocamlprof.dump file is written only if the program terminates
normally (by calling exit or by falling through). It is not written
if the program terminates with an uncaught exception.

If a compatible dump file already exists in the current directory, then the
profiling information is accumulated in this dump file. This allows, for
instance, the profiling of several executions of a program on
different inputs.

The ocamlprof command produces a source listing of the program modules
where execution counts have been inserted as comments. For instance,

ocamlprof foo.ml

prints the source code for the foo module, with comments indicating
how many times the functions in this module have been called. Naturally,
this information is accurate only if the source file has not been modified
since the profiling execution took place.

The following options are recognized by ocamlprof:

-fdumpfile

Specifies an alternate dump file of profiling information

-Fstring

Specifies an additional string to be output with profiling information.
By default, ocamlprof will annotate programs with comments of the form
(* n *) where n is the counter value for a profiling
point. With option -F s, the annotation will be
(* sn *).

Profiling with ocamlprof only records execution counts, not the actual
time spent into each function. There is currently no way to perform
time profiling on bytecode programs generated by ocamlc.

Native-code programs generated by ocamlopt can be profiled for time
and execution counts using the -p option and the standard Unix
profiler gprof. Just add the -p option when compiling and linking
the program:

ocamlopt -o myprog -p other-options files
./myprog
gprof myprog

Caml function names in the output of gprof have the following format:

Module-name_function-name_unique-number

Other functions shown are either parts of the Caml run-time system or
external C functions linked with the program.

The output of gprof is described in the Unix manual page for
gprof(1). It generally consists of two parts: a ``flat'' profile
showing the time spent in each function and the number of invocation
of each function, and a ``hierarchical'' profile based on the call
graph. Currently, only the Intel x86/Linux and Alpha/Digital Unix
ports of ocamlopt support the two profiles. On other platforms,
gprof will report only the ``flat'' profile with just time
information. When reading the output of gprof, keep in mind that
the accumulated times computed by gprof are based on heuristics and
may not be exact.

User primitives are declared in an implementation file or
struct...end module expression using the external keyword:

external name : type = C-function-name

This defines the value name name as a function with type
type that executes by calling the given C function.
For instance, here is how the input primitive is declared in the
standard library module Pervasives:

external input : in_channel -> string -> int -> int -> int
= "input"

Primitives with several arguments are always curried. The C function
does not necessarily have the same name as the ML function.

External functions thus defined can be specified in interface files or
sig...end signatures either as regular values

val name : type

thus hiding their implementation as a C function, or explicitly as
``manifest'' external functions

external name : type = C-function-name

The latter is slightly more efficient, as it allows clients of the
module to call directly the C function instead of going through the
corresponding Caml function.

The arity (number of arguments) of a primitive is automatically
determined from its Caml type in the external declaration, by
counting the number of function arrows in the type. For instance,
input above has arity 4, and the input C function is called with
four arguments. Similarly,

external input2 : in_channel * string * int * int -> int = "input2"

has arity 1, and the input2 C function receives one argument (which
is a quadruple of Caml values).

Type abbreviations are not expanded when determining the arity of a
primitive. For instance,

User primitives with arity n£ 5 are implemented by C functions
that take n arguments of type value, and return a result of type
value. The type value is the type of the representations for Caml
values. It encodes objects of several base types (integers,
floating-point numbers, strings, ...), as well as Caml data
structures. The type value and the associated conversion
functions and macros are described in details below. For instance,
here is the declaration for the C function implementing the input
primitive:

When the primitive function is applied in a Caml program, the C
function is called with the values of the expressions to which the
primitive is applied as arguments. The value returned by the function is
passed back to the Caml program as the result of the function
application.

User primitives with arity greater than 5 should be implemented by two
C functions. The first function, to be used in conjunction with the
bytecode compiler ocamlc, receives two arguments: a pointer to an
array of Caml values (the values for the arguments), and an
integer which is the number of arguments provided. The other function,
to be used in conjunction with the native-code compiler ocamlopt,
takes its arguments directly. For instance, here are the two C
functions for the 7-argument primitive Nat.add_nat:

Implementing a user primitive is actually two separate tasks: on the
one hand, decoding the arguments to extract C values from the given
Caml values, and encoding the return value as a Caml
value; on the other hand, actually computing the result from the arguments.
Except for very simple primitives, it is often preferable to have two
distinct C functions to implement these two tasks. The first function
actually implements the primitive, taking native C values as
arguments and returning a native C value. The second function,
often called the ``stub code'', is a simple wrapper around the first
function that converts its arguments from Caml values to C values,
call the first function, and convert the returned C value to Caml
value. For instance, here is the stub code for the input
primitive:

(Here, Val_long, Long_val and so on are conversion macros for the
type value, that will be described later. The CAMLprim macro
expands to the required compiler directives to ensure that the
function following it is exported and accessible from Caml.)
The hard work is performed by the function getblock, which is
declared as:

long getblock(struct channel * channel, char * p, long n)
{
...
}

To write C code that operates on Objective Caml values, the following
include files are provided:

The Objective Caml runtime system comprises three main parts: the bytecode
interpreter, the memory manager, and a set of C functions that
implement the primitive operations. Some bytecode instructions are
provided to call these C functions, designated by their offset in a
table of functions (the table of primitives).

In the default mode, the Caml linker produces bytecode for the
standard runtime system, with a standard set of primitives. References
to primitives that are not in this standard set result in the
``unavailable C primitive'' error. (Unless dynamic loading of C
libraries is supported -- see section 18.1.4 below.)

In the ``custom runtime'' mode, the Caml linker scans the
object files and determines the set of required primitives. Then, it
builds a suitable runtime system, by calling the native code linker with:

the table of the required primitives;

a library that provides the bytecode interpreter, the
memory manager, and the standard primitives;

libraries and object code files (.o files) mentioned on the
command line for the Caml linker, that provide implementations
for the user's primitives.

This builds a runtime system with the required primitives. The Caml
linker generates bytecode for this custom runtime system. The
bytecode is appended to the end of the custom runtime system, so that
it will be automatically executed when the output file (custom
runtime + bytecode) is launched.

To link in ``custom runtime'' mode, execute the ocamlc command with:

the -custom option;

the names of the desired Caml object files (.cmo and .cma files) ;

the names of the C object files and libraries (.o and .a
files) that implement the required primitives. Under Unix and Windows,
a library named libname.a residing in one of the standard
library directories can also be specified as -cclib -lname.

If you are using the native-code compiler ocamlopt, the -custom
flag is not needed, as the final linking phase of ocamlopt always
builds a standalone executable. To build a mixed Caml/C executable,
execute the ocamlopt command with:

the names of the desired Caml native object files (.cmx and
.cmxa files);

the names of the C object files and libraries (.o, .a,
.so or .dll files) that implement the required primitives.

Starting with OCaml 3.00, it is possible to record the
-custom option as well as the names of C libraries in a Caml
library file .cma or .cmxa. For instance, consider a Caml library
mylib.cma, built from the Caml object files a.cmo and b.cmo,
which reference C code in libmylib.a. If the library is
built as follows:

ocamlc -a -o mylib.cma -custom a.cmo b.cmo -cclib -lmylib

users of the library can simply link with mylib.cma:

ocamlc -o myprog mylib.cma ...

and the system will automatically add the -custom and -cclib -lmylib options, achieving the same effect as

ocamlc -o myprog -custom a.cmo b.cmo ... -cclib -lmylib

The alternative, of course, is to build the library without extra
options:

ocamlc -a -o mylib.cma a.cmo b.cmo

and then ask users to provide the -custom and -cclib -lmylib
options themselves at link-time:

ocamlc -o myprog -custom mylib.cma ... -cclib -lmylib

The former alternative is more convenient for the final users of the
library, however.

Starting with OCaml 3.03, an alternative to static linking of C code
using the -custom code is provided. In this mode, the Caml linker
generates a pure bytecode executable (no embedded custom runtime
system) that simply records the names of dynamically-loaded libraries
containing the C code. The standard Caml runtime system ocamlrun
then loads dynamically these libraries, and resolves references to the
required primitives, before executing the bytecode.

This facility is currently supported and known to work well under
Linux and Windows (the native Windows port). It is supported, but not
fully tested yet, under FreeBSD, Tru64, Solaris and Irix. It is not
supported yet under other Unixes, Cygwin for Windows, and MacOS.

To dynamically link C code with Caml code, the C code must first be
compiled into a shared library (under Unix) or DLL (under Windows).
This involves 1- compiling the C files with appropriate C compiler
flags for producing position-independent code, and 2- building a
shared library from the resulting object files. The resulting shared
library or DLL file must be installed in a place where ocamlrun can
find it later at program start-up time (see
section 10.3).
Finally (step 3), execute the ocamlc command with

the names of the desired Caml object files (.cmo and .cma files) ;

the names of the C shared libraries (.so or .dll files) that
implement the required primitives. Under Unix and Windows,
a library named dllname.so (respectively, .dll) residing
in one of the standard library directories can also be specified as
-dllib -lname.

Do not set the -custom flag, otherwise you're back to static linking
as described in section 18.1.3.
Under Unix, the ocamlmklib tool (see section 18.10)
automates steps 2 and 3.

As in the case of static linking, it is possible (and recommended) to
record the names of C libraries in a Caml .cmo library archive.
Consider again a Caml library
mylib.cma, built from the Caml object files a.cmo and b.cmo,
which reference C code in dllmylib.so. If the library is
built as follows:

ocamlc -a -o mylib.cma a.cmo b.cmo -dllib -lmylib

users of the library can simply link with mylib.cma:

ocamlc -o myprog mylib.cma ...

and the system will automatically add the -dllib -lmylib option,
achieving the same effect as

ocamlc -o myprog a.cmo b.cmo ... -dllib -lmylib

Using this mechanism, users of the library mylib.cma do not need to
known that it references C code, nor whether this C code must be
statically linked (using -custom) or dynamically linked.

After having described two different ways of linking C code with Caml
code, we now review the pros and cons of each, to help developers of
mixed Caml/C libraries decide.

The main advantage of dynamic linking is that it preserves the
platform-independence of bytecode executables. That is, the bytecode
executable contains no machine code, and can therefore be compiled on
platform A and executed on other platforms B, C, ..., as long
as the required shared libraries are available on all these
platforms. In contrast, executables generated by ocamlc -custom run
only on the platform on which they were created, because they embark a
custom-tailored runtime system specific to that platform. In
addition, dynamic linking results in smaller executables.

Another advantage of dynamic linking is that the final users of the
library do not need to have a C compiler, C linker, and C runtime
libraries installed on their machines. This is no big deal under
Unix and Cygwin, but many Windows users are reluctant to install
Microsoft Visual C just to be able to do ocamlc -custom.

There are two drawbacks to dynamic linking. The first is that the
resulting executable is not stand-alone: it requires the shared
libraries, as well as ocamlrun, to be installed on the machine
executing the code. If you wish to distribute a stand-alone
executable, it is better to link it statically, using ocamlc -custom -ccopt -static or ocamlopt -ccopt -static. Dynamic linking also
raises the ``DLL hell'' problem: some care must be taken to ensure
that the right versions of the shared libraries are found at start-up
time.

The second drawback of dynamic linking is that it complicates the
construction of the library. The C compiler and linker flags to
compile to position-independent code and build a shared library vary
wildly between different Unix systems. Also, dynamic linking is not
supported on all Unix systems, requiring a fall-back case to static
linking in the Makefile for the library. The ocamlmklib command
(see section 18.10) tries to hide some of these system
dependencies.

In conclusion: dynamic linking is highly recommended under the native
Windows port, because there are no portability problems and it is much
more convenient for the end users. Under Unix, dynamic linking should
be considered for mature, frequently used libraries because it
enhances platform-independence of bytecode executables. For new or
rarely-used libraries, static linking is much simpler to set up in a
portable way.

It is sometimes inconvenient to build a custom runtime system each
time Caml code is linked with C libraries, like ocamlc -custom does.
For one thing, the building of the runtime system is slow on some
systems (that have bad linkers or slow remote file systems); for
another thing, the platform-independence of bytecode files is lost,
forcing to perform one ocamlc -custom link per platform of interest.

An alternative to ocamlc -custom is to build separately a custom
runtime system integrating the desired C libraries, then generate
``pure'' bytecode executables (not containing their own runtime
system) that can run on this custom runtime. This is achieved by the
-make_runtime and -use_runtime flags to ocamlc. For example,
to build a custom runtime system integrating the C parts of the
``Unix'' and ``Threads'' libraries, do:

ocamlc -make-runtime -o /home/me/ocamlunixrun unix.cma threads.cma

To generate a bytecode executable that runs on this runtime system,
do:

The bytecode executable myprog can then be launched as usual:
myprogargs or /home/me/ocamlunixrun myprogargs.

Notice that the bytecode libraries unix.cma and threads.cma must
be given twice: when building the runtime system (so that ocamlc
knows which C primitives are required) and also when building the
bytecode executable (so that the bytecode from unix.cma and
threads.cma is actually linked in).

Blocks in the heap are garbage-collected, and therefore have strict
structure constraints. Each block includes a header containing the
size of the block (in words), and the tag of the block.
The tag governs how the contents of the blocks are structured. A tag
lower than No_scan_tag indicates a structured block, containing
well-formed values, which is recursively traversed by the garbage
collector. A tag greater than or equal to No_scan_tag indicates a
raw block, whose contents are not scanned by the garbage collector.
For the benefits of ad-hoc polymorphic primitives such as equality and
structured input-output, structured and raw blocks are further
classified according to their tags as follows:

Tag

Contents of the block

0 to No_scan_tag-1

A structured block (an array of
Caml objects). Each field is a value.

Closure_tag

A closure representing a functional value. The first
word is a pointer to a piece of code, the remaining words are
value containing the environment.

Any word-aligned pointer to an address outside the heap can be safely
cast to and from the type value. This includes pointers returned by
malloc, and pointers to C variables (of size at least one word)
obtained with the & operator.

Caution: if a pointer returned by malloc is cast to the type value
and returned to Caml, explicit deallocation of the pointer using
free is potentially dangerous, because the pointer may still be
accessible from the Caml world. Worse, the memory space deallocated
by free can later be reallocated as part of the Caml heap; the
pointer, formerly pointing outside the Caml heap, now points inside
the Caml heap, and this can confuse the garbage collector. To avoid
these problems, it is preferable to wrap the pointer in a Caml block
with tag Abstract_tag or Custom_tag.

Records are also represented by zero-tagged blocks. The ordering of
labels in the record type declaration determines the layout of
the record fields: the value associated to the label
declared first is stored in field 0 of the block, the value associated
to the label declared next goes in field 1, and so on.

As an optimization, records whose fields all have static type float
are represented as arrays of floating-point numbers, with tag
Double_array_tag. (See the section below on arrays.)

Arrays of integers and pointers are represented like tuples,
that is, as pointers to blocks tagged 0. They are accessed with the
Field macro for reading and the modify function for writing.

Arrays of floating-point numbers (type float array)
have a special, unboxed, more efficient representation.
These arrays are represented by pointers to blocks with tag
Double_array_tag. They should be accessed with the Double_field
and Store_double_field macros.

Constructed terms are represented either by unboxed integers (for
constant constructors) or by blocks whose tag encode the constructor
(for non-constant constructors). The constant constructors and the
non-constant constructors for a given concrete type are numbered
separately, starting from 0, in the order in which they appear in the
concrete type declaration. Constant constructors are represented by
unboxed integers equal to the constructor number. Non-constant
constructors declared with a n-tuple as argument are represented by
a block of size n, tagged with the constructor number; the n
fields contain the components of its tuple argument. Other
non-constant constructors are represented by a block of size 1, tagged
with the constructor number; the field 0 contains the value of the
constructor argument. Example:

Constructed term

Representation

()

Val_int(0)

false

Val_int(0)

true

Val_int(1)

[]

Val_int(0)

h::t

Block with size = 2 and tag = 0; first field
contains h, second field t

As a convenience, caml/mlvalues.h defines the macros Val_unit,
Val_false and Val_true to refer to (), false and true.

Objects are represented as zero-tagged blocks. The first field of the
block refers to the object class and associated method suite, in a
format that cannot easily be exploited from C. The remaining fields of
the object contain the values of the instance variables of the object.
Instance variables are stored in the order in which they appear in the
class definition (taking inherited classes into account).

One may extract a public method from an object using the C function
caml_get_public_method (declared in <caml/mlvalues.h>.)
Since public method tags are hashed in the same way as variant tags,
and methods are functions taking self as first argument, if you want
to do the method call foo#bar from the C side, you should call:

Like constructed terms, values of variant types are represented either
as integers (for variants without arguments), or as blocks (for
variants with an argument). Unlike constructed terms, variant
constructors are not numbered starting from 0, but identified by a
hash value (a Caml integer), as computed by the C function
hash_variant (declared in <caml/mlvalues.h>):
the hash value for a variant constructor named, say, VConstr
is hash_variant("VConstr").

The variant value `VConstr is represented by
hash_variant("VConstr"). The variant value `VConstr(v) is
represented by a block of size 2 and tag 0, with field number 0
containing hash_variant("VConstr") and field number 1 containing
v.

Unlike constructed values, variant values taking several arguments are
not flattened. That is, `VConstr(v, v') is
represented by a block of size 2, whose field number 1 contains
the representation of the pair (v, v'), but not as a
block of size 3 containing v and v' in fields 1 and 2.

Wosize_val(v) returns the size of the block v, in words,
excluding the header.

Tag_val(v) returns the tag of the block v.

Field(v, n) returns the value contained in the
nth field of the structured block v. Fields are numbered from 0 to
Wosize_val(v)-1.

Store_field(b, n, v) stores the value
v in the field number n of value b, which must be a
structured block.

Code_val(v) returns the code part of the closure v.

string_length(v) returns the length (number of characters)
of the string v.

Byte(v, n) returns the nth character of the string
v, with type char. Characters are numbered from 0 to
string_length(v)-1.

Byte_u(v, n) returns the nth character of the string
v, with type unsigned char. Characters are numbered from 0 to
string_length(v)-1.

String_val(v) returns a pointer to the first byte of the string
v, with type char *. This pointer is a valid C string: there is a
null character after the last character in the string. However, Caml
strings can contain embedded null characters, that will confuse
the usual C functions over strings.

Double_val(v) returns the floating-point number contained in
value v, with type double.

Store_double_field(v, n, d) stores the double precision floating-point number d
in the nth element of the array of floating-point numbers v.

Data_custom_val(v) returns a pointer to the data part
of the custom block v. This pointer has type void * and must
be cast to the type of the data contained in the custom block.

Int32_val(v) returns the 32-bit integer contained
in the int32v.

Int64_val(v) returns the 64-bit integer contained
in the int64v.

Nativeint_val(v) returns the long integer contained
in the nativeintv.

The expressions Field(v, n),
Byte(v, n) and
Byte_u(v, n)
are valid l-values. Hence, they can be assigned to, resulting in an
in-place modification of value v.
Assigning directly to Field(v, n) must
be done with care to avoid confusing the garbage collector (see
below).

Atom(t) returns an ``atom'' (zero-sized block) with tag t.
Zero-sized blocks are preallocated outside of the heap. It is
incorrect to try and allocate a zero-sized block using the functions below.
For instance, Atom(0) represents the empty array.

alloc(n, t) returns a fresh block of size n
with tag t. If t is less than No_scan_tag, then the
fields of the block are initialized with a valid value in order to
satisfy the GC constraints.

copy_double(d) returns a floating-point value initialized
with the doubled.

copy_int32(i), copy_int64(i) and
copy_nativeint(i) return a value of Caml type int32,
int64 and nativeint, respectively, initialized with the integer
i.

alloc_array(f, a) allocates an array of values, calling
function f over each element of the input array a to transform it
into a value. The array a is an array of pointers terminated by the
null pointer. The function f receives each pointer as argument, and
returns a value. The zero-tagged block returned by
alloc_array(f, a) is filled with the values returned by the
successive calls to f. (This function must not be used to build
an array of floating-point numbers.)

copy_string_array(p) allocates an array of strings, copied from
the pointer to a string array p (a char **). p must
be NULL-terminated.

Low-level interface

The following functions are slightly more efficient than alloc, but
also much more difficult to use.

From the standpoint of the allocation functions, blocks are divided
according to their size as zero-sized blocks, small blocks (with size
less than or equal to Max_young_wosize), and large blocks (with
size greater than Max_young_wosize). The constant
Max_young_wosize is declared in the include file mlvalues.h. It
is guaranteed to be at least 64 (words), so that any block with
constant size less than or equal to 64 can be assumed to be small. For
blocks whose size is computed at run-time, the size must be compared
against Max_young_wosize to determine the correct allocation procedure.

alloc_small(n, t) returns a fresh small block of size
n£Max_young_wosize words, with tag t.
If this block is a structured block (i.e. if t < No_scan_tag), then
the fields of the block (initially containing garbage) must be initialized
with legal values (using direct assignment to the fields of the block)
before the next allocation.

alloc_shr(n, t) returns a fresh block of size
n, with tag t.
The size of the block can be greater than Max_young_wosize. (It
can also be smaller, but in this case it is more efficient to call
alloc_small instead of alloc_shr.)
If this block is a structured block (i.e. if t < No_scan_tag), then
the fields of the block (initially containing garbage) must be initialized
with legal values (using the initialize function described below)
before the next allocation.

Raising arbitrary exceptions from C is more delicate: the
exception identifier is dynamically allocated by the Caml program, and
therefore must be communicated to the C function using the
registration facility described below in section 18.7.3.
Once the exception identifier is recovered in C, the following
functions actually raise the exception:

raise_constant(id) raises the exception id with
no argument;

raise_with_arg(id, v) raises the exception
id with the Caml value v as argument;

raise_with_string(id, s), where s is a
null-terminated C string, raises the exception id with a copy of
the C string s as argument.

All the macros described in this section are declared in the
memory.h header file.

Rule 1
A function that has parameters or local variables of type value must
begin with a call to one of the CAMLparam macros and return with
CAMLreturn or CAMLreturn0.

There are six CAMLparam macros: CAMLparam0 to CAMLparam5, which
take zero to five arguments respectively. If your function has fewer
than 5 parameters of type value, use the corresponding macros
with these parameters as arguments. If your function has more than 5
parameters of type value, use CAMLparam5 with five of these
parameters, and use one or more calls to the CAMLxparam macros for
the remaining parameters (CAMLxparam1 to CAMLxparam5).

The macros CAMLreturn and CAMLreturn0 are used to replace the C
keyword return. Every occurence of return x must be replaced by
CAMLreturn (x), every occurence of return without argument must be
replaced by CAMLreturn0. If your C function is a procedure (i.e. if
it returns void), you must insert CAMLreturn0 at the end (to replace
C's implicit return).

Note:

some C compilers give bogus warnings about unused
variables caml__dummy_xxx at each use of CAMLparam and
CAMLlocal. You should ignore them.

Note:

if your function is a primitive with more than 5 arguments
for use with the byte-code runtime, its arguments are not values and
must not be declared (they have types value * and int).

Rule 2
Local variables of type value must be declared with one of the
CAMLlocal macros. Arrays of values are declared with
CAMLlocalN.

The macros CAMLlocal1 to CAMLlocal5 declare and initialize one to
five local variables of type value. The variable names are given as
arguments to the macros. CAMLlocalN(x, n) declares
and initializes a local variable of type value [n]. You can
use several calls to these macros if you have more than 5 local
variables. You can also use them in nested C blocks within the
function.

Rule 3
Assignments to the fields of structured blocks must be done with the
Store_field macro (for normal blocks) or Store_double_field macro
(for arrays and records of floating-point numbers). Other assignments
must not use Store_field nor Store_double_field.

Store_field (b, n, v) stores the value
v in the field number n of value b, which must be a
block (i.e. Is_block(b) must be true).

Warning:

The first argument of Store_field and
Store_double_field must be a variable declared by CAMLparam* or
a parameter declared by CAMLlocal* to ensure that a garbage
collection triggered by the evaluation of the other arguments will not
invalidate the first argument after it is computed.

Rule 4 Global variables containing values must be registered
with the garbage collector using the register_global_root function.

Registration of a global variable v is achieved by calling
register_global_root(&v) just before a valid value is stored in v
for the first time.

A registered global variable v can be un-registered by calling
remove_global_root(&v).

Note: The CAML macros use identifiers (local variables, type
identifiers, structure tags) that start with caml__. Do not use any
identifier starting with caml__ in your programs.

We now give the GC rules corresponding to the low-level allocation
functions alloc_small and alloc_shr. You can ignore those rules
if you stick to the simplified allocation function alloc.

Rule 5 After a structured block (a block with tag less than
No_scan_tag) is allocated with the low-level functions, all fields
of this block must be filled with well-formed values before the next
allocation operation. If the block has been allocated with
alloc_small, filling is performed by direct assignment to the fields
of the block:

Field(v, n) = vn;

If the block has been allocated with alloc_shr, filling is performed
through the initialize function:

initialize(&Field(v, n), vn);

The next allocation can trigger a garbage collection. The garbage
collector assumes that all structured blocks contain well-formed
values. Newly created blocks contain random data, which generally do
not represent well-formed values.

If you really need to allocate before the fields can receive their
final value, first initialize with a constant value (e.g.
Val_unit), then allocate, then modify the fields with the correct
value (see rule 6).

Rule 6 Direct assignment to a field of a block, as in

Field(v, n) = w;

is safe only if v is a block newly allocated by alloc_small;
that is, if no allocation took place between the
allocation of v and the assignment to the field. In all other cases,
never assign directly. If the block has just been allocated by alloc_shr,
use initialize to assign a value to a field for the first time:

initialize(&Field(v, n), w);

Otherwise, you are updating a field that previously contained a
well-formed value; then, call the modify function:

modify(&Field(v, n), w);

To illustrate the rules above, here is a C function that builds and
returns a list containing the two integers given as parameters.
First, we write it using the simplified allocation functions:

Here, the registering of result is not strictly needed, because no
allocation takes place after it gets its value, but it's easier and
safer to simply register all the local variables that have type value.

Here is the same function written using the low-level allocation
functions. We notice that the cons cells are small blocks and can be
allocated with alloc_small, and filled by direct assignments on
their fields.

It would be incorrect to perform
Field(r, 1) = tail directly, because the allocation of tail
has taken place since r was allocated. tail is not registered as
a root because there is no allocation between the assignment where it
takes its value and the modify statement that uses the value.

This section outlines how the functions from the Unix curses library
can be made available to Objective Caml programs. First of all, here is
the interface curses.mli that declares the curses primitives and
data types:

So far, we have described how to call C functions from Caml. In this
section, we show how C functions can call Caml functions, either as
callbacks (Caml calls C which calls Caml), or because the main program
is written in C.

callbackN(f, n, args) applies the functional value f
to the n arguments contained in the array of values args.

If the function f does not return, but raises an exception that
escapes the scope of the application, then this exception is
propagated to the next enclosing Caml code, skipping over the C
code. That is, if a Caml function f calls a C function g that
calls back a Caml function h that raises a stray exception, then the
execution of g is interrupted and the exception is propagated back
into f.

If the C code wishes to catch exceptions escaping the Caml function,
it can use the functions callback_exn, callback2_exn,
callback3_exn, callbackN_exn. These functions take the same
arguments as their non-_exn counterparts, but catch escaping
exceptions and return them to the C code. The return value v of the
callback*_exn functions must be tested with the macro
Is_exception_result(v). If the macro returns ``false'', no
exception occured, and v is the value returned by the Caml
function. If Is_exception_result(v) returns ``true'',
an exception escaped, and its value (the exception descriptor) can be
recovered using Extract_exception(v).

The main difficulty with the callback functions described above is
obtaining a closure to the Caml function to be called. For this
purpose, Objective Caml provides a simple registration mechanism, by
which Caml code can register Caml functions under some global name,
and then C code can retrieve the corresponding closure by this global
name.

On the Caml side, registration is performed by evaluating
Callback.registern v. Here, n is the global name
(an arbitrary string) and v the Caml value. For instance:

On the C side, a pointer to the value registered under name n is
obtained by calling caml_named_value(n). The returned
pointer must then be dereferenced to recover the actual Caml value.
If no value is registered under the name n, the null pointer is
returned. For example, here is a C wrapper that calls the Caml function f
above:

The pointer returned by caml_named_value is constant and can safely
be cached in a C variable to avoid repeated name lookups. On the other
hand, the value pointed to can change during garbage collection and
must always be recomputed at the point of use. Here is a more
efficient variant of call_caml_f above that calls caml_named_value
only once:

The registration mechanism described above can also be used to
communicate exception identifiers from Caml to C. The Caml code
registers the exception by evaluating
Callback.register_exceptionn exn, where n is an
arbitrary name and exn is an exception value of the
exception to register. For example:

The C code can then recover the exception identifier using
caml_named_value and pass it as first argument to the functions
raise_constant, raise_with_arg, and raise_with_string (described
in section 18.4.5) to actually raise the exception. For
example, here is a C function that raises the Error exception with
the given argument:

In normal operation, a mixed Caml/C program starts by executing the
Caml initialization code, which then may proceed to call C
functions. We say that the main program is the Caml code. In some
applications, it is desirable that the C code plays the role of the
main program, calling Caml functions when needed. This can be achieved as
follows:

The C part of the program must provide a main function,
which will override the default main function provided by the Caml
runtime system. Execution will start in the user-defined main function
just like for a regular C program.

At some point, the C code must call caml_main(argv) to
initialize the Caml code. The argv argument is a C array of strings
(type char **), terminated with a NULL pointer,
which represents the command-line arguments, as
passed as second argument to main. The Caml array Sys.argv will
be initialized from this parameter. For the bytecode compiler,
argv[0] and argv[1] are also consulted to find the file containing
the bytecode.

The call to caml_main initializes the Caml runtime system,
loads the bytecode (in the case of the bytecode compiler), and
executes the initialization code of the Caml program. Typically, this
initialization code registers callback functions using Callback.register.
Once the Caml initialization code is complete, control returns to the
C code that called caml_main.

The C code can then invoke Caml functions using the callback
mechanism (see section 18.7.1).

The bytecode compiler in custom runtime mode (ocamlc -custom)
normally appends the bytecode to the executable file containing the
custom runtime. This has two consequences. First, the final linking
step must be performed by ocamlc. Second, the Caml runtime library
must be able to find the name of the executable file from the
command-line arguments. When using caml_main(argv) as in
section 18.7.4, this means that argv[0] or argv[1] must
contain the executable file name.

An alternative is to embed the bytecode in the C code. The
-output-obj option to ocamlc is provided for this purpose.
It causes the ocamlc compiler to output a C object file (.o file)
containing the bytecode for the Caml part of the program, as well as a
caml_startup function. The C object file produced by ocamlc -output-obj can then be linked with C code using the standard C
compiler, or stored in a C library.

The caml_startup function must be called from the main C program in
order to initialize the Caml runtime and execute the Caml
initialization code. Just like caml_main, it takes one argv
parameter containing the command-line parameters. Unlike caml_main,
this argv parameter is used only to initialize Sys.argv, but not
for finding the name of the executable file.

The native-code compiler ocamlopt also supports the -output-obj
option, causing it to output a C object file containing the native
code for all Caml modules on the command-line, as well as the Caml
startup code. Initialization is performed by calling caml_startup as
in the case of the bytecode compiler.

For the final linking phase, in addition to the object file produced
by -output-obj, you will have to provide the Objective Caml runtime
library (libcamlrun.a for bytecode, libasmrun.a for native-code),
as well as all C libraries that are required by the Caml libraries
used. For instance, assume the Caml part of your program uses the
Unix library. With ocamlc, you should do:

Warning:

On some ports, special options are required on the final
linking phase that links together the object file produced by the
-output-obj option and the remainder of the program. Those options
are shown in the configuration file config/Makefile generated during
compilation of Objective Caml, as the variables BYTECCLINKOPTS
(for object files produced by ocamlc -output-obj) and
NATIVECCLINKOPTS (for object files produced by ocamlopt -output-obj). Currently, the only ports that require special
attention are:

Alpha under Digital Unix / Tru64 Unix with gcc:
object files produced by ocamlc -output-obj must be linked with the
gcc options -Wl,-T,12000000 -Wl,-D,14000000.
This is not necessary for object files produced by ocamlopt -output-obj.

Windows NT: the object file produced by Objective Caml have been
compiled with the /MT flag, and therefore all other object files
linked with it should also be compiled with /MT.

This section illustrates the callback facilities described in
section 18.7. We are going to package some Caml functions
in such a way that they can be linked with C code and called from C
just like any C functions. The Caml functions are defined in the
following mod.ml Caml source:

Blocks with tag Custom_tag contain both arbitrary user data and a
pointer to a C struct, with type struct custom_operations, that
associates user-provided finalization, comparison, hashing,
serialization and deserialization functions to this block.

The struct custom_operations is defined in <caml/custom.h> and
contains the following fields:

char *identifier
A zero-terminated character string serving as an identifier for
serialization and deserialization operations.

void (*finalize)(value v)
The finalize field contains a pointer to a C function that is called
when the block becomes unreachable and is about to be reclaimed.
The block is passed as first argument to the function.
The finalize field can also be NULL to indicate that no
finalization function is associated with the block.
Important note: the v parameter of this function is of type value, but
it must not be declared using the CAMLparam macros.

int (*compare)(value v1, value v2)
The compare field contains a pointer to a C function that is
called whenever two custom blocks are compared using Caml's generic
comparison operators (=, <>, <=, >=, <, > and
compare). The C function should return 0 if the data contained in
the two blocks are structurally equal, a negative integer if the data
from the first block is less than the data from the second block, and
a positive integer if the data from the first block is greater than
the data from the second block.
Note: You must use CAMLparam to declare v1 and v2 and CAMLreturn
to return the result.

The compare field can be set to custom_compare_default; this
default comparison function simply raises Failure.

long (*hash)(value v)
The hash field contains a pointer to a C function that is called
whenever Caml's generic hash operator (see module Hashtbl) is
applied to a custom block. The C function can return an arbitrary
long integer representing the hash value of the data contained in the
given custom block. The hash value must be compatible with the
compare function, in the sense that two structurally equal data
(that is, two custom blocks for which compare returns 0) must have
the same hash value.
Note: You must use CAMLparam to declare v and CAMLreturn
to return the result.

The hash field can be set to custom_hash_default, in which case
the custom block is ignored during hash computation.

void (*serialize)(value v, unsigned long * wsize_32, unsigned long * wsize_64)
The serialize field contains a pointer to a C function that is
called whenever the custom block needs to be serialized (marshaled)
using the Caml functions output_value or Marshal.to_....
For a custom block, those functions first write the identifier of the
block (as given by the identifier field) to the output stream,
then call the user-provided serialize function. That function is
responsible for writing the data contained in the custom block, using
the serialize_... functions defined in <caml/intext.h> and listed
below. The user-provided serialize function must then store in its
wsize_32 and wsize_64 parameters the sizes in bytes of the data
part of the custom block on a 32-bit architecture and on a 64-bit
architecture, respectively.
Note: You must use CAMLparam to declare v and CAMLreturn
to return the result.

The serialize field can be set to custom_serialize_default,
in which case the Failure exception is raised when attempting to
serialize the custom block.

unsigned long (*deserialize)(void * dst)
The deserialize field contains a pointer to a C function that is
called whenever a custom block with identifier identifier needs to
be deserialized (un-marshaled) using the Caml functions input_value
or Marshal.from_.... This user-provided function is responsible for
reading back the data written by the serialize operation, using the
deserialize_... functions defined in <caml/intext.h> and listed
below. It must then rebuild the data part of the custom block
and store it at the pointer given as the dst argument. Finally, it
returns the size in bytes of the data part of the custom block.
This size must be identical to the wsize_32 result of
the serialize operation if the architecture is 32 bits, or
wsize_64 if the architecture is 64 bits.

The deserialize field can be set to custom_deserialize_default
to indicate that deserialization is not supported. In this case,
do not register the struct custom_operations with the deserializer
using register_custom_operations (see below).

Custom blocks must be allocated via the alloc_custom function.
alloc_custom(ops, size, used, max)
returns a fresh custom block, with room for size bytes of user
data, and whose associated operations are given by ops (a
pointer to a struct custom_operations, usually statically allocated
as a C global variable).

The two parameters used and max are used to control the
speed of garbage collection when the finalized object contains
pointers to out-of-heap resources. Generally speaking, the
Caml incremental major collector adjusts its speed relative to the
allocation rate of the program. The faster the program allocates, the
harder the GC works in order to reclaim quickly unreachable blocks
and avoid having large amount of ``floating garbage'' (unreferenced
objects that the GC has not yet collected).

Normally, the allocation rate is measured by counting the in-heap size
of allocated blocks. However, it often happens that finalized
objects contain pointers to out-of-heap memory blocks and other resources
(such as file descriptors, X Windows bitmaps, etc.). For those
blocks, the in-heap size of blocks is not a good measure of the
quantity of resources allocated by the program.

The two arguments used and max give the GC an idea of how
much out-of-heap resources are consumed by the finalized block
being allocated: you give the amount of resources allocated to this
object as parameter used, and the maximum amount that you want
to see in floating garbage as parameter max. The units are
arbitrary: the GC cares only about the ratio used / max.

For instance, if you are allocating a finalized block holding an X
Windows bitmap of w by h pixels, and you'd rather not
have more than 1 mega-pixels of unreclaimed bitmaps, specify
used = w * h and max = 1000000.

Another way to describe the effect of the used and max
parameters is in terms of full GC cycles. If you allocate many custom
blocks with used / max = 1 / N, the GC will then do one
full cycle (examining every object in the heap and calling
finalization functions on those that are unreachable) every N
allocations. For instance, if used = 1 and max = 1000,
the GC will do one full cycle at least every 1000 allocations of
custom blocks.

If your finalized blocks contain no pointers to out-of-heap resources,
or if the previous discussion made little sense to you, just take
used = 0 and max = 1. But if you later find that the
finalization functions are not called ``often enough'', consider
increasing the used / max ratio.

The data part of a custom block v can be
accessed via the pointer Data_custom_val(v). This pointer
has type void * and should be cast to the actual type of the data
stored in the custom block.

The contents of custom blocks are not scanned by the garbage
collector, and must therefore not contain any pointer inside the Caml
heap. In other terms, never store a Caml value in a custom block,
and do not use Field, Store_field nor modify to access the data
part of a custom block. Conversely, any C data structure (not
containing heap pointers) can be stored in a custom block.

The following functions, defined in <caml/intext.h>, are provided to
write and read back the contents of custom blocks in a portable way.
Those functions handle endianness conversions when e.g. data is
written on a little-endian machine and read back on a big-endian machine.

Function

Action

serialize_int_1

Write a 1-byte integer

serialize_int_2

Write a 2-byte integer

serialize_int_4

Write a 4-byte integer

serialize_int_8

Write a 8-byte integer

serialize_float_4

Write a 4-byte float

serialize_float_8

Write a 8-byte float

serialize_block_1

Write an array of 1-byte quantities

serialize_block_2

Write an array of 2-byte quantities

serialize_block_4

Write an array of 4-byte quantities

serialize_block_8

Write an array of 8-byte quantities

deserialize_uint_1

Read an unsigned 1-byte integer

deserialize_sint_1

Read a signed 1-byte integer

deserialize_uint_2

Read an unsigned 2-byte integer

deserialize_sint_2

Read a signed 2-byte integer

deserialize_uint_4

Read an unsigned 4-byte integer

deserialize_sint_4

Read a signed 4-byte integer

deserialize_uint_8

Read an unsigned 8-byte integer

deserialize_sint_8

Read a signed 8-byte integer

deserialize_float_4

Read a 4-byte float

deserialize_float_8

Read an 8-byte float

deserialize_block_1

Read an array of 1-byte quantities

deserialize_block_2

Read an array of 2-byte quantities

deserialize_block_4

Read an array of 4-byte quantities

deserialize_block_8

Read an array of 8-byte quantities

deserialize_error

Signal an error during deserialization;
input_value or Marshal.from_... raise a Failure exception after
cleaning up their internal data structures

Serialization functions are attached to the custom blocks to which
they apply. Obviously, deserialization functions cannot be attached
this way, since the custom block does not exist yet when
deserialization begins! Thus, the struct custom_operations that
contain deserialization functions must be registered with the
deserializer in advance, using the register_custom_operations
function declared in <caml/custom.h>. Deserialization proceeds by
reading the identifier off the input stream, allocating a custom block
of the size specified in the input stream, searching the registered
struct custom_operation blocks for one with the same identifier, and
calling its deserialize function to fill the data part of the custom block.

Identifiers in struct custom_operations must be chosen carefully,
since they must identify uniquely the data structure for serialization
and deserialization operations. In particular, consider including a
version number in the identifier; this way, the format of the data can
be changed later, yet backward-compatible deserialisation functions
can be provided.

Identifiers starting with _ (an underscore character) are reserved
for the Objective Caml runtime system; do not use them for your custom
data. We recommend to use a URL
(http://mymachine.mydomain.com/mylibrary/version-number)
or a Java-style package name
(com.mydomain.mymachine.mylibrary.version-number)
as identifiers, to minimize the risk of identifier collision.

Custom blocks generalize the finalized blocks that were present in
Objective Caml prior to version 3.00. For backward compatibility, the
format of custom blocks is compatible with that of finalized blocks,
and the alloc_final function is still available to allocate a custom
block with a given finalization function, but default comparison,
hashing and serialization functions. alloc_final(n, f, used, max) returns a fresh custom block of
size n words, with finalization function f. The first
word is reserved for storing the custom operations; the other
n-1 words are available for your data. The two parameters
used and max are used to control the speed of garbage
collection, as described for alloc_custom.

The ocamlmklib command facilitates the construction of libraries
containing both Caml code and C code, and usable both in static
linking and dynamic linking modes.

Windows:

This command is available only under Cygwin, but not for the
native Win32 port.

The ocamlmklib command takes three kinds of arguments:

Caml source files and object files (.cmo, .cmx, .ml)
comprising the Caml part of the library;

C object files (.o, .a) comprising the C part of the
library;

Support libraries for the C part (-llib).

It generates the following outputs:

A Caml bytecode library .cma incorporating the .cmo and
.ml Caml files given as arguments, and automatically referencing the
C library generated with the C object files.

A Caml native-code library .cmxa incorporating the .cmx and
.ml Caml files given as arguments, and automatically referencing the
C library generated with the C object files.

If dynamic linking is supported on the target platform, a
.so shared library built from the C object files given as arguments,
and automatically referencing the support libraries.

A C static library .a built from the C object files.

In addition, the following options are recognized:

-cclib, -ccopt, -I, -linkall

These options are passed as is to ocamlc or ocamlopt.
See the documentation of these commands.

-pthread, -rpath, -R, -Wl,-rpath, -Wl,-R

These options are passed as is to the C compiler. Refer to the
documentation of the C compiler.

-custom

Force the construction of a statically linked library
only, even if dynamic linking is supported.

-failsafe

Fall back to building a statically linked library
if a problem occurs while building the shared library (e.g. some of
the support libraries are not available as shared libraries).

-Ldir

Add dir to the search path for support
libraries (-llib).

-ocamlccmd

Use cmd instead of ocamlc to call
the bytecode compiler.

-ocamloptcmd

Use cmd instead of ocamlopt to call
the native-code compiler.

-ooutput

Set the name of the generated Caml library.
ocamlmklib will generate output.cma and/or output.cmxa.
If not specified, defaults to a.

-ocoutputc

Set the name of the generated C library.
ocamlmklib will generate liboutputc.so (if shared
libraries are supported) and liboutputc.a.
If not specified, defaults to the output name given with -o.

Example

Consider a Caml interface to the standard libz
C library for reading and writing compressed files. Assume this
library resides in /usr/local/zlib. This interface is
composed of a Caml part zip.cmo/zip.cmx and a C part zipstubs.o
containing the stub code around the libz entry points. The
following command builds the Caml libraries zip.cma and zip.cmxa,
as well as the companion C libraries dllzip.so and libzip.a:

ocamlmklib -o zip zip.cmo zip.cmx zipstubs.o -lz -L/usr/local/zlib

If shared libraries are supported, this performs the following
commands:

Instead of building simultaneously the bytecode library, the
native-code library and the C libraries, ocamlmklib can be called
three times to build each separately. Thus,

ocamlmklib -o zip zip.cmo -lz -L/usr/local/zlib

builds the bytecode library zip.cma, and

ocamlmklib -o zip zip.cmx -lz -L/usr/local/zlib

builds the native-code library zip.cmxa, and

ocamlmklib -o zip zipstubs.o -lz -L/usr/local/zlib

builds the C libraries dllzip.so and libzip.a. Notice that the
support libraries (-lz) and the corresponding options
(-L/usr/local/zlib) must be given on all three invocations of ocamlmklib,
because they are needed at different times depending on whether shared
libraries are supported.

This chapter describes the Objective Caml core library, which is
composed of declarations for built-in types and exceptions, plus
the module Pervasives that provides basic operations on these
built-in types. The Pervasives module is special in two
ways:

It is automatically linked with the user's object code files by
the ocamlc command (chapter 8).

It is automatically ``opened'' when a compilation starts, or
when the toplevel system is launched. Hence, it is possible to use
unqualified identifiers to refer to the functions provided by the
Pervasives module, without adding a open Pervasives directive.

Conventions

The declarations of the built-in types and the components of module
Pervasives are printed one by one in typewriter font, followed by a
short comment. All library modules and the components they provide are
indexed at the end of this report.

The following built-in types and predefined exceptions are always
defined in the
compilation environment, but are not part of any module. As a
consequence, they can only be referred by their short names.

The type of signed, platform-native integers (32 bits on 32-bit
processors, 64 bits on 64-bit processors).
See the Nativeint[Nativeint] module.

type ('a, 'b, 'c, 'd) format4

The type of format strings. 'a is the type of the parameters
of the format, 'd is the result type for the printf-style
function, 'b is the type of the first argument given to
\%a and \%t printing functions (see module Printf[Printf]),
and 'c is the result type of these functions.

type 'a lazy_t

This type is used to implement the Lazy[Lazy] module.
It should not be used directly.

Predefined exceptions

exception Match_failure of (string * int * int)

Exception raised when none of the cases of a pattern-matching
apply. The arguments are the location of the match keyword
in the source code (file name, line number, column number).

exception Assert_failure of (string * int * int)

Exception raised when an assertion fails. The arguments are
the location of the assert keyword in the source code
(file name, line number, column number).

exception Invalid_argument of string

Exception raised by library functions to signal that the given
arguments do not make sense.

exception Failure of string

Exception raised by library functions to signal that they are
undefined on the given arguments.

exception Not_found

Exception raised by search functions when the desired object
could not be found.

exception Out_of_memory

Exception raised by the garbage collector
when there is insufficient memory to complete the computation.

exception Stack_overflow

Exception raised by the bytecode interpreter when the evaluation
stack reaches its maximal size. This often indicates infinite
or excessively deep recursion in the user's program.
(Not fully implemented by the native-code compiler;
see section 11.5.)

exception Sys_error of string

Exception raised by the input/output functions to report
an operating system error.

exception End_of_file

Exception raised by input functions to signal that the
end of file has been reached.

exception Division_by_zero

Exception raised by division and remainder operations
when their second argument is null.
(Not fully implemented by the native-code compiler;
see section 11.5.)

exception Sys_blocked_io

A special case of Sys_error raised when no I/O is possible
on a non-blocking I/O channel.

exception Undefined_recursive_module of (string * int * int)

Exception raised when an ill-founded recursive module definition
is evaluated. (See section 7.9.)
The arguments are the location of the definition in the source code
(file name, line number, column number).

This chapter describes the functions provided by the Objective Caml
standard library. The modules from the standard library are
automatically linked with the user's object code files by the ocamlc
command. Hence, these modules can be used in standalone programs without
having to add any .cmo file on the command line for the linking
phase. Similarly, in interactive use, these globals can be used in
toplevel phrases without having to load any .cmo file in memory.

Unlike the Pervasive module from the core library, the modules from the
standard library are not automatically ``opened'' when a compilation
starts, or when the toplevel system is launched. Hence it is necessary
to use qualified identifiers to refer to the functions provided by these
modules, or to add open directives.

Conventions

For easy reference, the modules are listed below in alphabetical order
of module names.
For each module, the declarations from its signature are printed
one by one in typewriter font, followed by a short comment.
All modules and the identifiers they export are indexed at the end of
this report.

The unix library makes many Unix
system calls and system-related library functions available to
Objective Caml programs. This chapter describes briefly the functions
provided. Refer to sections 2 and 3 of the Unix manual for more
details on the behavior of these functions.

Not all functions are provided by all Unix variants. If some functions
are not available, they will raise Invalid_arg when called.

Programs that use the unix library must be linked as follows:

ocamlc other options unix.cma other files
ocamlopt other options unix.cmxa other files

A fairly complete emulation of the Unix system calls is provided in
the Windows version of Objective Caml. The end of this chapter gives
more information on the functions that are not supported under Windows.

The Cygwin port of Objective Caml fully implements all functions from
the Unix module. The native Win32 ports implement a subset of them.
Below is a list of the functions that are not implemented, or only
partially implemented, by the Win32 ports. Functions not mentioned are
fully implemented and behave as described previously in this chapter.

Functions

Comment

fork

not implemented, use create_process or threads

wait

not implemented, use waitpid

waitpid

can only wait for a given PID, not any child process

getppid

not implemented (meaningless under Windows)

nice

not implemented

in_channel_of_descr

does not work on sockets under Windows
95, 98, ME; works fine under NT, 2000, XP

out_channel_of_descr

ditto

truncate, ftruncate

not implemented

lstat, fstat

not implemented

link, symlink, readlink

not implemented (no links under
Windows)

fchmod

not implemented

chown, fchown

not implemented (make no sense on a DOS
file system)

umask

not implemented

set_nonblock, clear_nonblock

implemented as dummy
functions; use threads instead of non-blocking I/O

rewinddir

not implemented; re-open the directory instead

mkfifo

not implemented

select

implemented, but works only for sockets; use threads
if you need to wait on other kinds of file descriptors

More documentation on the functions provided in this library can be found
in The CAML Numbers Reference Manual by
Valérie Ménissier-Morain, technical report 141, INRIA, july 1992
(available electronically,
ftp://ftp.inria.fr/INRIA/publication/RT/RT-0141.ps.gz).

Programs that use the num library must be linked as follows:

ocamlc other options nums.cma other files
ocamlopt other options nums.cmxa other files

The str library provides high-level string processing functions,
some based on regular expressions. It is intended to support the kind
of file processing that is usually performed with scripting languages
such as awk, perl or sed.

Programs that use the str library must be linked as follows:

ocamlc other options str.cma other files
ocamlopt other options str.cmxa other files

The threads library allows concurrent programming in Objective Caml.
It provides multiple threads of control (also called lightweight
processes) that execute concurrently in the same memory space. Threads
communicate by in-place modification of shared data structures, or by
sending and receiving data on communication channels.

The threads library is implemented by time-sharing on a single
processor. It will not take advantage of multi-processor machines.
Using this library will therefore never make programs run
faster. However, many programs are easier to write when structured as
several communicating processes.

Two implementations of the threads library are available, depending
on the capabilities of the operating system:

System threads. This implementation builds on the OS-provided threads
facilities: POSIX 1003.1c threads for Unix, and Win32 threads for
Windows. When available, system threads support both bytecode and
native-code programs.

VM-level threads. This implementation performs time-sharing and
context switching at the level of the OCaml virtual machine (bytecode
interpreter). It is available on Unix systems, and supports only
bytecode programs. It cannot be used with native-code programs.

Here are the graphics mode specifications supported by open_graph on
the X11 implementation of this library:
the argument to open_graph has the format
"display-name geometry",
where display-name is the name of the X-windows display to
connect to, and geometry is a standard X-windows geometry
specification. The two components are separated by a space. Either can
be omitted, or both. Examples:

open_graph "foo:0"

connects to the display foo:0 and creates a window with the default geometry

open_graph "foo:0 300x100+50-0"

connects to the display foo:0 and creates a window 300 pixels wide
by 100 pixels tall, at location (50,0)

open_graph " 300x100+50-0"

connects to the default display and creates a window 300 pixels wide
by 100 pixels tall, at location (50,0)

open_graph ""

connects to the default display and creates a window with the default
geometry.

Windows:

This library is available both for standalone compiled programs and
under the toplevel application ocamlwin.exe. For the latter, this
library must be loaded in-core by typing

#load "graphics.cma";;

The screen coordinates are interpreted as shown in the figure below.
Notice that the coordinate system used is the same as in mathematics:
y increases from the bottom of the screen to the top of the screen,
and angles are measured counterclockwise (in degrees).
Drawing is clipped to the screen.

The dbm library provides access to NDBM databases under Unix.
NDBM databases maintain key/data associations, where both the key and
the data are arbitrary strings. They support fairly large databases
(several gigabytes) and can retrieve a keyed item in one or two file
system accesses. Refer to the Unix manual pages for more information.

Unix:

Programs that use the dbm library must be linked as follows:

ocamlc other options dbm.cma other files
ocamlopt other options dbm.cmxa other files

The dynlink library supports type-safe dynamic loading and linking
of bytecode object files (.cmo and .cma files) in a running
bytecode program. Type safety is ensured by limiting the set of
modules from the running program that the loaded object file can
access, and checking that the running program and the loaded object
file have been compiled against the same interfaces for these modules.

Programs that use the dynlink library simply need to link
dynlink.cma with their object files and other libraries.
Dynamic linking is available only to bytecode programs compiled with
ocamlc, not to native-code programs compiled with ocamlopt.

The labltk library provides access to the Tcl/Tk GUI from Objective
Caml programs. This interface is generated in an automated way, and
you should refer to Tcl/Tk books and man pages for detailed
information on the behavior of the numerous functions. We also suggest
to use ocamlbrowser to see the types of the various functions, that
are the best documentation for the library itself.

The labltk library is available for any system with Tcl/Tk installed,
starting from Tcl 7.5/Tk 4.1 up to Tcl/Tk 8.3. Beware that some beta
versions may have compatibility problems.

If the library was not compiled correctly, try to run again the
configure script with the option -tkdefsswitches,
where switches is a list of C-style inclusion paths leading to
the right tcl.h and tk.h, for instance
'-I/usr/local/include/tcl8.3 -I/usr/local/include/tk8.3'.

A script is installed, to make easier the use of the labltk
library as toplevel.

labltk

This is a toplevel including the labltk library, and the path is
already set as to allow the use of the various modules. It also
includes code for the Unix and Str libraries. You can use it
in place of ocaml.

Windows:

The labltk library has been precompiled for use with Tcl/Tk 8.3.
You must first have it installed on your system.
It can be downloaded fromhttp://www.scriptics.com/products/tcltk/8.3.html.
After installing it, you must put the dynamically loaded libraries
tcl83.dll and tk83.dll (from the bin directory of the Tcl
installation) in a directory included in you path.

No toplevel is available, but you can load the library from the
standard toplevel with the following commands.

Giving a detailed account of each of these module would be impractical
here. We will just present some of the basic functions in the module
Tk. Note that for most other modules information can be found in the
Tcl man page of their name.

The bigarray library implements large, multi-dimensional, numerical
arrays. These arrays are called ``big arrays'' to distinguish them
from the standard Caml arrays described in
Module Array.
The main differences between ``big arrays'' and standard Caml arrays
are as follows:

Big arrays are not limited in size, unlike Caml arrays
(float array are limited to 2097151 elements on a 32-bit platform,
other array types to 4194303 elements).

Big arrays are multi-dimensional. Any number of dimensions
between 1 and 16 is supported. In contrast, Caml arrays are
mono-dimensional and require encoding multi-dimensional arrays as
arrays of arrays.

Big arrays can only contain integers and floating-point
numbers, while Caml arrays can contain arbitrary Caml data types.
However, big arrays provide more space-efficient storage of integer
and floating-point elements, in particular because they support
``small'' types such as single-precision floats and 8 and 16-bit
integers, in addition to the standard Caml types of double-precision
floats and 32 and 64-bit integers.

The memory layout of big arrays is entirely compatible with that
of arrays in C and Fortran, allowing large arrays to be passed back
and forth between Caml code and C / Fortran code with no data copying
at all.

Big arrays support interesting high-level operations that normal
arrays do not provide efficiently, such as extracting sub-arrays and
``slicing'' a multi-dimensional array along certain dimensions, all
without any copying.

Programs that use the bigarray library must be linked as follows:

ocamlc other options bigarray.cma other files
ocamlopt other options bigarray.cmxa other files

If v is a Caml value representing a big array, the expression
Data_bigarray_val(v) returns a pointer to the data part of the array.
This pointer is of type void * and can be cast to the appropriate C
type for the array (e.g. double [], char [][10], etc).

Various characteristics of the Caml big array can be consulted from C
as follows:

C expression

Returns

Bigarray_val(v)->num_dims

number of dimensions

Bigarray_val(v)->dim[i]

i-th dimension

Bigarray_val(v)->flags & BIGARRAY_KIND_MASK

kind of array elements

The kind of array elements is one of the following constants:

Constant

Element kind

BIGARRAY_FLOAT32

32-bit single-precision floats

BIGARRAY_FLOAT64

64-bit double-precision floats

BIGARRAY_SINT8

8-bit signed integers

BIGARRAY_UINT8

8-bit unsigned integers

BIGARRAY_SINT16

16-bit signed integers

BIGARRAY_UINT16

16-bit unsigned integers

BIGARRAY_INT32

32-bit signed integers

BIGARRAY_INT64

64-bit signed integers

BIGARRAY_CAML_INT

31- or 63-bit signed integers

BIGARRAY_NATIVE_INT

32- or 64-bit (platform-native) integers

The following example shows the passing of a two-dimensional big array
to a C function and a Fortran function.

A pointer p to an already-allocated C or Fortran array can be
wrapped and returned to Caml as a big array using the alloc_bigarray
or alloc_bigarray_dims functions.

alloc_bigarray(kind|layout, numdims, p, dims)

Return a Caml big array wrapping the data pointed to by p.
kind is the kind of array elements (one of the BIGARRAY_
kind constants above). layout is BIGARRAY_C_LAYOUT for an
array with C layout and BIGARRAY_FORTRAN_LAYOUT for an array with
Fortran layout. numdims is the number of dimensions in the
array. dims is an array of numdims long integers, giving
the sizes of the array in each dimension.