This manual is also available in PDF. Postscript, DVI, plain text, as a bundle of HTML files, and as a bundle of Emacs Info files.
This manual documents the release 4.00 of the OCaml system. It is organized as follows.
OCaml runs on several operating systems. The parts of this manual that are specific to one operating system are presented as shown below:
Unix: This is material specific to the Unix family of operating systems, including Linux and MacOS X.
Windows: This is material specific to Microsoft Windows (2000, XP, Vista, Seven).
The OCaml system is copyright © 1996–2012 Institut National de Recherche en Informatique et en Automatique (INRIA). INRIA holds all ownership rights to the OCaml system.
The OCaml system is open source and can be freely redistributed. See the file LICENSE in the distribution for licensing information.
The present documentation is copyright © 2012 Institut National de Recherche en Informatique et en Automatique (INRIA). The OCaml documentation and user’s manual may be reproduced and distributed in whole or in part, subject to the following conditions:
The complete OCaml distribution can be accessed via the http://caml.inria.fr/Caml Web site. The http://caml.inria.fr/Caml Web site contains a lot of additional information on OCaml.
Part I |
This part of the manual is a tutorial introduction to the OCaml 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 2 with the module system, and chapter3 deals with the object-oriented features.
For this overview of OCaml, 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 OCaml 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).
# 1+2*3;; - : int = 7 # let pi = 4.0 *. atan 1.0;; val pi : float = 3.14159265358979312 # let square x = x *. x;; val square : float -> float = <fun> # square(sin pi) +. square(cos pi);; - : float = 1.
The OCaml 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;; Error: This expression has type float but an expression was expected of type int
Recursive functions are defined with the let rec binding:
# let rec fib n = if n < 2 then n else fib(n-1) + fib(n-2);; val fib : int -> int = <fun> # fib 10;; - : int = 55
In addition to integers and floating-point numbers, OCaml offers the usual basic data types: booleans, characters, and character strings.
# (1 < 2) = false;; - : bool = false # 'a';; - : char = 'a' # "Hello world";; - : string = "Hello world"
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.
# let l = ["is"; "a"; "tale"; "told"; "etc."];; val l : string list = ["is"; "a"; "tale"; "told"; "etc."] # "Life" :: l;; - : string list = ["Life"; "is"; "a"; "tale"; "told"; "etc."]
As with all other OCaml data structures, lists do not need to be explicitly allocated and deallocated from memory: all memory management is entirely automatic in OCaml. Similarly, there is no explicit handling of pointers: the OCaml compiler silently introduces pointers where necessary.
As with most OCaml 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:
# let rec sort lst = match lst with [] -> [] | head :: tail -> insert head (sort tail) and insert elt lst = match lst with [] -> [elt] | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail ;; val sort : 'a list -> 'a list = <fun> val insert : 'a -> 'a list -> 'a list = <fun> # sort l;; - : string list = ["a"; "etc."; "is"; "tale"; "told"]
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 OCaml: they operate between any two values of the same type. This makes sort itself polymorphic over all list types.
# sort [6;2;5;3];; - : int list = [2; 3; 5; 6] # sort [3.14; 2.718];; - : float list = [2.718; 3.14]
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 OCaml to modify in-place a list once it is built: we say that lists are immutable data structures. Most OCaml data structures are immutable, but a few (most notably arrays) are mutable, meaning that they can be modified in-place at any time.
OCaml 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:
# let deriv f dx = function x -> (f(x +. dx) -. f(x)) /. dx;; val deriv : (float -> float) -> float -> float -> float = <fun> # let sin' = deriv sin 1e-6;; val sin' : float -> float = <fun> # sin' pi;; - : float = -1.00000000013961143
Even function composition is definable:
# let compose f g = function x -> f(g(x));; val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun> # let cos2 = compose square cos;; val cos2 : float -> float = <fun>
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 OCaml library provides a List.map functional that applies a given function to each element of a list, and returns the list of the results:
# List.map (function n -> n * 2 + 1) [0;1;2;3;4];; - : int list = [1; 3; 5; 7; 9]
This functional, along with a number of other list and array functionals, is predefined because it is often useful, but there is nothing magic with it: it can easily be defined as follows.
# let rec map f l = match l with [] -> [] | hd :: tl -> f hd :: map f tl;; val map : ('a -> 'b) -> 'a list -> 'b list = <fun>
User-defined data structures include records and variants. Both are defined with the type declaration. Here, we declare a record type to represent rational numbers.
# type ratio = {num: int; denom: int};; type ratio = { num : int; denom : int; } # let add_ratio r1 r2 = {num = r1.num * r2.denom + r2.num * r1.denom; denom = r1.denom * r2.denom};; val add_ratio : ratio -> ratio -> ratio = <fun> # add_ratio {num=1; denom=3} {num=2; denom=5};; - : ratio = {num = 11; denom = 15}
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):
# type number = Int of int | Float of float | Error;; type number = Int of int | Float of float | Error
This declaration expresses that a value of type number is either an integer, a floating-point number, or the constant Error representing the result of an invalid operation (e.g. a division by zero).
Enumerated types are a special case of variant types, where all alternatives are constants:
# type sign = Positive | Negative;; type sign = Positive | Negative # let sign_int n = if n >= 0 then Positive else Negative;; val sign_int : int -> sign = <fun>
To define arithmetic operations for the number type, we use pattern-matching on the two numbers involved:
# let add_num n1 n2 = match (n1, n2) with (Int i1, Int i2) -> (* Check for overflow of integer addition *) if sign_int i1 = sign_int i2 && sign_int(i1 + i2) <> sign_int i1 then Float(float i1 +. float i2) else Int(i1 + i2) | (Int i1, Float f2) -> Float(float i1 +. f2) | (Float f1, Int i2) -> Float(f1 +. float i2) | (Float f1, Float f2) -> Float(f1 +. f2) | (Error, _) -> Error | (_, Error) -> Error;; val add_num : number -> number -> number = <fun> # add_num (Int 123) (Float 3.14159);; - : number = Float 126.14159
The most common usage of variant types is to describe recursive data structures. Consider for example the type of binary trees:
# type 'a btree = Empty | Node of 'a * 'a btree * 'a btree;; type 'a btree = Empty | Node of 'a * 'a btree * 'a btree
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):
# let rec member x btree = match btree with Empty -> false | Node(y, left, right) -> if x = y then true else if x < y then member x left else member x right;; val member : 'a -> 'a btree -> bool = <fun> # let rec insert x btree = match btree with Empty -> Node(x, Empty, Empty) | Node(y, left, right) -> if x <= y then Node(y, insert x left, right) else Node(y, left, insert x right);; val insert : 'a -> 'a btree -> 'a btree = <fun>
Though all examples so far were written in purely applicative style, OCaml 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.
# let add_vect v1 v2 = let len = min (Array.length v1) (Array.length v2) in let res = Array.create len 0.0 in for i = 0 to len - 1 do res.(i) <- v1.(i) +. v2.(i) done; res;; val add_vect : float array -> float array -> float array = <fun> # add_vect [| 1.0; 2.0 |] [| 3.0; 4.0 |];; - : float array = [|4.; 6.|]
Record fields can also be modified by assignment, provided they are declared mutable in the definition of the record type:
# type mutable_point = { mutable x: float; mutable y: float };; type mutable_point = { mutable x : float; mutable y : float; } # let translate p dx dy = p.x <- p.x +. dx; p.y <- p.y +. dy;; val translate : mutable_point -> float -> float -> unit = <fun> # let mypoint = { x = 0.0; y = 0.0 };; val mypoint : mutable_point = {x = 0.; y = 0.} # translate mypoint 1.0 2.0;; - : unit = () # mypoint;; - : mutable_point = {x = 1.; y = 2.}
OCaml 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:
# let insertion_sort a = for i = 1 to Array.length a - 1 do let val_i = a.(i) in let j = ref i in while !j > 0 && val_i < a.(!j - 1) do a.(!j) <- a.(!j - 1); j := !j - 1 done; a.(!j) <- val_i done;; val insertion_sort : 'a array -> unit = <fun>
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:
# let current_rand = ref 0;; val current_rand : int ref = {contents = 0} # let random () = current_rand := !current_rand * 25713 + 1345; !current_rand;; val random : unit -> int = <fun>
Again, there is nothing magical with references: they are implemented as a single-field mutable record, as follows.
# type 'a ref = { mutable contents: 'a };; type 'a ref = { mutable contents : 'a; } # let (!) r = r.contents;; val ( ! ) : 'a ref -> 'a = <fun> # let (:=) r newval = r.contents <- newval;; val ( := ) : 'a ref -> 'a -> unit = <fun>
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.
# type idref = { mutable id: 'a. 'a -> 'a };; type idref = { mutable id : 'a. 'a -> 'a; } # let r = {id = fun x -> x};; val r : idref = {id = <fun>} # let g s = (s.id 1, s.id true);; val g : idref -> int * bool = <fun> # r.id <- (fun x -> print_string "called id\n"; x);; - : unit = () # g r;; called id called id - : int * bool = (1, true)
OCaml 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.
# exception Empty_list;; exception Empty_list # let head l = match l with [] -> raise Empty_list | hd :: tl -> hd;; val head : 'a list -> 'a = <fun> # head [1;2];; - : int = 1 # head [];; Exception: Empty_list.
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:
# List.assoc 1 [(0, "zero"); (1, "one")];; - : string = "one" # List.assoc 2 [(0, "zero"); (1, "one")];; Exception: Not_found.
Exceptions can be trapped with the try…with construct:
# let name_of_binary_digit digit = try List.assoc digit [0, "zero"; 1, "one"] with Not_found -> "not a binary digit";; val name_of_binary_digit : int -> string = <fun> # name_of_binary_digit 0;; - : string = "zero" # name_of_binary_digit (-1);; - : string = "not a binary digit"
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:
# let temporarily_set_reference ref newval funct = let oldval = !ref in try ref := newval; let res = funct () in ref := oldval; res with x -> ref := oldval; raise x;; val temporarily_set_reference : 'a ref -> 'a -> (unit -> 'b) -> 'b = <fun>
We finish this introduction with a more complete example representative of the use of OCaml for symbolic processing: formal manipulations of arithmetic expressions containing variables. The following variant type describes the expressions we shall manipulate:
# type expression = Const of float | Var of string | Sum of expression * expression (* e1 + e2 *) | Diff of expression * expression (* e1 - e2 *) | Prod of expression * expression (* e1 * e2 *) | Quot of expression * expression (* e1 / e2 *) ;; type expression = Const of float | Var of string | Sum of expression * expression | Diff of expression * expression | Prod of expression * expression | Quot of expression * expression
We first define a function to evaluate an expression given an environment that maps variable names to their values. For simplicity, the environment is represented as an association list.
# exception Unbound_variable of string;; exception Unbound_variable of string # let rec eval env exp = match exp with Const c -> c | Var v -> (try List.assoc v env with Not_found -> raise(Unbound_variable v)) | Sum(f, g) -> eval env f +. eval env g | Diff(f, g) -> eval env f -. eval env g | Prod(f, g) -> eval env f *. eval env g | Quot(f, g) -> eval env f /. eval env g;; val eval : (string * float) list -> expression -> float = <fun> # eval [("x", 1.0); ("y", 3.14)] (Prod(Sum(Var "x", Const 2.0), Var "y"));; - : float = 9.42
Now for a real symbolic processing, we define the derivative of an expression with respect to a variable dv:
# let rec deriv exp dv = match exp with Const c -> Const 0.0 | Var v -> if v = dv then Const 1.0 else Const 0.0 | Sum(f, g) -> Sum(deriv f dv, deriv g dv) | Diff(f, g) -> Diff(deriv f dv, deriv g dv) | Prod(f, g) -> Sum(Prod(f, deriv g dv), Prod(deriv f dv, g)) | Quot(f, g) -> Quot(Diff(Prod(deriv f dv, g), Prod(f, deriv g dv)), Prod(g, g)) ;; val deriv : expression -> string -> expression = <fun> # deriv (Quot(Const 1.0, Var "x")) "x";; - : expression = Quot (Diff (Prod (Const 0., Var "x"), Prod (Const 1., Const 1.)), Prod (Var "x", Var "x"))
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.
# let print_expr exp = (* Local function definitions *) let open_paren prec op_prec = if prec > op_prec then print_string "(" in let close_paren prec op_prec = if prec > op_prec then print_string ")" in let rec print prec exp = (* prec is the current precedence *) match exp with Const c -> print_float c | Var v -> print_string v | Sum(f, g) -> open_paren prec 0; print 0 f; print_string " + "; print 0 g; close_paren prec 0 | Diff(f, g) -> open_paren prec 0; print 0 f; print_string " - "; print 1 g; close_paren prec 0 | Prod(f, g) -> open_paren prec 2; print 2 f; print_string " * "; print 2 g; close_paren prec 2 | Quot(f, g) -> open_paren prec 2; print 2 f; print_string " / "; print 3 g; close_paren prec 2 in print 0 exp;; val print_expr : expression -> unit = <fun> # let e = Sum(Prod(Const 2.0, Var "x"), Const 1.0);; val e : expression = Sum (Prod (Const 2., Var "x"), Const 1.) # print_expr e; print_newline();; 2. * x + 1. - : unit = () # print_expr (deriv e "x"); print_newline();; 2. * 1. + 0. * x + 0. - : unit = ()
Parsing (transforming concrete syntax into abstract syntax) is usually more delicate. OCaml offers several tools to help write parsers: on the one hand, OCaml 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 directives below.
# #load "dynlink.cma";; #load "camlp4o.cma";; Camlp4 Parsing version 4.00.0+dev19_2012-06-01 # open Genlex;; let lexer = make_lexer ["("; ")"; "+"; "-"; "*"; "/"];; val lexer : char Stream.t -> Genlex.token Stream.t = <fun>
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.
# let token_stream = lexer(Stream.of_string "1.0 +x");; val token_stream : Genlex.token Stream.t = <abstr> # Stream.next token_stream;; - : Genlex.token = Float 1. # Stream.next token_stream;; - : Genlex.token = Kwd "+" # Stream.next token_stream;; - : Genlex.token = Ident "x"
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.
# let rec parse_expr = parser [< e1 = parse_mult; e = parse_more_adds e1 >] -> e and parse_more_adds e1 = parser [< 'Kwd "+"; e2 = parse_mult; e = parse_more_adds (Sum(e1, e2)) >] -> e | [< 'Kwd "-"; e2 = parse_mult; e = parse_more_adds (Diff(e1, e2)) >] -> e | [< >] -> e1 and parse_mult = parser [< e1 = parse_simple; e = parse_more_mults e1 >] -> e and parse_more_mults e1 = parser [< 'Kwd "*"; e2 = parse_simple; e = parse_more_mults (Prod(e1, e2)) >] -> e | [< 'Kwd "/"; e2 = parse_simple; e = parse_more_mults (Quot(e1, e2)) >] -> e | [< >] -> e1 and parse_simple = parser [< 'Ident s >] -> Var s | [< 'Int i >] -> Const(float i) | [< 'Float f >] -> Const f | [< 'Kwd "("; e = parse_expr; 'Kwd ")" >] -> e;; val parse_expr : Genlex.token Stream.t -> expression = <fun> val parse_more_adds : expression -> Genlex.token Stream.t -> expression = <fun> val parse_mult : Genlex.token Stream.t -> expression = <fun> val parse_more_mults : expression -> Genlex.token Stream.t -> expression = <fun> val parse_simple : Genlex.token Stream.t -> expression = <fun> # let parse_expression = parser [< e = parse_expr; _ = Stream.empty >] -> e;; val parse_expression : Genlex.token Stream.t -> expression = <fun>
Composing the lexer and parser, we finally obtain a function to read an expression from a character string:
# let read_expression s = parse_expression(lexer(Stream.of_string s));; val read_expression : string -> expression = <fun> # read_expression "2*(x+y)";; - : expression = Prod (Const 2., Sum (Var "x", Var "y"))
A small puzzle: why do we get different results in the following two examples?
# read_expression "x - 1";; - : expression = Diff (Var "x", Const 1.) # read_expression "x-1";; Exception: Stream.Error "".
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. OCaml code can also be compiled separately and executed non-interactively using the batch compilers ocamlc and 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:
(* File fib.ml *) let rec fib n = if n < 2 then 1 else fib(n-1) + fib(n-2);; let main () = let arg = int_of_string Sys.argv.(1) in print_int(fib arg); print_newline(); exit 0;; main ();;
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:
$ ocamlc -o fib fib.ml $ ./fib 10 89 $ ./fib 20 10946
More complex standalone OCaml programs are typically composed of multiple source files, and can link with precompiled libraries. Chapters 8 and 11 explain how to use the batch compilers ocamlc and ocamlopt. Recompilation of multi-file OCaml projects can be automated using the ocamlbuild compilation manager, documented in chapter 18.
This chapter introduces the module system of OCaml.
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:
# module PrioQueue = struct type priority = int type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue let empty = Empty let rec insert queue prio elt = match queue with Empty -> Node(prio, elt, Empty, Empty) | Node(p, e, left, right) -> if prio <= p then Node(prio, elt, insert right p e, left) else Node(p, e, insert right prio elt, left) exception Queue_is_empty let rec remove_top = function Empty -> raise Queue_is_empty | Node(prio, elt, left, Empty) -> left | Node(prio, elt, Empty, right) -> right | Node(prio, elt, (Node(lprio, lelt, _, _) as left), (Node(rprio, relt, _, _) as right)) -> if lprio <= rprio then Node(lprio, lelt, remove_top left, right) else Node(rprio, relt, left, remove_top right) let extract = function Empty -> raise Queue_is_empty | Node(prio, elt, _, _) as queue -> (prio, elt, remove_top queue) end;; module PrioQueue : sig type priority = int type 'a queue = Empty | Node of priority * 'a * 'a queue * 'a queue val empty : 'a queue val insert : 'a queue -> priority -> 'a -> 'a queue exception Queue_is_empty val remove_top : 'a queue -> 'a queue val extract : 'a queue -> priority * 'a * 'a queue end
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 is the function insert defined inside the structure PrioQueue and PrioQueue.queue is the type queue defined in PrioQueue.
# PrioQueue.insert PrioQueue.empty 1 "hello";; - : string PrioQueue.queue = PrioQueue.Node (1, "hello", PrioQueue.Empty, PrioQueue.Empty)
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).
# module type PRIOQUEUE = sig type priority = int (* still concrete *) type 'a queue (* now abstract *) val empty : 'a queue val insert : 'a queue -> int -> 'a -> 'a queue val extract : 'a queue -> int * 'a * 'a queue exception Queue_is_empty end;; module type PRIOQUEUE = sig type priority = int type 'a queue val empty : 'a queue val insert : 'a queue -> int -> 'a -> 'a queue val extract : 'a queue -> int * 'a * 'a queue exception Queue_is_empty end
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:
# module AbstractPrioQueue = (PrioQueue : PRIOQUEUE);; module AbstractPrioQueue : PRIOQUEUE # AbstractPrioQueue.remove_top;; Error: Unbound value AbstractPrioQueue.remove_top # AbstractPrioQueue.insert AbstractPrioQueue.empty 1 "hello";; - : string AbstractPrioQueue.queue = <abstr>
The restriction can also be performed during the definition of the structure, as in
module PrioQueue = (struct ... end : PRIOQUEUE);;
An alternate syntax is provided for the above:
module PrioQueue : PRIOQUEUE = struct ... end;;
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):
# type comparison = Less | Equal | Greater;; type comparison = Less | Equal | Greater # module type ORDERED_TYPE = sig type t val compare: t -> t -> comparison end;; module type ORDERED_TYPE = sig type t val compare : t -> t -> comparison end # module Set = functor (Elt: ORDERED_TYPE) -> struct type element = Elt.t type set = element list let empty = [] let rec add x s = match s with [] -> [x] | hd::tl -> match Elt.compare x hd with Equal -> s (* x is already in s *) | Less -> x :: s (* x is smaller than all elements of s *) | Greater -> hd :: add x tl let rec member x s = match s with [] -> false | hd::tl -> match Elt.compare x hd with Equal -> true (* x belongs to s *) | Less -> false (* x is smaller than all elements of s *) | Greater -> member x tl end;; module Set : functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t type set = element list val empty : 'a list val add : Elt.t -> Elt.t list -> Elt.t list val member : Elt.t -> Elt.t list -> bool end
By applying the Set functor to a structure implementing an ordered type, we obtain set operations for this type:
# module OrderedString = struct type t = string let compare x y = if x = y then Equal else if x < y then Less else Greater end;; module OrderedString : sig type t = string val compare : 'a -> 'a -> comparison end # module StringSet = Set(OrderedString);; module StringSet : sig type element = OrderedString.t type set = element list val empty : 'a list val add : OrderedString.t -> OrderedString.t list -> OrderedString.t list val member : OrderedString.t -> OrderedString.t list -> bool end # StringSet.member "bar" (StringSet.add "foo" StringSet.empty);; - : bool = false
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:
# module type SETFUNCTOR = functor (Elt: ORDERED_TYPE) -> sig type element = Elt.t (* concrete *) type set (* abstract *) val empty : set val add : element -> set -> set val member : element -> set -> bool end;; module type SETFUNCTOR = functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t type set val empty : set val add : element -> set -> set val member : element -> set -> bool end # module AbstractSet = (Set : SETFUNCTOR);; module AbstractSet : SETFUNCTOR # module AbstractStringSet = AbstractSet(OrderedString);; module AbstractStringSet : sig type element = OrderedString.t type set = AbstractSet(OrderedString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end # AbstractStringSet.add "gee" AbstractStringSet.empty;; - : AbstractStringSet.set = <abstr>
In an attempt to write the type constraint above more elegantly, one may wish to name the signature of the structure returned by the functor, then use that signature in the constraint:
# module type SET = sig type element type set val empty : set val add : element -> set -> set val member : element -> set -> bool end;; module type SET = sig type element type set val empty : set val add : element -> set -> set val member : element -> set -> bool end # module WrongSet = (Set : functor(Elt: ORDERED_TYPE) -> SET);; module WrongSet : functor (Elt : ORDERED_TYPE) -> SET # module WrongStringSet = WrongSet(OrderedString);; module WrongStringSet : sig type element = WrongSet(OrderedString).element type set = WrongSet(OrderedString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end # WrongStringSet.add "gee" WrongStringSet.empty;; Error: This expression has type string but an expression was expected of type WrongStringSet.element = WrongSet(OrderedString).element
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, OCaml provides a with type construct over signatures that allows enriching a signature with extra type equalities:
# module AbstractSet2 = (Set : functor(Elt: ORDERED_TYPE) -> (SET with type element = Elt.t));; module AbstractSet2 : functor (Elt : ORDERED_TYPE) -> sig type element = Elt.t type set val empty : set val add : element -> set -> set val member : element -> set -> bool end
As in the case of simple structures, an alternate syntax is provided for defining functors and restricting their result:
module AbstractSet2(Elt: ORDERED_TYPE) : (SET with type element = Elt.t) = struct ... end;;
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.
# module NoCaseString = struct type t = string let compare s1 s2 = OrderedString.compare (String.lowercase s1) (String.lowercase s2) end;; module NoCaseString : sig type t = string val compare : string -> string -> comparison end # module NoCaseStringSet = AbstractSet(NoCaseString);; module NoCaseStringSet : sig type element = NoCaseString.t type set = AbstractSet(NoCaseString).set val empty : set val add : element -> set -> set val member : element -> set -> bool end # NoCaseStringSet.add "FOO" AbstractStringSet.empty;; Error: This expression has type AbstractStringSet.set = AbstractSet(OrderedString).set but an expression was expected of type NoCaseStringSet.set = AbstractSet(NoCaseString).set
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), they 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 OCaml, 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:
These two files together define a structure named A as if the following definition was entered at top-level:
module A: sig (* contents of file A.mli *) end = struct (* contents of file A.ml *) end;;
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:
$ ocamlc -c Aux.mli # produces aux.cmi $ ocamlc -c Aux.ml # produces aux.cmo $ ocamlc -c Main.mli # produces main.cmi $ ocamlc -c Main.ml # produces main.cmo $ ocamlc -o theprogram Aux.cmo Main.cmo
The program behaves exactly as if the following phrases were entered at top-level:
module Aux: sig (* contents of Aux.mli *) end = struct (* contents of Aux.ml *) end;; module Main: sig (* contents of Main.mli *) end = struct (* contents of Main.ml *) end;;
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.
(Chapter written by Jérôme Vouillon, Didier Rémy and Jacques Garrigue)
This chapter gives an overview of the object-oriented features of OCaml. Note that the relation between object, class and type in OCaml is very different from that in mainstream object-oriented languages like Java or C++, so that you should not assume that similar keywords mean the same thing.
3.1 Classes and objects
3.2 Immediate objects
3.3 Reference to self
3.4 Initializers
3.5 Virtual methods
3.6 Private methods
3.7 Class interfaces
3.8 Inheritance
3.9 Multiple inheritance
3.10 Parameterized classes
3.11 Polymorphic methods
3.12 Using coercions
3.13 Functional objects
3.14 Cloning objects
3.15 Recursive classes
3.16 Binary methods
3.17 Friends
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.
# class point = object val mutable x = 0 method get_x = x method move d = x <- x + d end;; class point : object val mutable x : int method get_x : int method move : int -> unit end
We now create a new point p, instance of the point class.
# let p = new point;; val p : point = <obj>
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.
We now invoke some methods to p:
# p#get_x;; - : int = 0 # p#move 3;; - : unit = () # p#get_x;; - : int = 3
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.
# let x0 = ref 0;; val x0 : int ref = {contents = 0} # class point = object val mutable x = incr x0; !x0 method get_x = x method move d = x <- x + d end;; class point : object val mutable x : int method get_x : int method move : int -> unit end # new point#get_x;; - : int = 1 # new point#get_x;; - : int = 2
The class point can also be abstracted over the initial values of the x coordinate.
# class point = fun x_init -> object val mutable x = x_init method get_x = x method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_x : int method move : int -> unit end
Like in function definitions, the definition above can be abbreviated as:
# class point x_init = object val mutable x = x_init method get_x = x method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_x : int method move : int -> unit end
An instance of the class point is now a function that expects an initial parameter to create a point object:
# new point;; - : int -> point = <fun> # let p = new point 7;; val p : point = <obj>
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.
# class point x_init = object val mutable x = x_init method get_x = x method get_offset = x - x_init method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end
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:
# class adjusted_point x_init = let origin = (x_init / 10) * 10 in object val mutable x = origin method get_x = x method get_offset = x - origin method move d = x <- x + d end;; class adjusted_point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end
(One could also raise an exception if the x_init coordinate is not on the grid.) In fact, the same effect could here be obtained by calling the definition of class point with the value of the origin.
# class adjusted_point x_init = point ((x_init / 10) * 10);; class adjusted_point : int -> point
An alternate solution would have been to define the adjustment in a special allocation function:
# let new_adjusted_point x_init = new point ((x_init / 10) * 10);; val new_adjusted_point : int -> point = <fun>
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.
# let p = object val mutable x = 0 method get_x = x method move d = x <- x + d end;; val p : < get_x : int; move : int -> unit > = <obj> # p#get_x;; - : int = 0 # p#move 3;; - : unit = () # p#get_x;; - : int = 3
Unlike classes, which cannot be defined inside an expression, immediate objects can appear anywhere, using variables from their environment.
# let minmax x y = if x < y then object method min = x method max = y end else object method min = y method max = x end;; val minmax : 'a -> 'a -> < max : 'a; min : 'a > = <fun>
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.)
# class printable_point x_init = object (s) val mutable x = x_init method get_x = x method move d = x <- x + d method print = print_int s#get_x end;; class printable_point : int -> object val mutable x : int method get_x : int method move : int -> unit method print : unit end # let p = new printable_point 7;; val p : printable_point = <obj> # p#print;; 7- : unit = ()
Dynamically, the variable s is bound at the invocation of a method. In particular, when the class printable_point is inherited, the variable s will be correctly bound to the object of the subclass.
A common problem with self is that, as its type may be extended in subclasses, you cannot fix it in advance. Here is a simple example.
# let ints = ref [];; val ints : '_a list ref = {contents = []} # class my_int = object (self) method n = 1 method register = ints := self :: !ints end;; Error: This expression has type < n : int; register : 'b; .. > as 'a but an expression was expected of type 'a This instance of < n : int; register : 'b; .. > is ambiguous: it would escape the scope of its equation
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 through inheritance. 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 my_int = object (self) method n = 1 method register = ints := self :: !ints end;; val my_int : < n : int; register : unit > = <obj>
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, it can access self and the instance variables.
# class printable_point x_init = let origin = (x_init / 10) * 10 in object (self) val mutable x = origin method get_x = x method move d = x <- x + d method print = print_int self#get_x initializer print_string "new point at "; self#print; print_newline() end;; class printable_point : int -> object val mutable x : int method get_x : int method move : int -> unit method print : unit end # let p = new printable_point 17;; new point at 10 val p : printable_point = <obj>
Initializers cannot be overridden. On the contrary, all initializers are evaluated sequentially. Initializers are particularly useful to enforce invariants. Another example can be seen in section 5.1.
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.)
# class virtual abstract_point x_init = object (self) method virtual get_x : int method get_offset = self#get_x - x_init method virtual move : int -> unit end;; class virtual abstract_point : int -> object method get_offset : int method virtual get_x : int method virtual move : int -> unit end # class point x_init = object inherit abstract_point x_init val mutable x = x_init method get_x = x method move d = x <- x + d end;; class point : int -> object val mutable x : int method get_offset : int method get_x : int method move : int -> unit end
Instance variables can also be declared as virtual, with the same effect as with methods.
# class virtual abstract_point2 = object val mutable virtual x : int method move d = x <- x + d end;; class virtual abstract_point2 : object val mutable virtual x : int method move : int -> unit end # class point2 x_init = object inherit abstract_point2 val mutable x = x_init method get_offset = x - x_init end;; class point2 : int -> object val mutable x : int method get_offset : int method move : int -> unit end
Private methods are methods that do not appear in object interfaces. They can only be invoked from other methods of the same object.
# class restricted_point x_init = object (self) val mutable x = x_init method get_x = x method private move d = x <- x + d method bump = self#move 1 end;; class restricted_point : int -> object val mutable x : int method bump : unit method get_x : int method private move : int -> unit end # let p = new restricted_point 0;; val p : restricted_point = <obj> # p#move 10;; Error: This expression has type restricted_point It has no method move # p#bump;; - : unit = ()
Note that this is not the same thing as private and protected methods in Java or C++, which can be called from other objects of the same class. This is a direct consequence of the independence between types and classes in OCaml: two unrelated classes may produce objects of the same type, and there is no way at the type level to ensure that an object comes from a specific class. However a possible encoding of friend methods is given in section 3.17.
Private methods are inherited (they are by default visible in subclasses), unless they are hidden by signature matching, as described below.
Private methods can be made public in a subclass.
# class point_again x = object (self) inherit restricted_point x method virtual move : _ end;; class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end
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.
An alternative definition is
# class point_again x = object (self : < move : _; ..> ) inherit restricted_point x end;; class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end
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:
# class point_again x = object inherit restricted_point x as super method move = super#move end;; class point_again : int -> object val mutable x : int method bump : unit method get_x : int method move : int -> unit end
Of course, private methods can also be virtual. Then, the keywords must appear in this order method private virtual.
Class interfaces are inferred from class definitions. They may also be defined directly and used to restrict the type of a class. Like class declarations, they also define a new type abbreviation.
# class type restricted_point_type = object method get_x : int method bump : unit end;; class type restricted_point_type = object method bump : unit method get_x : int end # fun (x : restricted_point_type) -> x;; - : restricted_point_type -> restricted_point_type = <fun>
In addition to program documentation, class interfaces can be used to constrain the type of a class. Both concrete instance variables and concrete private methods can be hidden by a class type constraint. Public methods and virtual members, however, cannot.
# class restricted_point' x = (restricted_point x : restricted_point_type);; class restricted_point' : int -> restricted_point_type
Or, equivalently:
# class restricted_point' = (restricted_point : int -> restricted_point_type);; class restricted_point' : int -> restricted_point_type
The interface of a class can also be specified in a module signature, and used to restrict the inferred signature of a module.
# module type POINT = sig class restricted_point' : int -> object method get_x : int method bump : unit end end;; module type POINT = sig class restricted_point' : int -> object method bump : unit method get_x : int end end # module Point : POINT = struct class restricted_point' = restricted_point end;; module Point : POINT
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.
# class colored_point x (c : string) = object inherit point x val c = c method color = c end;; class colored_point : int -> string -> object val c : string val mutable x : int method color : string method get_offset : int method get_x : int method move : int -> unit end # let p' = new colored_point 5 "red";; val p' : colored_point = <obj> # p'#get_x, p'#color;; - : int * string = (5, "red")
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.
# let get_succ_x p = p#get_x + 1;; val get_succ_x : < get_x : int; .. > -> int = <fun> # get_succ_x p + get_succ_x p';; - : int = 8
Methods need not be declared previously, as shown by the example:
# let set_x p = p#set_x;; val set_x : < set_x : 'a; .. > -> 'a = <fun> # let incr p = set_x p (get_succ_x p);; val incr : < get_x : int; set_x : int -> 'a; .. > -> 'a = <fun>
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.
# class printable_colored_point y c = object (self) val c = c method color = c inherit printable_point y as super method print = print_string "("; super#print; print_string ", "; print_string (self#color); print_string ")" end;; class printable_colored_point : int -> string -> object val c : string val mutable x : int method color : string method get_x : int method move : int -> unit method print : unit end # let p' = new printable_colored_point 17 "red";; new point at (10, red) val p' : printable_colored_point = <obj> # p'#print;; (10, red)- : unit = ()
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.
Reference cells can be implemented as objects. The naive definition fails to typecheck:
# class ref x_init = object val mutable x = x_init method get = x method set y = x <- y end;; Error: Some type variables are unbound in this type: class ref : 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end The method get has type 'a where 'a is unbound
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:
# class ref (x_init:int) = object val mutable x = x_init method get = x method set y = x <- y end;; class ref : int -> object val mutable x : int method get : int method set : int -> unit end
Note that since immediate objects do not define a class type, they have no such restriction.
# let new_ref x_init = object val mutable x = x_init method get = x method set y = x <- y end;; val new_ref : 'a -> < get : 'a; set : 'a -> unit > = <fun>
On the other hand, a class for polymorphic references must explicitly list the type parameters in its declaration. Class type parameters are listed between [ and ]. The type parameters must also be bound somewhere in the class body by a type constraint.
# class ['a] ref x_init = object val mutable x = (x_init : 'a) method get = x method set y = x <- y end;; class ['a] ref : 'a -> object val mutable x : 'a method get : 'a method set : 'a -> unit end # let r = new ref 1 in r#set 2; (r#get);; - : int = 2
The type parameter in the declaration may actually be constrained in the body of the class definition. In the class type, the actual value of the type parameter is displayed in the constraint clause.
# class ['a] ref_succ (x_init:'a) = object val mutable x = x_init + 1 method get = x method set y = x <- y end;; class ['a] ref_succ : 'a -> object constraint 'a = int val mutable x : int method get : int method set : int -> unit end
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.
# class ['a] circle (c : 'a) = object val mutable center = c method center = center method set_center c = center <- c method move = (center#move : int -> unit) end;; class ['a] circle : 'a -> object constraint 'a = < move : int -> unit; .. > val mutable center : 'a method center : 'a method move : int -> unit method set_center : 'a -> unit end
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.
# class ['a] circle (c : 'a) = object constraint 'a = #point val mutable center = c method center = center method set_center c = center <- c method move = center#move end;; class ['a] circle : 'a -> object constraint 'a = #point val mutable center : 'a method center : 'a method move : int -> unit method set_center : 'a -> unit end
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 ].
# class ['a] colored_circle c = object constraint 'a = #colored_point inherit ['a] circle c method color = center#color end;; class ['a] colored_circle : 'a -> object constraint 'a = #colored_point val mutable center : 'a method center : 'a method color : string method move : int -> unit method set_center : 'a -> unit end
While parameterized classes may be polymorphic in their contents, they are not enough to allow polymorphism of method use.
A classical example is defining an iterator.
# List.fold_left;; - : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a = <fun> # class ['a] intlist (l : int list) = object method empty = (l = []) method fold f (accu : 'a) = List.fold_left f accu l end;; class ['a] intlist : int list -> object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end
At first look, we seem to have a polymorphic iterator, however this does not work in practice.
# let l = new intlist [1; 2; 3];; val l : '_a intlist = <obj> # l#fold (fun x y -> x+y) 0;; - : int = 6 # l;; - : int intlist = <obj> # l#fold (fun s x -> s ^ string_of_int x ^ " ") "";; Error: This expression has type int but an expression was expected of type string
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: it 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.
# class intlist (l : int list) = object method empty = (l = []) method fold : 'a. ('a -> int -> 'a) -> 'a -> 'a = fun f accu -> List.fold_left f accu l end;; class intlist : int list -> object method empty : bool method fold : ('a -> int -> 'a) -> 'a -> 'a end # let l = new intlist [1; 2; 3];; val l : intlist = <obj> # l#fold (fun x y -> x+y) 0;; - : int = 6 # l#fold (fun s x -> s ^ string_of_int x ^ " ") "";; - : string = "1 2 3 "
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), quantified type variables can be left implicit in class descriptions. Why require types to be explicit? The problem is that (int -> int -> int) -> int -> int would also be a valid type for fold, and it happens to be incompatible with the polymorphic type we gave (automatic instantiation only works for toplevel types variables, not for inner quantifiers, where it becomes an undecidable problem.) So the compiler cannot choose between those two types, and must be helped.
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.
# class intlist_rev l = object inherit intlist l method fold f accu = List.fold_left f accu (List.rev l) end;;
The following idiom separates description and definition.
# class type ['a] iterator = object method fold : ('b -> 'a -> 'b) -> 'b -> 'b end;; class intlist l = object (self : int #iterator) method empty = (l = []) method fold f accu = List.fold_left f accu l end;;
Note here the (self : int #iterator) idiom, which ensures that this object implements the interface iterator.
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.
# let sum lst = lst#fold (fun x y -> x+y) 0;; val sum : < fold : (int -> int -> int) -> int -> 'a; .. > -> 'a = <fun> # sum l;; Error: This expression has type intlist but an expression was expected of type < fold : (int -> int -> int) -> int -> 'a; .. > Types for method fold are incompatible
The workaround is easy: you should put a type constraint on the parameter.
# let sum (lst : _ #iterator) = lst#fold (fun x y -> x+y) 0;; val sum : int #iterator -> int = <fun>
Of course the constraint may also be an explicit method type. Only occurences of quantified variables are required.
# let sum lst = (lst : < fold : 'a. ('a -> _ -> 'a) -> 'a -> 'a; .. >)#fold (+) 0;; val sum : < fold : 'a. ('a -> int -> 'a) -> 'a -> 'a; .. > -> int = <fun>
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.
# class type point0 = object method get_x : int end;; class type point0 = object method get_x : int end # class distance_point x = object inherit point x method distance : 'a. (#point0 as 'a) -> int = fun other -> abs (other#get_x - x) end;; class distance_point : int -> object val mutable x : int method distance : #point0 -> int method get_offset : int method get_x : int method move : int -> unit end # let p = new distance_point 3 in (p#distance (new point 8), p#distance (new colored_point 1 "blue"));; - : int * int = (5, 2)
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.
# class multi_poly = object method m1 : 'a. (< n1 : 'b. 'b -> 'b; .. > as 'a) -> _ = fun o -> o#n1 true, o#n1 "hello" method m2 : 'a 'b. (< n2 : 'b -> bool; .. > as 'a) -> 'b -> _ = fun o x -> o#n2 x end;; class multi_poly : object method m1 : < n1 : 'b. 'b -> 'b; .. > -> bool * string method m2 : < n2 : 'b -> bool; .. > -> 'b -> bool end
In method m1, o must be an object with at least a method n1, itself polymorphic. In method m2, the argument of n2 and x must have the same type, which is quantified at the same level as 'a.
Subtyping is never implicit. There are, however, two ways to perform subtyping. The most general construction is fully explicit: both the domain and the codomain of the type coercion must be given.
We have seen that points and colored points have incompatible types. For instance, they cannot be mixed in the same list. However, a colored point can be coerced to a point, hiding its color method:
# let colored_point_to_point cp = (cp : colored_point :> point);; val colored_point_to_point : colored_point -> point = <fun> # let p = new point 3 and q = new colored_point 4 "blue";; val p : point = <obj> val q : colored_point = <obj> # let l = [p; (colored_point_to_point q)];; val l : point list = [<obj>; <obj>]
An object of type t can be seen as an object of type t' only if t is a subtype of t'. For instance, a point cannot be seen as a colored point.
# (p : point :> colored_point);; Error: Type point = < get_offset : int; get_x : int; move : int -> unit > is not a subtype of colored_point = < color : string; get_offset : int; get_x : int; move : int -> unit >
Indeed, narrowing coercions without runtime checks would be unsafe. Runtime type checks might raise exceptions, and they would require the presence of type information at runtime, which is not the case in the OCaml system. For these reasons, 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 often be omitted. For instance, one can define:
# let to_point cp = (cp :> point);; val to_point : #point -> point = <fun>
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:
# class c0 = object method m = {< >} method n = 0 end;; class c0 : object ('a) method m : 'a method n : int end
The object type c0 is an abbreviation for <m : 'a; n : int> as 'a. Consider now the type declaration:
# class type c1 = object method m : c1 end;; class type c1 = object method m : c1 end
The object type c1 is an abbreviation for the type <m : 'a> as 'a. The coercion from an object of type c0 to an object of type c1 is correct:
# fun (x:c0) -> (x : c0 :> c1);; - : c0 -> c1 = <fun>
However, the domain of the coercion cannot always be omitted. In that case, the solution is to use the explicit form. Sometimes, a change in the class-type definition can also solve the problem
# class type c2 = object ('a) method m : 'a end;; class type c2 = object ('a) method m : 'a end # fun (x:c0) -> (x :> c2);; - : c0 -> c2 = <fun>
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 leaving 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:
# let to_c1 x = (x :> c1);; val to_c1 : < m : #c1; .. > -> c1 = <fun> # let to_c2 x = (x :> c2);; val to_c2 : #c2 -> c2 = <fun>
Note the difference between these two coercions: in the case of to_c2, 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.
# class c = object method m = 1 end and d = object (self) inherit c method n = 2 method as_c = (self :> c) end;; Error: This expression cannot be coerced to type c = < m : int >; it has type < as_c : c; m : int; n : int; .. > but is here used with type c Self type cannot be unified with a closed object type
However, the most common instance of this problem, coercing self to its current class, is detected as a special case by the type checker, and properly typed.
# class c = object (self) method m = (self :> c) end;; class c : object method m : c end
This allows the following idiom, keeping a list of all objects belonging to a class or its subclasses:
# let all_c = ref [];; val all_c : '_a list ref = {contents = []} # class c (m : int) = object (self) method m = m initializer all_c := (self :> c) :: !all_c end;; class c : int -> object method m : int end
This idiom can in turn be used to retrieve an object whose type has been weakened:
# let rec lookup_obj obj = function [] -> raise Not_found | obj' :: l -> if (obj :> < >) = (obj' :> < >) then obj' else lookup_obj obj l ;; val lookup_obj : < .. > -> (< .. > as 'a) list -> 'a = <fun> # let lookup_c obj = lookup_obj obj !all_c;; val lookup_c : < .. > -> < m : int > = <fun>
The type < m : int > we see here is just the expansion of c, due to the use of a reference; we have succeeded in getting back an object of type c.
The previous coercion problem can often be avoided by first
defining the abbreviation, using a class type:
# class type c' = object method m : int end;; class type c' = object method m : int end # class c : c' = object method m = 1 end and d = object (self) inherit c method n = 2 method as_c = (self :> c') end;; class c : c' and d : object method as_c : c' method m : int method n : int end
It is also possible to use a virtual class. Inheriting from this class simultaneously forces all methods of c to have the same type as the methods of c'.
# class virtual c' = object method virtual m : int end;; class virtual c' : object method virtual m : int end # class c = object (self) inherit c' method m = 1 end;; class c : object method m : int end
One could think of defining the type abbreviation directly:
# type c' = <m : int>;;
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 a #-abbreviation carries an implicit anonymous variable .. that cannot be explicitly named. The closer you get to it is:
# type 'a c'_class = 'a constraint 'a = < m : int; .. >;;
with an extra type variable capturing the open object type.
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.
# class functional_point y = object val x = y method get_x = x method move d = {< x = x + d >} end;; class functional_point : int -> object ('a) val x : int method get_x : int method move : int -> 'a end # let p = new functional_point 7;; val p : functional_point = <obj> # p#get_x;; - : int = 7 # (p#move 3)#get_x;; - : int = 10 # p#get_x;; - : int = 7
Note that the type abbreviation functional_point is recursive, which can be seen in the class type of functional_point: the type of self is 'a and 'a appears inside the type of the method move.
The above definition of functional_point is not equivalent to the following:
# class bad_functional_point y = object val x = y method get_x = x method move d = new bad_functional_point (x+d) end;; class bad_functional_point : int -> object val x : int method get_x : int method move : int -> bad_functional_point end
While objects of either class will behave the same, objects of their subclasses will be different. In a subclass of bad_functional_point, the method move will keep returning an object of the parent class. On the contrary, in a subclass of functional_point, 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 is 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.
# let p = new point 5;; val p : point = <obj> # let q = Oo.copy p;; val q : point = <obj> # q#move 7; (p#get_x, q#get_x);; - : int * int = (5, 12)
In fact, Oo.copy p will behave as p#copy assuming that a public method copy with body {< >} has been defined in the class of p.
Objects can be compared using the generic comparison functions = and <>. Two objects are equal if and only if they are physically equal. In particular, an object and its copy are not equal.
# let q = Oo.copy p;; val q : point = <obj> # p = q, p = p;; - : bool * bool = (false, true)
Other generic comparisons 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:
# class copy = object method copy = {< >} end;; class copy : object ('a) method copy : 'a end # class copy = object (self) method copy = Oo.copy self end;; class copy : object ('a) method copy : 'a end
Only the override can be used to actually override fields, and only the Oo.copy primitive can be used externally.
Cloning can also be used to provide facilities for saving and restoring the state of objects.
# class backup = object (self : 'mytype) val mutable copy = None method save = copy <- Some {< copy = None >} method restore = match copy with Some x -> x | None -> self end;; class backup : object ('a) val mutable copy : 'a option method restore : 'a method save : unit end
The above definition will only backup one level. The backup facility can be added to any class by using multiple inheritance.
# class ['a] backup_ref x = object inherit ['a] ref x inherit backup end;; class ['a] backup_ref : 'a -> object ('b) val mutable copy : 'b option val mutable x : 'a method get : 'a method restore : 'b method save : unit method set : 'a -> unit end # let rec get p n = if n = 0 then p # get else get (p # restore) (n-1);; val get : (< get : 'b; restore : 'a; .. > as 'a) -> int -> 'b = <fun> # let p = new backup_ref 0 in p # save; p # set 1; p # save; p # set 2; [get p 0; get p 1; get p 2; get p 3; get p 4];; - : int list = [2; 1; 1; 1; 1]
We can define a variant of backup that retains all copies. (We also add a method clear to manually erase all copies.)
# class backup = object (self : 'mytype) val mutable copy = None method save = copy <- Some {< >} method restore = match copy with Some x -> x | None -> self method clear = copy <- None end;; class backup : object ('a) val mutable copy : 'a option method clear : unit method restore : 'a method save : unit end
# class ['a] backup_ref x = object inherit ['a] ref x inherit backup end;; class ['a] backup_ref : 'a -> object ('b) val mutable copy : 'b option val mutable x : 'a method clear : unit method get : 'a method restore : 'b method save : unit method set : 'a -> unit end # let p = new backup_ref 0 in p # save; p # set 1; p # save; p # set 2; [get p 0; get p 1; get p 2; get p 3; get p 4];; - : int list = [2; 1; 0; 0; 0]
Recursive classes can be used to define objects whose types are mutually recursive.
# class window = object val mutable top_widget = (None : widget option) method top_widget = top_widget end and widget (w : window) = object val window = w method window = window end;; class window : object val mutable top_widget : widget option method top_widget : widget option end and widget : window -> object val window : window method window : window end
Although their types are mutually recursive, the classes widget and window are themselves independent.
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 writing recursive types.
# class virtual comparable = object (_ : 'a) method virtual leq : 'a -> bool end;; class virtual comparable : object ('a) method virtual leq : 'a -> bool end
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. We have to use a type constraint on the class parameter x because the primitive <= is a polymorphic function in OCaml. The inherit clause ensures that the type of objects of this class is an instance of #comparable.
# class money (x : float) = object inherit comparable val repr = x method value = repr method leq p = repr <= p#value end;; class money : float -> object ('a) val repr : float method leq : 'a -> bool method value : float end
Note that the type money 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 a call to method leq on m with an argument that does not have a method value, which would be an error.
Similarly, the type money2 below is not a subtype of type money.
# class money2 x = object inherit money x method times k = {< repr = k *. repr >} end;; class money2 : float -> object ('a) val repr : float method leq : 'a -> bool method times : float -> 'a method value : float end
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.
# let min (x : #comparable) y = if x#leq y then x else y;; val min : (#comparable as 'a) -> 'a -> 'a = <fun>
This function can be applied to objects of type money or money2.
# (min (new money 1.3) (new money 3.1))#value;; - : float = 1.3 # (min (new money2 5.0) (new money2 3.14))#value;; - : float = 3.14
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:
# class money x = object (self : 'a) val repr = x method value = repr method print = print_float repr method times k = {< repr = k *. x >} method leq (p : 'a) = repr <= p#value method plus (p : 'a) = {< repr = x +. p#value >} end;; class money : float -> object ('a) val repr : float method leq : 'a -> bool method plus : 'a -> 'a method print : unit method times : float -> 'a method value : float end
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 soon as some binary method requires access to the representation of objects of the same class (other than self).
# class safe_money x = object (self : 'a) val repr = x method print = print_float repr method times k = {< repr = k *. x >} end;; class safe_money : float -> object ('a) val repr : float method print : unit method times : float -> 'a end
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.
# module type MONEY = sig type t class c : float -> object ('a) val repr : t method value : t method print : unit method times : float -> 'a method leq : 'a -> bool method plus : 'a -> 'a end end;; module Euro : MONEY = struct type t = float class c x = object (self : 'a) val repr = x method value = repr method print = print_float repr method times k = {< repr = k *. x >} method leq (p : 'a) = repr <= p#value method plus (p : 'a) = {< repr = x +. p#value >} end end;;
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 the module.
(Chapter written by Jacques Garrigue)
This chapter gives an overview of the new features in OCaml 3: labels, and polymorphic variants.
If you have a look at modules ending in Labels in the standard library, you will see that function types have annotations you did not have in the functions you defined yourself.
# ListLabels.map;; - : f:('a -> 'b) -> 'a list -> 'b list = <fun> # StringLabels.sub;; - : string -> pos:int -> len:int -> string = <fun>
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 ~.
# let f ~x ~y = x - y;; val f : x:int -> y:int -> int = <fun> # let x = 3 and y = 2 in f ~x ~y;; - : int = 1
When you want to use distinct names for the variable and the label appearing in the type, you can use a naming label of the form ~name:. This also applies when the argument is not a variable.
# let f ~x:x1 ~y:y1 = x1 - y1;; val f : x:int -> y:int -> int = <fun> # f ~x:3 ~y:2;; - : int = 1
Labels obey the same rules as other identifiers in OCaml, 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.
# let f ~x ~y = x - y;; val f : x:int -> y:int -> int = <fun> # f ~y:2 ~x:3;; - : int = 1 # ListLabels.fold_left;; - : f:('a -> 'b -> 'a) -> init:'a -> 'b list -> 'a = <fun> # ListLabels.fold_left [1;2;3] ~init:0 ~f:(+);; - : int = 6 # ListLabels.fold_left ~init:0;; - : f:(int -> 'a -> int) -> 'a list -> int = <fun>
If in a function several arguments bear the same label (or no label), they will not commute among themselves, and order matters. But they can still commute with other arguments.
# let hline ~x:x1 ~x:x2 ~y = (x1, x2, y);; val hline : x:'a -> x:'b -> y:'c -> 'a * 'b * 'c = <fun> # hline ~x:3 ~y:2 ~x:5;; - : int * int * int = (3, 5, 2)
As an exception to the above parameter matching rules, if an application is total (omitting all optional arguments), labels may be omitted. In practice, many applications are total, so that labels can often be omitted.
# f 3 2;; - : int = 1 # ListLabels.map succ [1;2;3];; - : int list = [2; 3; 4]
But beware that functions like ListLabels.fold_left whose result type is a type variable will never be considered as totally applied.
# ListLabels.fold_left (+) 0 [1;2;3];; Error: This expression has type int -> int -> int but an expression was expected of type 'a list
When a function is passed as an argument to an higher-order function, labels must match in both types. Neither adding nor removing labels are allowed.
# let h g = g ~x:3 ~y:2;; val h : (x:int -> y:int -> 'a) -> 'a = <fun> # h f;; - : int = 1 # h (+);; Error: This expression has type int -> int -> int but an expression was expected of type x:int -> y:int -> 'a
Note that when you don’t need an argument, you can still use a wildcard pattern, but you must prefix it with the label.
# h (fun ~x:_ ~y -> y+1);; - : int = 3
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.
# let bump ?(step = 1) x = x + step;; val bump : ?step:int -> int -> int = <fun> # bump 2;; - : int = 3 # bump ~step:3 2;; - : int = 5
A function taking some optional arguments must also take at least one non-optional argument. The criterion for deciding whether an optional argument has been omitted is the non-labeled application of an argument appearing after this optional argument in the function type. Note that if that argument is labeled, you will only be able to eliminate optional arguments through the special case for total applications.
# let test ?(x = 0) ?(y = 0) () ?(z = 0) () = (x, y, z);; val test : ?x:int -> ?y:int -> unit -> ?z:int -> unit -> int * int * int = <fun> # test ();; - : ?z:int -> unit -> int * int * int = <fun> # test ~x:2 () ~z:3 ();; - : int * int * int = (2, 0, 3)
Optional parameters may also commute with non-optional or unlabeled ones, as long as they are applied simultaneously. By nature, optional arguments do not commute with unlabeled arguments applied independently.
# test ~y:2 ~x:3 () ();; - : int * int * int = (3, 2, 0) # test () () ~z:1 ~y:2 ~x:3;; - : int * int * int = (3, 2, 1) # (test () ()) ~z:1;; Error: This expression is not a function; it cannot be applied
Here (test () ()) is already (0,0,0) and cannot be further applied.
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.
# let bump ?step x = match step with | None -> x * 2 | Some y -> x + y ;; val bump : ?step:int -> int -> int = <fun>
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.
# let test2 ?x ?y () = test ?x ?y () ();; val test2 : ?x:int -> ?y:int -> unit -> int * int * int = <fun> # test2 ?x:None;; - : ?y:int -> unit -> int * int * int = <fun>
While they provide an increased comfort for writing function applications, labels and optional arguments have the pitfall that they cannot be inferred as completely as the rest of the language.
You can see it in the following two examples.
# let h' g = g ~y:2 ~x:3;; val h' : (y:int -> x:int -> 'a) -> 'a = <fun> # h' f;; Error: This expression has type x:int -> y:int -> int but an expression was expected of type y:int -> x:int -> 'a # let bump_it bump x = bump ~step:2 x;; val bump_it : (step:int -> 'a -> 'b) -> 'a -> 'b = <fun> # bump_it bump 1;; Error: This expression has type ?step:int -> int -> int but an expression was expected of type step:int -> 'a -> 'b
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.
# let bump_it (bump : ?step:int -> int -> int) x = bump ~step:2 x;; val bump_it : (?step:int -> int -> int) -> int -> int = <fun> # bump_it bump 1;; - : int = 3
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.
# let twice f (x : int) = f(f x);; val twice : (int -> int) -> int -> int = <fun> # twice bump 2;; - : int = 8
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
We explain here the rules we applied when labeling OCaml 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.
ListLabels.map : f:('a -> 'b) -> 'a list -> 'b list UnixLabels.write : file_descr -> buf:string -> pos:int -> len:int -> unit
When there are several objects of same nature and role, they are all left unlabeled.
ListLabels.iter2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> unit
When there is no preferable object, all arguments are labeled.
StringLabels.blit : src:string -> src_pos:int -> dst:string -> dst_pos:int -> len:int -> unit
However, when there is only one argument, it is often left unlabeled.
StringLabels.create : int -> string
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. One 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.
In programs, polymorphic variants work like usual ones. You just have to prefix their names with a backquote character `.
# [`On; `Off];; - : [> `Off | `On ] list = [`On; `Off] # `Number 1;; - : [> `Number of int ] = `Number 1 # let f = function `On -> 1 | `Off -> 0 | `Number n -> n;; val f : [< `Number of int | `Off | `On ] -> int = <fun> # List.map f [`On; `Off];; - : int list = [1; 0]
[>`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 `Number n 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.
# type 'a vlist = [`Nil | `Cons of 'a * 'a vlist];; type 'a vlist = [ `Cons of 'a * 'a vlist | `Nil ] # let rec map f : 'a vlist -> 'b vlist = function | `Nil -> `Nil | `Cons(a, l) -> `Cons(f a, map f l) ;; val map : ('a -> 'b) -> 'a vlist -> 'b vlist = <fun>
Type-checking polymorphic variants is a subtle thing, and some expressions may result in more complex type information.
# let f = function `A -> `C | `B -> `D | x -> x;; val f : ([> `A | `B | `C | `D ] as 'a) -> 'a = <fun> # f `E;; - : [> `A | `B | `C | `D | `E ] = `E
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.
# let f1 = function `A x -> x = 1 | `B -> true | `C -> false let f2 = function `A x -> x = "a" | `B -> true ;; val f1 : [< `A of int | `B | `C ] -> bool = <fun> val f2 : [< `A of string | `B ] -> bool = <fun> # let f x = f1 x && f2 x;; val f : [< `A of string & int | `B ] -> bool = <fun>
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 both int 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.
# type 'a wlist = [`Nil | `Cons of 'a * 'a wlist | `Snoc of 'a wlist * 'a];; type 'a wlist = [ `Cons of 'a * 'a wlist | `Nil | `Snoc of 'a wlist * 'a ] # let wlist_of_vlist l = (l : 'a vlist :> 'a wlist);; val wlist_of_vlist : 'a vlist -> 'a wlist = <fun> # let open_vlist l = (l : 'a vlist :> [> 'a vlist]);; val open_vlist : 'a vlist -> [> 'a vlist ] = <fun> # fun x -> (x :> [`A|`B|`C]);; - : [< `A | `B | `C ] -> [ `A | `B | `C ] = <fun>
You may also selectively coerce values through pattern matching.
# let split_cases = function | `Nil | `Cons _ as x -> `A x | `Snoc _ as x -> `B x ;; val split_cases : [< `Cons of 'a | `Nil | `Snoc of 'b ] -> [> `A of [> `Cons of 'a | `Nil ] | `B of [> `Snoc of 'b ] ] = <fun>
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.
# let num x = `Num x let eval1 eval (`Num x) = x let rec eval x = eval1 eval x ;; val num : 'a -> [> `Num of 'a ] = <fun> val eval1 : 'a -> [< `Num of 'b ] -> 'b = <fun> val eval : [< `Num of 'a ] -> 'a = <fun> # let plus x y = `Plus(x,y) let eval2 eval = function | `Plus(x,y) -> eval x + eval y | `Num _ as x -> eval1 eval x let rec eval x = eval2 eval x ;; val plus : 'a -> 'b -> [> `Plus of 'a * 'b ] = <fun> val eval2 : ('a -> int) -> [< `Num of int | `Plus of 'a * 'a ] -> int = <fun> val eval : ([< `Num of int | `Plus of 'a * 'a ] as 'a) -> int = <fun>
To make this even more comfortable, 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)).
Such abbreviations may be used alone,
# let f = function | #myvariant -> "myvariant" | `Tag3 -> "Tag3";; val f : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>
or combined with with aliases.
# let g1 = function `Tag1 _ -> "Tag1" | `Tag2 _ -> "Tag2";; val g1 : [< `Tag1 of 'a | `Tag2 of 'b ] -> string = <fun> # let g = function | #myvariant as x -> g1 x | `Tag3 -> "Tag3";; val g : [< `Tag1 of int | `Tag2 of bool | `Tag3 ] -> string = <fun>
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 twofold. 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 some 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.
# type abc = [`A | `B | `C] ;; type abc = [ `A | `B | `C ] # let f = function | `As -> "A" | #abc -> "other" ;; val f : [< `A | `As | `B | `C ] -> string = <fun> # let f : abc -> string = f ;; val f : abc -> string = <fun>
You can avoid such risks by annotating the definition itself.
# let f : abc -> string = function | `As -> "A" | #abc -> "other" ;; Warning 11: this match case is unused. val f : abc -> string = <fun>
(Chapter written by Didier Rémy)
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.)
# let euro = new Euro.c;; val euro : float -> Euro.c = <fun> # let zero = euro 0.;; val zero : Euro.c = <obj> # let neg x = x#times (-1.);; val neg : < times : float -> 'a; .. > -> 'a = <fun> # class account = object val mutable balance = zero method balance = balance method deposit x = balance <- balance # plus x method withdraw x = if x#leq balance then (balance <- balance # plus (neg x); x) else zero end;; class account : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method withdraw : Euro.c -> Euro.c end # let c = new account in c # deposit (euro 100.); c # withdraw (euro 50.);; - : Euro.c = <obj>
We now refine this definition with a method to compute interest.
# class account_with_interests = object (self) inherit account method private interest = self # deposit (self # balance # times 0.03) end;; class account_with_interests : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method private interest : unit method withdraw : Euro.c -> Euro.c end
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:
# class safe_account = object inherit account method deposit x = if zero#leq x then balance <- balance#plus x end;; class safe_account : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method withdraw : Euro.c -> Euro.c end
However, the bug might be fixed more safely by the following definition:
# class safe_account = object inherit account as unsafe method deposit x = if zero#leq x then unsafe # deposit x else raise (Invalid_argument "deposit") end;; class safe_account : object val mutable balance : Euro.c method balance : Euro.c method deposit : Euro.c -> unit method withdraw : Euro.c -> Euro.c end
In particular, this does not require the knowledge of the implementation of the method deposit.
To keep trace of operations, we extend the class with a mutable field history and a private method trace to add an operation in the log. Then each method to be traced is redefined.
# type 'a operation = Deposit of 'a | Retrieval of 'a;; type 'a operation = Deposit of 'a | Retrieval of 'a # class account_with_history = object (self) inherit safe_account as super val mutable history = [] method private trace x = history <- x :: history method deposit x = self#trace (Deposit x); super#deposit x method withdraw x = self#trace (Retrieval x); super#withdraw x method history = List.rev history end;; class account_with_history : object val mutable balance : Euro.c val mutable history : Euro.c operation list method balance : Euro.c method deposit : Euro.c -> unit method history : Euro.c operation list method private trace : Euro.c operation -> unit method withdraw : Euro.c -> Euro.c end
One may wish to open an account and simultaneously deposit some initial amount. Although the initial implementation did not address this requirement, it can be achieved by using an initializer.
# class account_with_deposit x = object inherit account_with_history initializer balance <- x end;; class account_with_deposit : Euro.c -> object val mutable balance : Euro.c val mutable history : Euro.c operation list method balance : Euro.c method deposit : Euro.c -> unit method history : Euro.c operation list method private trace : Euro.c operation -> unit method withdraw : Euro.c -> Euro.c end
A better alternative is:
# class account_with_deposit x = object (self) inherit account_with_history initializer self#deposit x end;; class account_with_deposit : Euro.c -> object val mutable balance : Euro.c val mutable history : Euro.c operation list method balance : Euro.c method deposit : Euro.c -> unit method history : Euro.c operation list method private trace : Euro.c operation -> unit method withdraw : Euro.c -> Euro.c end
Indeed, the latter is safer since the call to deposit will automatically benefit from safety checks and from the trace. Let’s test it:
# let ccp = new account_with_deposit (euro 100.) in let balance = ccp#withdraw (euro 50.) in ccp#history;; Warning 26: unused variable balance. - : Euro.c operation list = [Deposit <obj>; Retrieval <obj>]
Closing an account can be done with the following polymorphic function:
# let close c = c#withdraw (c#balance);; val close : < balance : 'a; withdraw : 'a -> 'b; .. > -> 'b = <fun>
Of course, this applies to all sorts of accounts.
Finally, we gather several versions of the account into a module Account abstracted over some currency.
# let today () = (01,01,2000) (* an approximation *) module Account (M:MONEY) = struct type m = M.c let m = new M.c let zero = m 0. class bank = object (self) val mutable balance = zero method balance = balance val mutable history = [] method private trace x = history <- x::history method deposit x = self#trace (Deposit x); if zero#leq x then balance <- balance # plus x else raise (Invalid_argument "deposit") method withdraw x = if x#leq balance then (balance <- balance # plus (neg x); self#trace (Retrieval x); x) else zero method history = List.rev history end class type client_view = object method deposit : m -> unit method history : m operation list method withdraw : m -> m method balance : m end class virtual check_client x = let y = if (m 100.)#leq x then x else raise (Failure "Insufficient initial deposit") in object (self) initializer self#deposit y end module Client (B : sig class bank : client_view end) = struct class account x : client_view = object inherit B.bank inherit check_client x end let discount x = let c = new account x in if today() < (1998,10,30) then c # deposit (m 100.); c end end;;
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.
# module Euro_account = Account(Euro);; module Client = Euro_account.Client (Euro_account);; new Client.account (new Euro.c 100.);;
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.
# module Investment_account (M : MONEY) = struct type m = M.c module A = Account(M) class bank = object inherit A.bank as super method deposit x = if (new M.c 1000.)#leq x then print_string "Would you like to invest?"; super#deposit x end module Client = A.Client end;;
The functor Client may also be redefined when some new features of the account can be given to the client.
# module Internet_account (M : MONEY) = struct type m = M.c module A = Account(M) class bank = object inherit A.bank method mail s = print_string s end class type client_view = object method deposit : m -> unit method history : m operation list method withdraw : m -> m method balance : m method mail : string -> unit end module Client (B : sig class bank : client_view end) = struct class account x : client_view = object inherit B.bank inherit A.check_client x end end end;;
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.
A naive definition of strings as objects could be:
# class ostring s = object method get n = String.get s n method set n c = String.set s n c method print = print_string s method copy = new ostring (String.copy s) end;; class ostring : string -> object method copy : ostring method get : int -> char method print : unit method set : int -> char -> unit end
However, the method copy returns an object of the class ostring, 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.
# class sub_string s = object inherit ostring s method sub start len = new sub_string (String.sub s start len) end;; class sub_string : string -> object method copy : ostring method get : int -> char method print : unit method set : int -> char -> unit method sub : int -> int -> sub_string end
As seen in section 3.16, the solution is to use functional update instead. We need to create an instance variable containing the representation s of the string.
# class better_string s = object val repr = s method get n = String.get repr n method set n c = String.set repr n c method print = print_string repr method copy = {< repr = String.copy repr >} method sub start len = {< repr = String.sub s start len >} end;; class better_string : string -> object ('a) val repr : string method copy : 'a method get : int -> char method print : unit method set : int -> char -> unit method sub : int -> int -> 'a end
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:
# class ostring s = object (self : 'mytype) val repr = s method repr = repr method get n = String.get repr n method set n c = String.set repr n c method print = print_string repr method copy = {< repr = String.copy repr >} method sub start len = {< repr = String.sub s start len >} method concat (t : 'mytype) = {< repr = repr ^ t#repr >} end;; class ostring : string -> object ('a) val repr : string method concat : 'a -> 'a method copy : 'a method get : int -> char method print : unit method repr : string method set : int -> char -> unit method sub : int -> int -> 'a end
Another constructor of the class string can be defined to return an uninitialized string of a given length:
# class cstring n = ostring (String.create n);; class cstring : int -> ostring
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.
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:
# exception Empty;; exception Empty # class ['a] stack = object val mutable l = ([] : 'a list) method push x = l <- x::l method pop = match l with [] -> raise Empty | a::l' -> l <- l'; a method clear = l <- [] method length = List.length l end;; class ['a] stack : object val mutable l : 'a list method clear : unit method length : int method pop : 'a method push : 'a -> unit end
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:
# class ['a, 'b] stack2 = object inherit ['a] stack method fold f (x : 'b) = List.fold_left f x l end;; class ['a, 'b] stack2 : object val mutable l : 'a list method clear : unit method fold : ('b -> 'a -> 'b) -> 'b -> 'b method length : int method pop : 'a method push : 'a -> unit end
However, the method fold of a given object can only be applied to functions that all have the same type:
# let s = new stack2;; val s : ('_a, '_b) stack2 = <obj> # s#fold (+) 0;; - : int = 0 # s;; - : (int, int) stack2 = <obj>
A better solution is to use polymorphic methods, which were introduced in OCaml 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.
# class ['a] stack3 = object inherit ['a] stack method fold : 'b. ('b -> 'a -> 'b) -> 'b -> 'b = fun f x -> List.fold_left f x l end;; class ['a] stack3 : object val mutable l : 'a list method clear : unit method fold : ('b -> 'a -> 'b) -> 'b -> 'b method length : int method pop : 'a method push : 'a -> unit end
A simplified version of object-oriented hash tables should have the following class type.
# class type ['a, 'b] hash_table = object method find : 'a -> 'b method add : 'a -> 'b -> unit end;; class type ['a, 'b] hash_table = object method add : 'a -> 'b -> unit method find : 'a -> 'b end
A simple implementation, which is quite reasonable for small hastables is to use an association list:
# class ['a, 'b] small_hashtbl : ['a, 'b] hash_table = object val mutable table = [] method find key = List.assoc key table method add key valeur = table <- (key, valeur) :: table end;; class ['a, 'b] small_hashtbl : ['a, 'b] hash_table
A better implementation, and one that scales up better, is to use a true hash tables… whose elements are small hash tables!
# class ['a, 'b] hashtbl size : ['a, 'b] hash_table = object (self) val table = Array.init size (fun i -> new small_hashtbl) method private hash key = (Hashtbl.hash key) mod (Array.length table) method find key = table.(self#hash key) # find key method add key = table.(self#hash key) # add key end;; class ['a, 'b] hashtbl : int -> ['a, 'b] hash_table
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.
# module type SET = sig type 'a tag class ['a] c : object ('b) method is_empty : bool method mem : 'a -> bool method add : 'a -> 'b method union : 'b -> 'b method iter : ('a -> unit) -> unit method tag : 'a tag end end;; module Set : SET = struct let rec merge l1 l2 = match l1 with [] -> l2 | h1 :: t1 -> match l2 with [] -> l1 | h2 :: t2 -> if h1 < h2 then h1 :: merge t1 l2 else if h1 > h2 then h2 :: merge l1 t2 else merge t1 l2 type 'a tag = 'a list class ['a] c = object (_ : 'b) val repr = ([] : 'a list) method is_empty = (repr = []) method mem x = List.exists ((=) x) repr method add x = {< repr = merge [x] repr >} method union (s : 'b) = {< repr = merge repr s#tag >} method iter (f : 'a -> unit) = List.iter f repr method tag = repr end end;;
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.
# class virtual ['subject, 'event] observer = object method virtual notify : 'subject -> 'event -> unit end;; class virtual ['subject, 'event] observer : object method virtual notify : 'subject -> 'event -> unit end
The class subject remembers a list of observers in an instance variable, and has a distinguished method notify_observers to broadcast the message notify to all observers with a particular event e.
# class ['observer, 'event] subject = object (self) val mutable observers = ([]:'observer list) method add_observer obs = observers <- (obs :: observers) method notify_observers (e : 'event) = List.iter (fun x -> x#notify self e) observers end;; class ['a, 'event] subject : object ('b) constraint 'a = < notify : 'b -> 'event -> unit; .. > val mutable observers : 'a list method add_observer : 'a -> unit method notify_observers : 'event -> unit end
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.
# type event = Raise | Resize | Move;; type event = Raise | Resize | Move # let string_of_event = function Raise -> "Raise" | Resize -> "Resize" | Move -> "Move";; val string_of_event : event -> string = <fun> # let count = ref 0;; val count : int ref = {contents = 0} # class ['observer] window_subject = let id = count := succ !count; !count in object (self) inherit ['observer, event] subject val mutable position = 0 method identity = id method move x = position <- position + x; self#notify_observers Move method draw = Printf.printf "{Position = %d}\n" position; end;; class ['a] window_subject : object ('b) constraint 'a = < notify : 'b -> event -> unit; .. > val mutable observers : 'a list val mutable position : int method add_observer : 'a -> unit method draw : unit method identity : int method move : int -> unit method notify_observers : event -> unit end # class ['subject] window_observer = object inherit ['subject, event] observer method notify s e = s#draw end;; class ['a] window_observer : object constraint 'a = < draw : unit; .. > method notify : 'a -> event -> unit end
Unsurprisingly the type of window is recursive.
# let window = new window_subject;; val window : < notify : 'a -> event -> unit; _.. > window_subject as 'a = <obj>
However, the two classes of window_subject and window_observer are not mutually recursive.
# let window_observer = new window_observer;; val window_observer : < draw : unit; _.. > window_observer = <obj> # window#add_observer window_observer;; - : unit = () # window#move 1;; {Position = 1} - : unit = ()
Classes window_observer and window_subject can still be extended by inheritance. For instance, one may enrich the subject with new behaviors and refined the behavior of the observer.
# class ['observer] richer_window_subject = object (self) inherit ['observer] window_subject val mutable size = 1 method resize x = size <- size + x; self#notify_observers Resize val mutable top = false method raise = top <- true; self#notify_observers Raise method draw = Printf.printf "{Position = %d; Size = %d}\n" position size; end;; class ['a] richer_window_subject : object ('b) constraint 'a = < notify : 'b -> event -> unit; .. > val mutable observers : 'a list val mutable position : int val mutable size : int val mutable top : bool method add_observer : 'a -> unit method draw : unit method identity : int method move : int -> unit method notify_observers : event -> unit method raise : unit method resize : int -> unit end # class ['subject] richer_window_observer = object inherit ['subject] window_observer as super method notify s e = if e <> Raise then s#raise; super#notify s e end;; class ['a] richer_window_observer : object constraint 'a = < draw : unit; raise : unit; .. > method notify : 'a -> event -> unit end
We can also create a different kind of observer:
# class ['subject] trace_observer = object inherit ['subject, event] observer method notify s e = Printf.printf "<Window %d <== %s>\n" s#identity (string_of_event e) end;; class ['a] trace_observer : object constraint 'a = < identity : int; .. > method notify : 'a -> event -> unit end
and attached several observers to the same object:
# let window = new richer_window_subject;; val window : < notify : 'a -> event -> unit; _.. > richer_window_subject as 'a = <obj> # window#add_observer (new richer_window_observer);; - : unit = () # window#add_observer (new trace_observer);; - : unit = () # window#move 1; window#resize 2;; <Window 1 <== Move> <Window 1 <== Raise> {Position = 1; Size = 1} {Position = 1; Size = 1} <Window 1 <== Resize> <Window 1 <== Raise> {Position = 1; Size = 3} {Position = 1; Size = 3} - : unit = ()
Part II |
This document is intended as a reference manual for the OCaml 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 OCaml 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.
The syntax of the language is given in BNF-like notation. Terminal symbols are set in typewriter font (like this). Non-terminal symbols are set in italic font (like that). 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 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 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 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.
|
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.
For convenience and readability, underscore characters (_) are accepted (and ignored) within integer literals.
|
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.
For convenience and readability, underscore characters (_) are accepted (and ignored) within floating-point literals.
|
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) |
\space | space (SPC) |
\ddd | the character with ASCII code ddd in decimal |
\xhh | the character with ASCII code hh in hexadecimal |
|
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.
To avoid ambiguities, naming labels in expressions cannot just be defined syntactically as the sequence of the three tokens ~, ident and :, and have to be defined at the lexical level.
|
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 ?.
Despite label and optlabel being lexical entities in expressions, their expansions ~ label-name : and ? label-name : will be used in grammars, for the sake of readability. Note also that inside type expressions, this expansion can be taken literally, i.e. there are really 3 tokens, with optional spaces beween them.
|
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 like normal identifiers.
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
The following character sequences are also keywords:
!= # & && ' ( ) * + , - -. -> . .. : :: := :> ; ;; < <- = > >] >} ? ?? [ [< [> [| ] _ ` { {< | |] } ~
Note that the following identifiers are keywords of the Camlp4 extensions and should be avoided for compatibility reasons.
parser << <: >> $ $$ $:
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.
|
Preprocessors that generate OCaml 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.
This section describes the kinds of values that are manipulated by OCaml programs.
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 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.
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.
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.
Tuples of values are written (v1, …, vn), standing for the n-tuple of values v1 to vn. The current implementation supports tuple of up to 222 − 1 elements (4194303 elements).
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 up to 222 − 1 elements (4194303 elements) unless the elements are floating-point numbers (2097151 elements in this case); on 64-bit platforms, the limit is 254 − 1 for all arrays.
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).
Functional values are mappings from values to values.
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:
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.
|
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.
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.
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; and they can only be generalized when leaving this scope. Anonymous variables have no such restriction. In the following cases, the scope of named type variables is restricted to the type expression where they appear: 1) for universal (explicitly polymorphic) type variables; 2) for type variables that only appear in public method specifications (as those variables will be made universal, as described in section 6.9.1); 3) for variables used as aliases, when the type they are aliased to would be invalid in the scope of the enclosing definition (i.e. when it contains free universal type variables, or locally defined types.)
The type expression ( typexpr ) denotes the same type as typexpr.
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.
? label-name : typexpr1 -> 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 typexpr1 option -> typexpr2.
The type expression typexpr1 * … * typexprn denotes the type of tuples whose elements belong to types typexpr1, … typexprn respectively.
Type constructors with no parameter, as in typeconstr, are type expressions.
The type expression typexpr typeconstr, 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.
The type expression typexpr as ' ident denotes the same type as typexpr, and also binds the type variable ident to type typexpr both in typexpr and in other types. In general the scope of an alias is the same as for a named type variable, and covers the whole enclosing definition. 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 polymorphic 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 polymorphic variant type, the row variable of typexpr is captured by ' ident, and quantified upon.
|
|
Polymorphic 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 [of typexpr] 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.
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.
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-path as ' ident) -> ' ident.
Use of #-types to abbreviate polymorphic 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]
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”.
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).
A pattern consisting in a constant matches the values that are equal to this constant.
The pattern pattern1 as value-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.
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 typexpr.
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.
The pattern constr pattern1 matches all variants whose constructor is equal to constr, and whose argument matches pattern1.
The pattern pattern1 :: pattern2 matches non-empty lists whose heads match pattern1, and whose tails match pattern2.
The pattern [ pattern1 ; … ; patternn ] matches lists of length n whose elements match pattern1 …patternn, respectively. This pattern behaves like pattern1 :: … :: patternn :: [].
The pattern `tag-name pattern1 matches all polymorphic variants whose tag is equal to tag-name, and whose argument matches pattern1.
If the type [('a,'b,...)] typeconstr = [`tag1 typexpr1 | … | `tagn typexprn] is defined, then the pattern #typeconstr is a shorthand for the or-pattern (`tag1(_ : typexpr1) | … | `tagn(_ : typexprn)). It matches all values of type #typeconstr.
The pattern pattern1 , … , patternn matches n-tuples whose components match the patterns pattern1 through patternn. That is, the pattern matches the tuple values (v1, …, vn) such that patterni matches vi for i = 1,… , n.
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.
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 *”.
Construction or operator | Associativity |
prefix-symbol | – |
. .( .[ | – |
function application, constructor application, assert, lazy | left |
- -. (prefix) | – |
**… lsl lsr asr | right |
*… /… %… mod land lor lxor | left |
+… -… | left |
:: | right |
@… ^… | right |
=… <… >… |… &… $… | left |
& && | right |
or || | right |
, | – |
<- := | right |
if | – |
; | right |
let match fun function try | – |
Expressions consisting in a constant evaluate to this constant.
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.
The expressions ( expr ) and begin expr end have the same value as expr. The two 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 : typexpr ). This constraint forces the type of expr to be compatible with typexpr.
Parenthesized expressions can also contain coercions ( expr [: typexpr] :> typexpr) (see subsection 6.7.6 below).
Function application is denoted by juxtaposition of (possibly labeled) expressions. The expression expr argument1 … 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.
Two syntactic forms are provided to define functions. The first form is introduced by the keyword function:
|
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:
This expression is equivalent to:
The parameter patterns ~var and ~(var [: typexpr]) are shorthands for respectively ~var:var and ~var:(var [: typexpr]), and similarly for their optional counterparts.
Functions of the form fun ?lab:( pattern = expr0 ) -> expr are equivalent to
where ident is a fresh variable. When expr0 will be evaluated is left unspecified.
After these two transformations, expressions are of the form
If we ignore labels, which will only be meaningful at function application, this is equivalent to
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.
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:
|
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.
The let and let rec constructs bind value names locally. The construct
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
in a let expression, one may instead write
Recursive definitions of names are introduced by let rec:
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:
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.
The expression if expr1 then expr2 else expr3 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 else expr3 part can be omitted, in which case it defaults to else ().
The expression
|
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.
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
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
The boolean operator & is synonymous for &&. The boolean operator or is synonymous for ||.
The expression while expr1 do expr2 done 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 for name = expr1 to expr2 do expr3 done 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 for name = expr1 downto expr2 do expr3 done 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 ().
The expression
|
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.
The expression constr expr 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.
The expression `tag-name expr evaluates to the polymorphic variant value whose tag is tag-name, and whose argument is the value of expr.
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 { expr with field1 = 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 ().
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 ().
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-symbol expr is interpreted as the application ( prefix-symbol ) expr. Similarly, the expression expr1 infix-symbol expr2 is interpreted as the application ( infix-symbol ) expr1 expr2.
The table below lists the symbols defined in the initial environment and their initial meaning. (See the description of the core library module Pervasives in chapter 20 for more details). Their meaning may be changed at any time using let ( infix-op ) name1 name2 = …
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). |
= | Structural equality test. |
<> | Structural inequality test. |
== | Physical equality test. |
!= | Physical inequality test. |
< | Test “less than”. |
<= | Test “less than or equal”. |
> | Test “greater than”. |
>= | Test “greater than or equal”. |
When class-path evaluates to a class body, new class-path evaluates to an object containing the instance variables and methods of this class.
When class-path evaluates to a class function, new class-path evaluates to a function expecting the same number of arguments and returning a new object of this class.
Creating directly an object through the object class-body end construct is operationally equivalent to defining locally a class class-name = object class-body end —see sections 6.9.2 and following for the syntax of class-body— and immediately creating a single object from it by new class-name.
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.
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 (let ident = new class-path … ) or if there is a type constraint. Principality of the derivation can be checked in the -principal mode.
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 ().
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.
Expressions whose type contains object or polymorphic variant types can be explicitly 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 polymorphic variants, keeping only recursion when it is explicit in the class type (for objects). As an exception to the above algorithm, if both the inferred type of expr and typexpr are ground (i.e. do not contain type variables), the former operator behaves as the latter one, taking the inferred type of expr as typexpr1. In case of failure with the former operator, the latter one should be used.
It is only possible to coerce an expression expr from type typexpr1 to type typexpr2, if the type of expr is an instance of typexpr1 (like for a type annotation), and typexpr1 is a subtype of typexpr2. The type of the coerced expression is an instance of typexpr2. If the types contain variables, they may be instantxsiated by the subtyping algorithm, but this is only done after determining whether typexpr1 is a potential subtype of typexpr2. This means that typing may fail during this latter unification step, even if some instance of typexpr1 is a subtype of some instance of typexpr2. In the following paragraphs we describe the subtyping relation used.
A fixed object type admits as subtype any object type including all its methods. The types of the methods shall be subtypes of those in the supertype. Namely,
< met1 : typ1 ; ... ; metn : typn > |
is a supertype of
< met1 : typ′1 ; ... ; metn : typ′n ; metn+1 : typ′n+1 ; ... ; metn+m : typ′n+m [; ..] > |
which may contain an ellipsis .., if every typi is a supertype of typ′i.
A monomorphic method type can be a supertype of a polymorphic method type. Namely, if typ is an instance of typ′, then 'a1 ...'an.typ′ is a subtype of typ.
Inside a class definition, newly defined types are not available for subtyping, as the type abbreviations are not yet completely defined. There is an exception for coercing self to the (exact) type of its class: this is allowed if the type of self does not appear in a contravariant position in the class type, i.e. if there are no binary methods.
A polymorphic variant type typ is subtype of another polymorphic variant type typ′ if the upper bound of typ (i.e. the maximum set of constructors that may appear in an instance of typ) is included in the lower bound of typ′, and the types of arguments for the constructors of typ are subtypes of those in typ′. Namely,
[[<] 'C1 of typ1 | ... | 'Cn of typn ] |
which may be a shrinkable type, is a subtype of
[[>] 'C1 of typ′1 | ... | 'Cn of typ′n | 'Cn+1 of typ′n+1 | ... | 'Cn+m of typ′n+m ] |
which may be an extensible type, if every typi is a subtype of typ′i.
Other types do not introduce new subtyping, but they may propagate the subtyping of their arguments. For instance, typ1 * typ2 is a subtype of typ′1 * typ′2 when typ1 and typ2 are respectively subtypes of typ′1 and typ′2. For function types, the relation is more subtle: typ1 -> typ2 is a subtype of typ′1 -> typ′2 if typ1 is a supertype of typ′1 and typ2 is a subtype of typ′2. For this reason, function types are covariant in their second argument (like tuples), but contravariant in their first argument. Mutable types, like array or ref are neither covariant nor contravariant, they are nonvariant, that is they do not propagate subtyping.
For user defined types, the variance is automatically inferred: a parameter is covariant if it has only covariant occurences, contravariant if it has only contravariant occurences, variance-free if it has no occurences, and nonvariant otherwise. A variance-free parameter may change freely through subtyping, it does not have to be a subtype or a supertype. For abstract and private types, the variance must be given explicitly, otherwise the default is nonvariant. This is also the case for constrained arguments in type definitions.
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 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 contravariant parameter only the left side (left branch of an odd number of arrows). If the type has either a representation or an equation, and the parameter is free (i.e. not bound via a type constraint to a constructed type), its variance constraint is checked but subtyping etc. will use the inferred variance of the parameter, which may be better; otherwise (i.e. for abstract types or non-free parameters), the variance must be given explicitly, and the parameter is invariant if no variance was given.
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-name of typexpr1, …, typexprn declares the name constr-name as a non-constant constructor, whose arguments have types typexpr1 …typexprn. 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 mutable field-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:
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.6).
For instance, type +'a t declares t as an abstract type that is covariant in its parameter; this means that if the type τ is a subtype of the type σ, then τ t is a subtype of σ t. Similarly, type -'a t declares that the abstract type t is contravariant in its parameter: if τ is subtype of σ, then σ t is subtype of τ 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 is neither a subtype nor a supertype of σ t if τ is subtype of σ.
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 the specification of 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 exception constr-name [of typexpr { * typexpr }] generates a new exception, distinct from all other exceptions in the system. The form exception constr-name = constr gives an alternate name to an existing exception.
Classes are defined using a small language, similar to the module language.
Class types are the class-level equivalent of type expressions: they specify the general shape and type properties of classes.
|
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 instantiated to respectively typexpr1, …typexprn.
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.
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.
The inheritance construct inherit class-type provides for inclusion of methods and instance variables from other class types. The instance variable and method types from class-type are added into the current class type.
A specification of an instance variable is written val [mutable] [virtual] 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. The flag virtual indicates that this instance variable is not initialized. It can be initialized later through inheritance.
An instance variable specification will hide any previous specification of an instance variable of the same name.
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 that the method cannot be accessed from outside the object.
The polymorphism may be left implicit in public 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 universal, and made polymorphic in the resulting method type. Writing an explicit polymorphic type will disable this behaviour.
Several specifications for the same method must have compatible types. Any non-private specification of a method forces it to be public.
Virtual method specification is written method [private] virtual method-name : poly-typexpr, where method-name is the name of the method and poly-typexpr its expected type.
The construct constraint typexpr1 = 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.
|
|
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 instantiated 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 is denoted by juxtaposition of (possibly labeled) expressions. It denotes the class whose constructor is the original constructor applied to the given arguments. The arguments are evaluated like for expression application, but the constructor itself will only be evaluated when objects are created. In particular, side-effects caused by the application of the constructor will only occur at object creation time.
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
is a short form for
The let and let rec constructs bind value names locally, as for the core language expressions.
If a local definition occurs at the very beginning of a class definition, it will be evaluated when the class is created (just as if the definition was outside of the class). Otherwise, it will be evaluated when the object constructor is called.
|
The expression object class-body 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.
The inheritance construct inherit class-expr allows reusing 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 as value-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.
The definition val [mutable] inst-var-name = expr adds an instance variable inst-var-name whose initial value is the value of expression expr. 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.
Since version 3.10, redefinitions of a visible instance variable with the same name do not create a new variable, but are merged, using the last value for initialization. They must have identical types and mutability. However, if an instance variable is hidden by omitting it from an interface, it will be kept distinct from other instance variables with the same name.
Variable specification is written val [mutable] virtual inst-var-name : typexpr. It specifies whether the variable is modifiable, and gives its type.
Virtual instance variables were added in version 3.10.
Method definition is written method method-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, method private method-name = expr, is a method that can only be invoked on self (from other methods of the same object, defined in this class or one of its subclasses). 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:
|
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.
Method specification is written method [private] virtual method-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.
The construct constraint typexpr1 = 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.
A class initializer initializer expr 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 class class-binding { and class-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).
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.
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.
|
This is the counterpart in signatures of class definitions. A class specification matches a class definition if they have the same type parameters and their types match.
|
A class type definition class class-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.
Module types are the module-level equivalent of type expressions: they specify the general shape and type properties of modules.
|
|
The expression modtype-path is equivalent to the module type bound to the name modtype-path. The expression ( module-type ) denotes the same type as module-type.
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.
A specification of a value component in a signature is written val value-name : typexpr, where value-name is the name of the value and typexpr its expected type.
The form external value-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 19).
A specification of one or several type components in a signature is written type typedef { and typedef } and consists of a sequence of mutually recursive definitions of type names.
Each type definition in the signature specifies an optional type equation = typexpr and an optional type representation = constr-decl … or = { field-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:
The specification exception constr-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.
A specification of one or several classes in a signature is written class class-spec { and class-spec } and consists of a sequence of mutually recursive definitions of class names.
Class specifications are described more precisely in section 6.9.4.
A specification of one or several classe types in a signature is written class type classtype-def { and classtype-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.
A specification of a module component in a signature is written module module-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.
For specifying a module component that is a functor, one may write
instead of
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 module type modtype-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 module type modtype-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.
The expression open module-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.
The expression include module-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-type with mod-constraint { and mod-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 = typexpr adds the type equation = typexpr to the specification of the type component named typeconstr of the constrained signature. The constraint module module-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.
Module expressions are the module-level equivalent of value expressions: they evaluate to modules, thus providing implementations for the specifications expressed in module types.
|
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. In this case, the ;; of the previous component is not optional.
A value definition let [rec] let-binding { and let-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 value definition external value-name : typexpr = external-declaration implements value-name as the external function specified in external-declaration (see chapter 19).
A definition of one or several type components is written type typedef { and typedef } and consists of a sequence of mutually recursive definitions of type names.
Exceptions are defined with the syntax exception constr-decl or exception constr-name = constr.
A definition of one or several classes is written class class-binding { and class-binding } and consists of a sequence of mutually recursive definitions of class names. Class definitions are described more precisely in section 6.9.3.
A definition of one or several classes is written class type classtype-def { and classtype-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.
The basic form for defining a module component is module module-name = module-expr, which evaluates module-expr and binds the result to the name module-name.
One can write
instead of
Another derived form is
which is equivalent to
A definition for a module type is written module type modtype-name = module-type. It binds the name modtype-name to the module type denoted by the expression module-type.
The expression open module-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.
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 = S.t let x = S.x 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).
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
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
where name1 … namen are the names of the other compilation units available in the search path (see chapter 8 for more details) and specification1 … specificationn are their respective interfaces.
This chapter describes language extensions and convenience features that are implemented in OCaml, but not described in the OCaml reference manual.
(Introduced in Objective Caml 3.07)
|
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.
(Removed in Objective Caml 3.03)
The syntax for streams and stream parsers is no longer part of the
OCaml language, but available through a Camlp4 syntax
extension. See the Camlp4 reference manual for more information.
Support for basic operations on streams is still available through the
Stream[Stream] module of the standard library.
OCaml programs
that use the stream parser syntax should be compiled with the
-pp camlp4o option to ocamlc and ocamlopt. For interactive use,
run ocaml and issue the #load "dynlink.cma";;
command,
followed by the #load "camlp4o.cma";;
command.
(Introduced in Objective Caml 1.00)
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
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:
It will be accepted if each one of expr1 … exprn is statically constructive with respect to name1 … namen, is not immediately linked to any of name1 … namen, and is not an array constructor whose arguments have abstract type.
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:
An expression e is said to be immediately linked to the variable name in the following cases:
(Introduced in Objective Caml 1.00)
In patterns, OCaml recognizes the form ' c ' .. ' d ' (two character literals separated by ..) as shorthand for the pattern
where c1, c2, …, cn are the characters that occur between c and d in the ASCII character set. For instance, the pattern '0'..'9' matches all characters that are digits.
(Introduced in Objective Caml 1.06)
OCaml supports the assert construct to check debugging assertions. The expression assert expr 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).
(Introduced in Objective Caml 1.06 for expressions; in Objective Caml 3.11 for patterns)
The expression lazy expr 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. Applications of Lazy.force may be implicit through pattern matching.
The pattern lazy pattern matches values v of type Lazy.t, provided pattern matches the result of forcing v with Lazy.force. A successful match of a pattern containing lazy sub-patterns forces the corresponding parts of the value being matched, even those that imply no test such as lazy value-name or lazy _. Matching a value with a pattern-matching where some patterns contain lazy sub-patterns may imply forcing parts of the value, even when the pattern selected in the end has no lazy sub-pattern.
For more information, see the description of module Lazy in the standard library (see Module Lazy).
(Introduced in Objective Caml 2.00)
The expression let module module-name = module-expr in expr 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:
let remove_duplicates comparison_fun string_list = let module StringSet = Set.Make(struct type t = string let compare = comparison_fun end) in StringSet.elements (List.fold_right StringSet.add string_list StringSet.empty)
(Introduced in Objective Caml 3.07)
|
Recursive module definitions, introduced by the module rec …and … construction, generalize regular module definitions module module-name = module-expr and module specifications module module-name : module-type by allowing the defining module-expr and the module-type to refer recursively to the module identifiers being defined. A typical example of a recursive module definition is:
module rec A : sig type t = Leaf of string | Node of ASet.t val compare: t -> t -> int end = struct type t = Leaf of string | Node of ASet.t let compare t1 t2 = match (t1, t2) with (Leaf s1, Leaf s2) -> Pervasives.compare s1 s2 | (Leaf _, Node _) -> 1 | (Node _, Leaf _) -> -1 | (Node n1, Node n2) -> ASet.compare n1 n2 end and ASet : Set.S with type elt = A.t = Set.Make(A)
It can be given the following specification:
module rec A : sig type t = Leaf of string | Node of ASet.t val compare: t -> t -> int end and ASet : Set.S with type elt = A.t
This is an experimental extension of OCaml: 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 typexpr1 -> typexpr2. Evaluation of a recursive module definition proceeds by building initial values for the safe modules involved, binding all (functional) values to fun _ -> raise Undefined_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.
Private type declarations in module signatures, of the form type t = private ..., enable libraries to reveal some, but not all aspects of the implementation of a type to clients of the library. In this respect, they strike a middle ground between abstract type declarations, where no information is revealed on the type implementation, and data type definitions and type abbreviations, where all aspects of the type implementation are publicized. Private type declarations come in three flavors: for variant and record types (section 7.9.1), for type abbreviations (section 7.9.2), and for row types (section 7.9.3).
(Introduced in Objective Caml 3.07)
|
Values of a variant or record type declared private 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:
module M : sig type t = private A | B of int val a : t val b : int -> t end = struct type t = A | B of int let a = A let b n = assert (n > 0); B n end
Here, the private declaration ensures that in any value of type M.t, the argument to the B constructor is always a positive integer.
With respect to the variance of their parameters, private types are handled like abstract types. That is, if a private type has parameters, their variance is the one explicitly given by prefixing the parameter by a ‘+’ or a ‘-’, it is invariant otherwise.
(Introduced in Objective Caml 3.11)
|
Unlike a regular type abbreviation, a private type abbreviation declares a type that is distinct from its implementation type typexpr. However, coercions from the type to typexpr are permitted. Moreover, the compiler “knows” the implementation type and can take advantage of this knowledge to perform type-directed optimizations. For ambiguity reasons, typexpr cannot be an object or polymorphic variant type, but a similar behaviour can be obtained through private row types.
The following example uses a private type abbreviation to define a module of nonnegative integers:
module N : sig type t = private int val of_int: int -> t val to_int: t -> int end = struct type t = int let of_int n = assert (n >= 0); n let to_int n = n end
The type N.t is incompatible with int, ensuring that nonnegative integers and regular integers are not confused. However, if x has type N.t, the coercion (x :> int) is legal and returns the underlying integer, just like N.to_int x. Deep coercions are also supported: if l has type N.t list, the coercion (l :> int list) returns the list of underlying integers, like List.map N.to_int l but without copying the list l.
Note that the coercion (expr :> typexpr) is actually an abbreviated form, and will only work in presence of private abbreviations if both the type of expr and typexpr contain no type variables. If this is not the case, you must use the full form (expr : typ_e :> typexpr) where typ_e is the expected type of expr. Concretely, this would be (x : N.t :> int) and (l : N.t list :> int list) for the above examples.
(Introduced in Objective Caml 3.09)
|
Private row types are type abbreviations where part of the structure of the type is left abstract. Concretely typexpr in the above should denote either an object type or a polymorphic variant type, with some possibility of refinement left. If the private declaration is used in an interface, the corresponding implementation may either provide a ground instance, or a refined private type.
module M : sig type c = private < x : int; .. > val o : c end = struct class c = object method x = 3 method y = 2 end let o = new c end
This declaration does more than hiding the y method, it also makes the type c incompatible with any other closed object type, meaning that only o will be of type c. In that respect it behaves similarly to private record types. But private row types are more flexible with respect to incremental refinement. This feature can be used in combination with functors.
module F(X : sig type c = private < x : int; .. > end) = struct let get_x (o : X.c) = o#x end module G(X : sig type c = private < x : int; y : int; .. > end) = struct include F(X) let get_y (o : X.c) = o#y end
Polymorphic variant types can be refined in two ways, either to allow the addition of new constructors, or to allow the disparition of declared constructors. The second case corresponds to private variant types (one cannot create a value of the private type), while the first case requires default cases in pattern-matching to handle addition.
type t = [ `A of int | `B of bool ] type u = private [< t > `A ] type v = private [> t ]
With type u, it is possible to create values of the form (`A n), but not (`B b). With type v, construction is not restricted but pattern-matching must have a default case.
Like for abstract and private types, the variance of type parameters is not inferred, and must be given explicitly.
(Introduced in OCaml 3.12)
|
The expressions let open module-path in expr and module-path. (expr) are strictly equivalent. They locally open the module referred to by the module path module-path in the scope of the expression expr.
Restricting opening to the scope of a single expression instead of a whole structure allows one to benefit from shorter syntax to refer to components of the opened module, without polluting the global scope. Also, this can make the code easier to read (the open statement is closer to where it is used) and to refactor (because the code fragment is more self-contained).
(Introduced in OCaml 3.12)
|
In a record pattern or a record construction expression, a single identifier id stands for id = id, and a qualified identifier module-path . id stands for module-path . id = id. For example, assuming the record type
type point = { x: float; y: float }
has been declared, the following expressions are equivalent:
let x = 1 and y = 2 in { x = x; y = y } let x = 1 and y = 2 in { x; y } let x = 1 and y = 2 in { x = x; y }
Likewise, the following functions are equivalent:
fun {x = x; y = y} -> x + y fun {x; y} -> x + y
Optionally, a record pattern can be terminated by ; _ to convey the fact that not all fields of the record type are listed in the record pattern and that it is intentional. By default, the compiler ignores the ; _ annotation. If the R warning is turned on, however, the compiler will warn if a record pattern fails to list all fields of the corresponding record type and is not terminated by ; _. Continuing the point example above,
fun {x} -> x + 1
will warn if the R warning is on, while
fun {x; _} -> x + 1
will not warn. This warning can help spot program points where record patterns may need to be modified after new fields were added to a record type.
(Introduced in OCaml 3.12)
|
Polymorphic type annotations in let-definitions behave in a way similar to polymorphic methods: they explicitly require the defined value to be polymorphic, and allow one to use this polymorphism in recursive occurences (when using let rec). Note however that this is just an usual polymorphic type, unifiable with any instance of itself.
There two possible applications of this feature. One is polymorphic recursion:
type 'a t = Leaf of 'a | Node of ('a * 'a) t let rec depth : 'a. 'a t -> 'b = function Leaf _ -> 1 | Node x -> 1 + depth x
Note that 'b is not explicitly polymorphic here, and it will actually be unified with int.
The other application is to ensure that some definition is sufficiently polymorphic.
# let id : 'a. 'a -> 'a = fun x -> x+1 ;; Error: This definition has type int -> int which is less general than 'a. 'a -> 'a
(Introduced in OCaml 3.12)
|
The expression fun ( type typeconstr-name ) -> expr introduces a type constructor named typeconstr-name which is considered abstract in the scope of the sub-expression, but then replaced by a fresh type variable. Note that contrary to what the syntax could suggest, the expression fun ( type typeconstr-name ) -> expr itself does not suspend the evaluation of expr as a regular abstraction would. The syntax has been chosen to fit nicely in the context of function declarations, where it is generally used. It is possible to freely mix regular function parameters with pseudo type parameters, as in:
let f = fun (type t) (foo : t list) -> ...
and even use the alternative syntax for declaring functions:
let f (type t) (foo : t list) = ...
This construction is useful because the type constructor it introduces can be used in places where a type variable is not allowed. For instance, one can use it to define an exception in a local module within a polymorphic function.
let f (type t) () = let module M = struct exception E of t end in (fun x -> M.E x), (function M.E x -> Some x | _ -> None)
Here is another example:
let sort_uniq (type s) (cmp : s -> s -> int) = let module S = Set.Make(struct type t = s let compare = cmp end) in fun l -> S.elements (List.fold_right S.add l S.empty)
It is also extremely useful for first-class modules and GADTs.
(Introduced in OCaml 4.00)
|
The (type t) syntax construction by itself does not make polymorphic the type variable it introduces, but it can be combined with explicit polymorphic annotations where needed. Some syntactic sugar is provided to make this easier. Namely,
let rec f : type t1 t2. t1 * t2 list -> t1 = ...
is automatically expanded into
let rec f : 't1 't2. 't1 * 't2 list -> 't1 = fun (type t1) (type t2) -> (... : t1 * t2 list -> t1)
(Introduced in OCaml 3.12, pattern syntax and package type inference since 4.00)
|
Modules are typically thought of as static components. This extension makes it possible to pack a module as a first-class value, which can later be dynamically unpacked into a module.
The expression (module module-expr : package-type) converts the module (structure or functor) denoted by module expression module-expr to a value of the core language that encapsulates this module. The type of this core language value is (module package-type). The package-type annotation can be omitted if it can be inferred from the context.
Conversely, the module expression (val expr : package-type) evaluates the core language expression expr to a value, which must have type module package-type, and extracts the module that was encapsulated in this value. Again package-type can be omitted if the type of expr is known.
The pattern (module module-name : package-type) matches a package with type package-type and binds it to module-name. It is not allowed in toplevel let bindings. Again package-type can be omitted if it can be inferred from the enclosing pattern.
The package-type syntactic class appearing in the (module package-type) type expression and in the annotated forms represents a subset of module types. This subset consists of named module types with optional constraints of a limited form: only non-parametrized types can be specified. For type-checking purposes, package types are compared by path equality on the module type name component, and normal type equality for constraints.
The module expression (val expr : package-type) cannot be used in the body of a functor, because this can cause unsoundness in conjunction with applicative functors. It can be used anywhere in the context of a local module binding let module module-name = (val expr1 : package-type) in expr2, however.
A typical use of first-class modules is to select at run-time among several implementations of a signatures. Each implementation is a structure that we can encapsulate as a first-class module, then store in a data structure such as a hash table:
module type DEVICE = sig ... end let devices : (string, module DEVICE) Hashtbl.t = Hashtbl.create 17 module SVG = struct ... end let _ = Hashtbl.add devices "SVG" (module SVG : DEVICE) module PDF = struct ... end let _ = Hashtbl.add devices "PDF" (module PDF: DEVICE)
We can then select one implementation based on command-line arguments, for instance:
module Device = (val (try Hashtbl.find devices (parse_cmdline()) with Not_found -> eprintf "Unknown device %s\n"; exit 2) : DEVICE)
Alternatively, the selection can be performed within a function:
let draw_using_device device_name picture = let module Device = (val (Hashtbl.find_devices device_name) : DEVICE) in Device.draw picture
With first-class modules, it is possible to parametrize some code over the implementation of a module without using a functor.
let sort (type s) (module Set : Set.S with type elt = s) l = Set.elements (List.fold_right Set.add l Set.empty) val sort : (module Set.S with type elt = 'a) -> 'a list -> 'a list
To use this function, one can wrap the Set.Make functor:
let make_set (type s) cmp = let module S = Set.Make(struct type t = s let compare = cmp end) in (module S : Set.S with type elt = s) val make_set : ('a -> 'a -> int) -> (module Set.S with type elt = 'a)
(Introduced in OCaml 3.12)
|
The construction module type of module-expr expands to the module type (signature or functor type) inferred for the module expression module-expr.
A typical use, in conjunction with the signature-level include construct, is to extend the signature of an existing structure, as in the following example.
module type MYHASH = sig include module type of Hashtbl val replace: ('a, 'b) t -> 'a -> 'b -> unit end
The signature MYHASH, then, contains all the fields of the signature of module Hashtbl, plus the new field replace. An implementation of this signature can be obtained easily, using the include construct at the structure level this time:
module MyHash : MYHASH = struct include Hashtbl let replace t k v = remove t k; add t k v end
(Introduced in OCaml 3.12)
|
“Destructive” substitution (with ... :=) behaves essentially like normal signature constraints (with ... =), but it additionally removes the redefined type or module from the signature. There are a number of restrictions: one can only remove types and modules at the outermost level (not inside submodules), and the definition must be either another type constructor (with identical type parameters), or a module path.
A natural application of destructive substitution is merging two signatures sharing a type name.
module type Printable = sig type t val print : Format.formatter -> t -> unit end module type Comparable = sig type t val compare : t -> t -> int end module type PrintableComparable = sig include Printable include Comparable with type t := t end
One can also use this to completely remove a field:
# module type S = Comparable with type t := int;; module type S = sig val compare : int -> int -> int end
or to rename one:
# module type S = sig type u include Comparable with type t := u end;; module type S = sig type u val compare : u -> u -> int end
Note that you can also remove manifest types, by substituting with the same type.
# module type ComparableInt = Comparable with type t = int ;; module type ComparableInt = sig type t = int val compare : t -> t -> int end # module type CompareInt = ComparableInt with type t := int ;; module type CompareInt = sig val compare : int -> int -> int end
(Introduced in OCaml 3.12)
|
The keywords inherit!, val! and method! have the same semantics as inherit, val and method, but they additionally require the definition they introduce to be an overriding. Namely, method! requires method-name to be already defined in this class, val! requires inst-var-name to be already defined in this class, and inherit! requires class-expr to override some definitions. If no such overriding occurs, an error is signaled.
As a side-effect, these 3 keywords avoid the warnings “method override” and “ instance variable override”. As of OCaml 3.12, the warning “method override” has to be enabled manually for backwards compatibility reasons.
(Introduced in OCaml 4.00)
|
Generalized algebraic datatypes, or GADTs, extend usual sum types in two ways: constraints on type parameters may change depending on the value constructor, and some type variables may be existentially quantified. Adding constraints is done by giving an explicit return type (the rightmost typexpr in the above syntax), where type parameters are instantiated. This return type must use the same type constructor as the type being defined, and have the same number of parameters. Variables are made existential when they appear inside a constructor’s argument, but not in its return type.
Since the use of a return type often eludes the need to name type parameters in the left-hand side of a type definition, one can replace them with anonymous types “_” there.
The constraints associated to each constructor can be recovered through pattern-matching. Namely, if the type of the scrutinee of a pattern-matching contains a locally abstract type, this type can be refined according to the constructor used. These extra constraints are only valid inside the corresponding branch of the pattern-matching. If a constructor has some existential variables, fresh locally abstract types are generated, and they must not escape the scope of this branch.
Here is a concrete example:
type _ term = | Int : int -> int term | Add : (int -> int -> int) term | App : ('b -> 'a) term * 'b term -> 'a term let rec eval : type a. a term -> a = function | Int n -> n (* a = int *) | Add -> (fun x y -> x+y) (* a = int -> int -> int *) | App(f,x) -> (eval f) (eval x) (* eval called at types (b->a) and b for fresh b *) let two = eval (App (App (Add, Int 1), Int 1)) val two : int = 2
Type inference for GADTs is notoriously hard. This is due to the fact some types may become ambiguous when escaping from a branch. For instance, in the Int case above, n could have either type int or a, and they are not equivalent outside of that branch. As a first approximation, type inference will always work if a pattern-matching is annotated with types containing no free type variables (both on the scrutinee and the return type). This is the case in the above example, thanks to the type annotation containing only locally abstract types.
In practice, type inference is a bit more clever than that: type annotations do not need to be immediately on the pattern-matching, and the types do not have to be always closed. As a result, it is usually enough to only annotate functions, as in the example above. Type annotations are propagated in two ways: for the scrutinee, they follow the flow of type inference, in a way similar to polymorphic methods; for the return type, they follow the structure of the program, they are split on functions, propagated to all branches of a pattern matching, and go through tuples, records, and sum types. Moreover, the notion of ambiguity used is stronger: a type is only seen as ambiguous if it was mixed with incompatible types (equated by constraints), without type annotations between them. For instance, the following program types correctly.
let rec sum : type a. a term -> _ = fun x -> let y = match x with | Int n -> n | Add -> 0 | App(f,x) -> sum f + sum x in y + 1 val sum : 'a term -> int = <fun>
Here the return type int is never mixed with a, so it is seen as non-ambiguous, and can be inferred. When using such partial type annotations we strongly suggest specifying the -principal mode, to check that inference is principal.
The exhaustiveness check is aware of GADT constraints, and can automatically infer that some cases cannot happen. For instance, the following pattern matching is correctly seen as exhaustive (the Add case cannot happen).
let get_int : int term -> int = function | Int n -> n | App(_,_) -> 0
The term type we have defined above is an indexed type, where a type parameter reflects a property of the value contents. Another use of GADTs is singleton types, where a GADT value represents exactly one type. This value can be used as runtime representation for this type, and a function receiving it can have a polytypic behavior.
Here is an example of a polymorphic function that takes the runtime representation of some type t and a value of the same type, then pretty-prints the value as a string:
type _ typ = | Int : int typ | String : string typ | Pair : 'a typ * 'b typ -> ('a * 'b) typ let rec to_string: type t. t typ -> t -> string = fun t x -> match t with | Int -> string_of_int x | String -> Printf.sprintf "%S" x | Pair(t1,t2) -> let (x1, x2) = x in Printf.sprintf "(%s,%s)" (to_string t1 x1) (to_string t2 x2)
Another frequent application of GADTs is equality witnesses.
type (_,_) eq = Eq : ('a,'a) eq let cast : type a b. (a,b) eq -> a -> b = fun Eq x -> x
Here type eq has only one constructor, and by matching on it one adds a local constraint allowing the conversion between a and b. By building such equality witnesses, one can make equal types which are syntactically different.
Here is an example using both singleton types and equality witnesses to implement dynamic types.
let rec eq_type : type a b. a typ -> b typ -> (a,b) eq option = fun a b -> match a, b with | Int, Int -> Some Eq | String, String -> Some Eq | Pair(a1,a2), Pair(b1,b2) -> begin match eq_type a1 b1, eq_type a2 b2 with | Some Eq, Some Eq -> Some Eq | _ -> None end | _ -> None type dyn = Dyn : 'a typ * 'a -> dyn let get_dyn : type a. a typ -> dyn -> a option = fun a (Dyn(b,x)) -> match eq_type a b with | None -> None | Some Eq -> Some x
Part III |
This chapter describes the OCaml batch compiler ocamlc, which compiles OCaml source files to bytecode object files and links 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:
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.
The output of the linking phase is a file containing compiled bytecode that can be executed by the OCaml bytecode interpreter: the command named ocamlrun. If a.out is the name of the file produced by the linking phase, the command
ocamlrun a.out arg1 arg2 … argn
executes the compiled code contained in a.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:
./a.out arg1 arg2 … argn
The produced file has the executable bit set, and it manages to launch the bytecode interpreter by itself.
The following command-line options are recognized by ocamlc. The options -pack, -a, -c and -output-obj are mutually exclusive.
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.
Unix: Never use the strip command on executables produced by ocamlc -custom, this would remove the bytecode part of the executable.
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.
ocamlc -pack -o p.cmo a.cmo b.cmo c.cmogenerates 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.
The warning-list argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:
Warning numbers and letters which are out of the range of warnings that are currently defined are ignored. The warning are as follows.
The default setting is -w +a-4-6-7-9-27-29-32..37. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.
Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error in production code, because this can break your build when future versions of OCaml add some new warnings.
The default setting is -warn-error -a (none of the warnings is treated as an error).
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.
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.
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:
type foo = A | B let f = function A -> 0 | B -> 1 type foo = C | D f C
This result in the error message “expression C of type foo cannot be used with type foo”.
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:
let sort_int_list = Sort.list (<) (* inferred type 'a list -> 'a list, with 'a not generalized *)write
let sort_int_list = (Sort.list (<) : int list -> int list);;
let map_length = List.map Array.length (* inferred type 'a array list -> int list, with 'a not generalized *)write
let map_length lv = List.map Array.length lv
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:
mod1.ml: let f x = ... Mod2.g ... mod2.ml: let g y = ... Mod1.f ...define
mod1.ml: let f g x = ... g ... mod2.ml: let rec g y = ... Mod1.f g ...and link mod1.cmo before mod2.cmo.
mod1.ml: let forward_g = ref((fun x -> failwith "forward_g") : <type>) let f x = ... !forward_g ... mod2.ml: let g y = ... Mod1.f ... let _ = Mod1.forward_g := g
This chapter describes the toplevel system for OCaml, that permits interactive use of the OCaml system through a read-eval-print loop. In this mode, the system repeatedly reads OCaml 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:
|
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.
Unix: The toplevel system is started by the command ocaml, as follows:ocaml options objects # interactive mode ocaml options objects scriptfile # script modeoptions 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 OCaml 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 OCaml 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 OCaml 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 OCaml, 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.
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 list once the toplevel is running with the #directory directive (section 9.2).
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.
- HOME
- Directory where the .ocamlinit file is searched.
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.
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.
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.
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 ocamlmktop command builds OCaml toplevels that contain user code preloaded at start-up.
The ocamlmktop command takes as argument a set of .cmo and .cma files, and links them with the object files that implement the OCaml toplevel. The typical use is:
ocamlmktop -o mytoplevel foo.cmo bar.cmo gee.cmo
This creates the bytecode file mytoplevel, containing the OCaml toplevel system, plus the code from the three .cmo files. This toplevel is directly executable and is started by:
./mytoplevel
This enters a regular toplevel loop, except that the code from foo.cmo, bar.cmo and gee.cmo is already loaded in memory, just as if you had typed:
#load "foo.cmo";; #load "bar.cmo";; #load "gee.cmo";;
on entrance to the toplevel. The modules Foo, Bar and Gee are not opened, though; you still have to do
open Foo;;
yourself, if this is what you wish.
The following command-line options are recognized by ocamlmktop.
The ocamlrun command executes bytecode files produced by the linking phase of the ocamlc command.
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 OCaml 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 a.out is a bytecode executable file,
a.out arg1 ... argn
works exactly as
ocamlrun a.out arg1 ... argn
Notice that it is not possible to pass options to ocamlrun when invoking a.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 ....
The following command-line options are recognized by ocamlrun.
The following environment variables are also consulted:
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.
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 19.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:
This section describes and explains the most frequently encountered error messages.
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.
This chapter describes the OCaml high-performance native-code compiler ocamlopt, which compiles OCaml source files to native code object files and link these object files to produce standalone executables.
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 ocamlopt with bytecode object files produced by ocamlc: 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:
The implementation is checked against the interface file x.mli (if it exists) as described in the manual for ocamlc (chapter 8).
The output of the linking phase is a regular Unix or Windows executable file. It does not need ocamlrun to run.
The following command-line options are recognized by ocamlopt. The options -pack, -a, -shared, -c and -output-obj are mutually exclusive.
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.
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.
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 32 and 64 bits under Linux, BSD and MacOS X). 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.
ocamlopt -pack -o P.cmx A.cmx B.cmx C.cmxgenerates 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.
The .cmx object files being combined must have been compiled with the appropriate -for-pack option. In the example above, A.cmx, B.cmx and C.cmx must have been compiled with ocamlopt -for-pack P.
Multiple levels of packing can be achieved by combining -pack with -for-pack. Consider the following example:
ocamlopt -for-pack P.Q -c A.ml ocamlopt -pack -o Q.cmx -for-pack P A.cmx ocamlopt -for-pack P -c B.ml ocamlopt -pack -o P.cmx Q.cmx B.cmx
The resulting P.cmx object file has sub-modules P.Q, P.Q.A and P.B.
The warning-list argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:
Warning numbers and letters which are out of the range of warnings that are currently defined are ignored. The warning are as follows.
The default setting is -w +a-4-6-7-9-27..29. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.
Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error in production code, because this can break your build when future versions of OCaml add some new warnings.
The default setting is -warn-error -a (none of the warnings is treated as an error).
The IA32 code generator (Intel Pentium, AMD Athlon) supports the following additional option:
The AMD64 code generator (64-bit versions of Intel Pentium and AMD Athlon) supports the following additional options:
The Sparc code generator supports the following additional options:
The default is to generate code for SPARC version 7, which runs on all SPARC processors.
The error messages are almost identical to those of ocamlc. See section 8.4.
Executables generated by ocamlopt are native, stand-alone executable files that can be invoked directly. They do not depend on the ocamlrun bytecode runtime system nor on dynamically-loaded C/OCaml stub libraries.
During execution of an ocamlopt-generated executable, the following environment variables are also consulted:
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.
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 OCaml 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 21.)
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.)
The following command-line options are recognized by ocamllex.
The format of lexer definitions is as follows:
{ header } let ident = regexp … rule entrypoint [arg1… argn] = parse regexp { action } | … | regexp { action } and entrypoint [arg1… argn] = parse … and … { trailer }
Comments are delimited by (* and *), as in OCaml. The parse keyword, can be replaced by the shortest keyword, with the semantic consequences explained below.
The header and trailer sections are arbitrary OCaml 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 let ident = 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 OCaml values (starting with a lowercase letter). Similarily, the arguments arg1… argn must be valid identifiers for OCaml. Each entry point becomes an OCaml 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 OCaml-like syntax.
|
Concerning the precedences of operators, # has the highest precedence, followed by *, + and ?, then concatenation, then | (alternation), then as.
The actions are arbitrary OCaml 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.
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 regexp as ident, 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 ( regexp as ident ) ? and of regexp1 | ( regexp2 as ident ).
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:
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.
All identifiers starting with __ocaml_lex are reserved for use by ocamllex; do not use any such identifier in your programs.
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 OCaml 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.
Grammar definitions have the following format:
%{ header %} declarations %% rules %% trailer
Comments are enclosed between /*
and */
(as in C) in the
“declarations” and “rules” sections, and between (*
and
*)
(as in OCaml) in the “header” and “trailer” sections.
The header and the trailer sections are OCaml 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.
Declarations are given one per line. They all start with a %
sign.
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 typexpr part
of a %token
declaration is copied to both.%type
directive below.-s
option is in effect). The typexpr part is an arbitrary OCaml
type expression, except that all type constructor names must be
fully qualified, as explained above for %token.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:
The syntax for rules is as usual:
nonterminal : symbol … symbol { semantic-action } | … | symbol … symbol { semantic-action } ;
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 OCaml 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 OCaml 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.
The ocamlyacc command recognizes the following options:
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 all-time favorite: a desk calculator. This program reads arithmetic expressions on standard input, one per line, and prints their values. Here is the grammar definition:
/* File parser.mly */ %token <int> INT %token PLUS MINUS TIMES DIV %token LPAREN RPAREN %token EOL %left PLUS MINUS /* lowest precedence */ %left TIMES DIV /* medium precedence */ %nonassoc UMINUS /* highest precedence */ %start main /* the entry point */ %type <int> main %% main: expr EOL { $1 } ; expr: INT { $1 } | LPAREN expr RPAREN { $2 } | expr PLUS expr { $1 + $3 } | expr MINUS expr { $1 - $3 } | expr TIMES expr { $1 * $3 } | expr DIV expr { $1 / $3 } | MINUS expr %prec UMINUS { - $2 } ;
Here is the definition for the corresponding lexer:
(* File lexer.mll *) { open Parser (* The type token is defined in parser.mli *) exception Eof } rule token = parse [' ' '\t'] { token lexbuf } (* skip blanks *) | ['\n' ] { EOL } | ['0'-'9']+ as lxm { INT(int_of_string lxm) } | '+' { PLUS } | '-' { MINUS } | '*' { TIMES } | '/' { DIV } | '(' { LPAREN } | ')' { RPAREN } | eof { raise Eof }
Here is the main program, that combines the parser with the lexer:
(* File calc.ml *) let _ = try let lexbuf = Lexing.from_channel stdin in while true do let result = Parser.main Lexer.token lexbuf in print_int result; print_newline(); flush stdout done with Lexer.Eof -> exit 0
To compile everything, execute:
ocamllex lexer.mll # generates lexer.ml ocamlyacc parser.mly # generates parser.ml and parser.mli ocamlc -c parser.mli ocamlc -c lexer.ml ocamlc -c parser.ml ocamlc -c calc.ml ocamlc -o calc lexer.cmo parser.cmo calc.cmo
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.
rule token = parse "keyword1" { KWD1 } | "keyword2" { KWD2 } | ... | "keyword100" { KWD100 } | ['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id { IDENT id}
To keep the generated automata small, rewrite those definitions with only one general “identifier” rule, followed by a hashtable lookup to separate keywords from identifiers:
{ let keyword_table = Hashtbl.create 53 let _ = List.iter (fun (kwd, tok) -> Hashtbl.add keyword_table kwd tok) [ "keyword1", KWD1; "keyword2", KWD2; ... "keyword100", KWD100 ] } rule token = parse ['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id { try Hashtbl.find keyword_table id with Not_found -> IDENT id }
The ocamldep command scans a set of OCaml 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.
The ocamlbuild compilation manager (see chapter 18) provide a higher-level, more automated alternative to the combination of make and ocamldep.
The following command-line options are recognized by ocamldep.
filename: Module1 Module2 ... ModuleNwhere Module1, …, ModuleN are the names of the compilation units referenced within the file filename, but these names are not resolved to source file names. Such raw dependencies cannot be used by make, but can be post-processed by other tools such as Omake.
Here is a template Makefile for a OCaml program.
OCAMLC=ocamlc OCAMLOPT=ocamlopt OCAMLDEP=ocamldep INCLUDES= # all relevant -I options here OCAMLFLAGS=$(INCLUDES) # add other options for ocamlc here OCAMLOPTFLAGS=$(INCLUDES) # add other options for ocamlopt here # prog1 should be compiled to bytecode, and is composed of three # units: mod1, mod2 and mod3. # The list of object files for prog1 PROG1_OBJS=mod1.cmo mod2.cmo mod3.cmo prog1: $(PROG1_OBJS) $(OCAMLC) -o prog1 $(OCAMLFLAGS) $(PROG1_OBJS) # prog2 should be compiled to native-code, and is composed of two # units: mod4 and mod5. # The list of object files for prog2 PROG2_OBJS=mod4.cmx mod5.cmx prog2: $(PROG2_OBJS) $(OCAMLOPT) -o prog2 $(OCAMLFLAGS) $(PROG2_OBJS) # Common rules .SUFFIXES: .ml .mli .cmo .cmi .cmx .ml.cmo: $(OCAMLC) $(OCAMLFLAGS) -c $< .mli.cmi: $(OCAMLC) $(OCAMLFLAGS) -c $< .ml.cmx: $(OCAMLOPT) $(OCAMLOPTFLAGS) -c $< # Clean up clean: rm -f prog1 prog2 rm -f *.cm[iox] # Dependencies depend: $(OCAMLDEP) $(INCLUDES) *.mli *.ml > .depend include .depend
This chapter describes OCamlBrowser, a source and compiled interface browser, written using LablTk. This is a useful companion to the programmer.
Its functions are:
The browser is started by the command ocamlbrowser, as follows:
ocamlbrowser options
The following command-line options are recognized by ocamlbrowser.
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.
This is the first window you get when you start OCamlBrowser. It displays a search window, and the list of modules in the load path. At the top a row of menus.
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.
Control-S lets you search a string in the signature.
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.
After typechecking, pressing the right button pops up a menu that gives the type of the pointed expression and, where applicable, provides some links that can be followed.
When you create a shell, a dialog is presented to you, letting you choose which command you want to run, and the title of the shell (to choose it in the Editor).
The executed subshell is given the current load path.
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.
OCamldoc is invoked via the command ocamldoc, as follows:
ocamldoc options sourcefiles
The following options determine the format for the generated documentation.
OCamldoc calls the OCaml type-checker to obtain type information. The following options impact the type-checking phase. They have the same meaning as for the ocamlc and ocamlopt commands.
The following options apply in conjunction with the -html option:
The following options apply in conjunction with the -latex option:
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.
The following options apply in conjunction with the -texi option:
The following options apply in conjunction with the -dot option:
The following options apply in conjunction with the -man option:
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:
The following rules must be respected in order to avoid name clashes resulting in cross-reference errors:
open Foo (* which has a module Bar with a value x *) module Foo = struct module Bar = struct let x = 1 end end let dummy = Bar.xIn this case, OCamldoc will associate Bar.x to the x of module Foo defined just above, instead of to the Bar.x defined in the opened module Foo.
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.
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 :
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 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 special comment for a constructor with another constructor following must be placed before the ’|’ character separating the two constructors.
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
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 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 special comment for a constructor with another constructor following must be placed before the ’|’ character separating the two constructors.
The following example of file toto.ml shows where to place comments in a .ml file.
(** The first special comment of the file is the comment associated to the whole module. *) (** The comment for function f *) let f x y = x + y (** This comment is not attached to any element since there is another special comment just before the next element. *) (** Comment for exception My_exception, even with a simple comment between the special comment and the exception.*) (* A simple comment. *) exception My_exception of (int -> int) * int (** Comment for type weather *) type weather = | Rain of int (** The comment for constructor Rain *) | Sun (** The comment for constructor Sun *) (** The comment for type my_record *) type my_record = { val foo : int ; (** Comment for field foo *) val bar : string ; (** Comment for field bar *) } (** The comment for class my_class *) class my_class = object (** A comment to describe inheritance from cl *) inherit cl (** The comment for the instance variable tutu *) val mutable tutu = "tutu" (** The comment for toto *) val toto = 1 val titi = "titi" (** Comment for method toto *) method toto = tutu ^ "!" (** Comment for method m *) method m (f : float) = 1 end (** The comment for class type my_class_type *) class type my_class_type = object (** The comment for the instance 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 in the class, but not associated to any element. *) end (** The comment for module type my_module_type. *) module type my_module_type = sig (* Comment for value x. *) val x : int (* ... *) end
The special comment (**/**) tells OCamldoc to discard elements placed after this comment, up to the end of the current class, class type, module or module type, or up to the next stop comment. For instance:
class type foo = object (** comment for method m *) method m : string (**/**) (** This method won't appear in the documentation *) method bar : int end (** This value appears in the documentation, since the Stop special comment in the class does not affect the parent module of the class.*) val foo : string (**/**) (** The value bar does not appear in the documentation.*) val bar : string (**/**) (** The type t appears since in the documentation since the previous stop comment toggled off the "no documentation mode". *) type t = string
The -no-stop option to ocamldoc causes the Stop special comments to be ignored.
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.
At last, (**) is the empty documentation comment.
Here is the BNF grammar for the simple markup language used to format text descriptions.
|
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 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 : string } 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 ’\’ |
∣ | blank-line | force a new line. |
|
A shortcut syntax exists for lists and enumerated lists:
(** Here is a {b list} - item 1 - item 2 - item 3 The list is ended by the blank line.*)
is equivalent to:
(** Here is a {b list} {ul {- item 1} {- item 2} {- item 3}} The list is ended by the blank line.*)
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
outside of the following text formatting : {ul list } , {ol list } , [ string ] , {[ string ]} , {v string v} , {% string %} , {! string } , {^ text } , {_ text } .
The following table gives the list of predefined @-tags, with their
syntax and meaning.
@author string | The author of the element. One author per @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 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 | Indicate when the element was introduced. |
@before version text | Associate the given description (text) to the given version in order to document compatibility issues. |
@version string | The version number for the element. |
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.
OCamldoc operates in two steps:
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 use to define custom generators are installed in the ocamldoc sub-directory of the OCaml standard library.
The type of a generator module depends on the kind of generated documentation. Here is the list of generator module types, with the name of the generator class in the module :
That is, to define a new generator, one must implement a module with the expected signature, and with the given generator class, providing the generate method as entry point to make the generator generates documentation for a given list of modules :
method generate : 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.
It is recommanded to inherit from the current generator of the same kind as the one you want to define. Doing so, it is possible to load various custom generators to combine improvments brought by each one.
This is done using first class modules (see chapter 7.14).
The easiest way to define a custom generator is the following this example, here extending the current HTML generator. We don’t have to know if this is the original HTML generator defined in ocamldoc or if it has been extended already by a previously loaded custom generator :
module Generator (G : Odoc_html.Html_generator) = struct class html = object(self) inherit G.html as html (* ... *) method generate module_list = (* ... *) () (* ... *) end end;; let _ = Odoc_args.extend_generator (module Generator : Odoc_gen.Html_functor);;
To know which methods to override and/or which methods are available, have a look at the different base implementations, depending on the kind of generator you are extending :
Making a custom generator handle custom tags (see 15.2.5) is very simple.
Here is how to develop a HTML generator handling your custom tags.
The class Odoc_html.Generator.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, extend the current HTML generator and complete the tag_functions field:
module Generator (G : Odoc_html.Html_generator) = struct class html = object(self) inherit G.html (** Return HTML code for the given text of a bar tag. *) method html_of_bar t = (* your code here *) initializer tag_functions <- ("bar", self#html_of_bar) :: tag_functions end end let _ = Odoc_args.extend_generator (module Generator : Odoc_gen.Html_functor);;
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.
You can act the same way for other kinds of generators.
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 function
Odoc_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.
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.
This chapter describes the OCaml source-level replay debugger ocamldebug.
Unix: The debugger is available on Unix systems that provide BSD sockets.
Windows: The debugger is available under the Cygwin port of OCaml, but not under the native Win32 ports.
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.
The OCaml debugger is invoked by running the program ocamldebug with the name of the bytecode executable file as first argument:
ocamldebug [options] program [arguments]
The arguments following program are optional, and are passed as command-line arguments to the program being debugged. (See also the set arguments command.)
The following command-line options are recognized:
The command quit exits the debugger. You can also exit the debugger by typing an end-of-file character (usually ctrl-D).
Typing an interrupt character (usually ctrl-C) will not exit the debugger, but will terminate the action of any debugger command that is in progress and return to the debugger command level.
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.
The OCaml debugger has a simple on-line help system, which gives a brief description of each command and variable.
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:
(f arg)§§
fun x y z -> §§ ...
function pat1 -> §§ expr1 | ... | patN -> §§ exprN
expr1; §§ expr2; §§ ...; §§ exprN
if cond then §§ expr1 else §§ expr2
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:
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).
The following commands execute the program forward or backward, starting at the current time. The execution will stop either when specified by the command or when a breakpoint is encountered.
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.
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).
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.
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 OCaml expressions, as described by the following grammar:
|
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.
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 loadingmode variable controls how the program is executed.
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.
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.
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.
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.
The following commands display information on checkpoints and events:
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.
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 OCaml support.
The OCaml 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:
In all buffers in OCaml editing mode, the following debugger commands are also available:
This chapter describes how the execution of OCaml programs can be profiled, by recording how many times functions are called, branches of conditionals are taken, …
Before profiling an execution, the program must be compiled in profiling mode, using the ocamlcp front-end to the ocamlc compiler (see chapter 8) or the ocamloptp front-end to the ocamlopt compiler (see chapter 11). When compiling modules separately, ocamlcp or ocamloptp must be used when compiling the modules (production of .cmo or .cmx files), and can also be used (though this is not strictly necessary) when linking them together.
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. The same problem exists with ocamloptp.
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 or ocamloptp, followed by one or several letters indicating which parts of the program should be profiled:
For instance, compiling with ocamlcp -P film profiles function calls, if…then…else…, loops and pattern matching.
Calling ocamlcp or ocamloptp without the -P option defaults to -P fm, meaning that only function calls and pattern matching are profiled.
For compatibility with previous releases, ocamlcp also accepts the -p option, with the same arguments and behaviour as -P.
The ocamlcp and ocamloptp commands also accept all the options of the corresponding ocamlc or ocamlopt compiler, except the -pp (preprocessing) option.
Running an executable that has been compiled with ocamlcp or ocamloptp records the execution counts for the specified parts of the program and saves them in a file called ocamlprof.dump in the current directory.
If the environment variable OCAMLPROF_DUMP is set when the program exits, its value is used as the file name instead of ocamlprof.dump.
The 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. Note that dump files produced by byte-code executables (compiled with ocamlcp) are compatible with the dump files produced by native executables (compiled with ocamloptp).
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 after it was compiled.
The following options are recognized by ocamlprof:
Profiling with ocamlprof only records execution counts, not the actual time spent within 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
OCaml 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 OCaml 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 ports of ocamlopt under Linux, BSD and MacOS X 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.
The ocamloptp command also accepts the -p option. In that case, both kinds of profiling are performed by the program, and you can display the results with the gprof and ocamlprof commands, respectively.
(Chapter written by Berke Durak and Nicolas Pouillard)
ocamlbuild is a tool automating the compilation of most OCaml projects with minimal user input. Its use is not restricted to projects having a simple structure – the extra effort needed to make it work with the more complex projects is in reasonable proportion with their added complexity. In practice, one will use a set of small text files, and, if needed, an OCaml compilation module that can fine-tune the behaviour and define custom rules.
This section is intended to read like a sales brochure or a datasheet.
Not perfect nor complete yet, but already pretty damn useful.
We were not expecting to write the ultimate compilation tool in a few man-months, however we believe we have a tool that solves many compilation problems, especially our own, in a satisfactory way. Hence there are a lot of missing features, incomplete options and hideous bugs lurking in ocamlbuild, and we hope that the OCaml community will find our first try at ocamlbuild useful and hopefully help it grow into a tool that satisfies most needs of most users by providing feedback, bug reports and patches.
The plugin API maybe somewhat lacking in maturity, as it has only been tested by a few people. We believe a good API can only evolve under pressure from many peers and the courage to rewrite things cleanly when time is ripe by the developers. Most of the important functions a user will need are encapsulated in the plugin API, which is the Ocamlbuild_plugin module pack. We intend to keep that API backwards compatible. It may happen that intricate projects need features not available in that module – you may then use functions or values directly from the core ocamlbuild modules. We ask you to report such usage to the authors so that we may make the necessary changes to the API; you may also want to isolate calls to the non-API parts of the ocamlbuild library from the rest of your plugin to be able to keep the later when incompatible changes arise.
The way that ocamlbuild handles the command-line options, the _tags file, the target names, names of the tags, and so on, are not expected to change in incompatible ways. We intend to keep a project that compiles without a plugin compilable without modifications in the future.
Learn how to use ocamlbuild with short, specific, straight-to-the-point examples.
The amount of time and effort spent on the compilation process of a project should be proportionate to that spent on the project itself. It should be easy to set up a small project, maybe a little harder for a medium-sized project, and it may take some more time, but not too much, for a big project. Ideally setting up a big project would be as easy as setting up a small project. However, as projects grow, modularization techniques start to be used, and the probability of using meta programming or multiple programming languages increases, thus making the compilation process more delicate.
ocamlbuild is intended to be very easy to use for projects, large or small, with a simple compilation process: typing ocamlbuild foo.native should be enough to compile the native version of a program whose top module is foo.ml and whose dependencies are in the same directory. As your project gets more complex, you will gradually start to use command-line options to specify libraries to link with, then configuration files, ultimately culminating in a custom OCaml plugin for complex projects with arbitrary dependencies and actions.
Your code is in the _build directory, but ocamlbuild automatically creates a symbolic link to the executables it produces in the current directory. ocamlbuild copies the source files and compiles them in a separate directory which is _build by default.
For ocamlbuild, any file that is not in the build directory is a source file. It is not unreasonable to think that some users may have bought binary object files they keep in their project directory. Usually binary files cluttering the project directory are due to previous builds using other systems. ocamlbuild has so-called “hygiene” rules that state that object files (.cmo, .cmi, or .o files, for instance) must not appear outside of the build directory. These rules are enforced at startup; any violations will be reported and ocamlbuild will exit. You must then remove these files by hand or run, with caution, the script sanitize.sh, which is generated in your source directory. This script will contain commands to remove them for you.
To disable these checks, you can use the -no-hygiene flag. If you have files that must elude the hygiene squad, just tag them with precious or not_hygienic.
Assuming we are in a directory named example1 containing one file hello.ml whose contents are
let _ = Printf.printf "Hello, %s ! My name is %s\n" (if Array.length Sys.argv > 1 then Sys.argv.(1) else "stranger") Sys.argv.(0) ;;
we can compile and link it into a native executable by invoking ocamlbuild hello.native. Here, hello is the basename of the top-level module and native is an extension used by ocamlbuild to denote native code executables.
% ls hello.ml % ocamlbuild hello.native Finished, 4 targets (0 cached) in 00:00:00. % ls -l total 12 drwxrwx— 2 linus gallium 4096 2007-01-17 16:24 _build/ -rw-rw—- 1 linus gallium 43 2007-01-17 16:23 hello.ml lrwxrwxrwx 1 linus gallium 19 2007-01-17 16:24 hello.native -> _build/hello.native*
What’s this funny _build directory ? Well that’s where ocamlbuild does its dirty work of compiling. You usually won’t have to look very often into this directory. Source files are copied into _build and this is where the compilers will be run. Various cache files are also stored there. Its contents may look like this:
% ls -l _build total 208 -rw-rw—- 1 linus gallium 337 2007-01-17 16:24 _digests -rw-rw—- 1 linus gallium 191 2007-01-17 16:24 hello.cmi -rw-rw—- 1 linus gallium 262 2007-01-17 16:24 hello.cmo -rw-rw—- 1 linus gallium 225 2007-01-17 16:24 hello.cmx -rw-rw—- 1 linus gallium 43 2007-01-17 16:23 hello.ml -rw-rw—- 1 linus gallium 17 2007-01-17 16:24 hello.ml.depends -rwxrwx— 1 linus gallium 173528 2007-01-17 16:24 hello.native* -rw-rw—- 1 linus gallium 936 2007-01-17 16:24 hello.o -rw-rw—- 1 linus gallium 22 2007-01-17 16:24 ocamlc.where
You can execute your code the old-fashioned way (./hello.native). You may also type
ocamlbuild hello.native – Caesar
and it will compile and then run hello.native with the arguments following --, which should display:
% ocamlbuild hello.native – Caesar Finished, 4 targets (0 cached) in 00:00:00. Hello, Caesar ! My name is _build/hello.native
By default, if you run ocamlbuild on a terminal, it will use some ANSI escape sequences to display a nice, one-line progress indicator. To see what commands ocamlbuild has actually run, you can check the contents of the _build/_log file. To change the name of the log file or to disable logging, use the -log <file> or -no-log options. Note that the log file is truncated at each execution of ocamlbuild.
The log file contains all the external commands that ocamlbuild ran or intended to run along with the target name and the computed tags. With the -verbose <level> option, ocamlbuild will also write more or less useful debugging information; a verbosity level of 1 (which can also be specified using the -verbose switch) prints generally useful information; higher levels produce much more output.
ocamlbuild may leave a _build directory and symbolic links to executables in that directory (unless when using -no-links). All of these can be removed safely by hand, or by invoking ocamlbuild with the -clean flag.
An important point is that ocamlbuild must be invoked from the root of the project, even if this project has multiple, nested subdirectories. This is because ocamlbuild likes to store the object files in a single _build directory. You can change the name of that directory with the -build-dir option.
ocamlbuild can be either invoked manually from the UNIX or Windows shell, or automatically from a build script or a Makefile. Unless run with the -no-hygiene option, there is the possibility that ocamlbuild will prompt the user for a response. By default, on UNIX systems, if ocamlbuild senses that the standard output is a terminal, it will use a nice progress indicator using ANSI codes, instrumenting the output of the processes it spawns to have a consistent display. Under non-UNIX systems, or if the standard output is not a terminal, it will run in classic mode where it will echo the executed commands on its standard output. This selection can be overridden with the -classic-display option.
Dependencies are automatically discovered.
Most of the value of ocamlbuild lies in the fact that it often needs no extra information to compile a project besides the name of the top-level module. ocamlbuild calls ocamldep to automatically find the dependencies of any modules it wants to compile. These dependencies are dynamically incorporated in the dependency graph, something make cannot do. For instance, let’s add a module Greet that implements various ways of greeting people.
% cat greet.ml type how = Nicely | Badly;; let greet how who = match how with Nicely -> Printf.printf "Hello, %s !\n" who | Badly -> Printf.printf "Oh, here is that %s again.\n" who ;; % cat hello.ml open Greet let _ = let name = if Array.length Sys.argv > 1 then Sys.argv.(1) else "stranger" in greet (if name = "Caesar" then Nicely else Badly) name; Printf.printf "My name is %s\n" Sys.argv.(0) ;;
Then the module Hello depends on the module Greet and ocamlbuild can figure this out for himself – we still only have to invoke ocamlbuild hello.native. Needless to say, this works for any number of modules.
If we want to compile byte-code instead of native, we just a target name of hello.byte instead of hello.native, i.e., we type ocamlbuild hello.byte.
To pass a flag to the compiler, such as the -rectypes option, use the -cflag option as in:
ocamlbuild -cflag -rectypes hello.native
You can put multiple -cflag options, they will be passed to the compiler in the same order. You can also give them in a comma-separated list with the -cflags option (notice the plural):
ocamlbuild -cflags -I,+lablgtk,-rectypes hello.native
These flags apply when compiling, that is, when producing .cmi, .cmo,.cmx and .o files from .ml or .mli files.
Link flags apply when the various object files are collected and linked into one executable. These will typically be include directories for libraries. They are given using the -lflag and -lflags options, which work in the same way as the -cflag and -cflags options.
In our third example, we use one Unix system call and functions from the num library:
% cat epoch.ml let _ = let s = Num.num_of_string (Printf.sprintf "%.0f" (Unix.gettimeofday ())) in let ps = Num.mult_num (Num.num_of_string "1000000000000") s in Printf.printf "%s picoseconds have passed since January 1st, 1970.\n" (Num.string_of_num ps) ;;
This requires linking with the unix and num modules, which is accomplished by using the -lib unix and -lib num flags, or, alternatively, -libs unix,num:
% ocamlbuild -libs nums,unix epoch.native – Finished, 4 targets (4 cached) in 00:00:00. 1169051647000000000000 picoseconds have passed since January 1st, 1970.
You may need to add options such as -cflags -I,/usr/local/lib/ocaml/ and -lflags -I,/usr/local/lib/ocaml/ if the libraries you wish to link with are not in OCaml’s default search path.
Finer control over the compiler flags applied to each source file, such as preprocessing, debugging, profiling and linking options, can be gained using ocamlbuild’s tagging mechanism.
Every source file has a set of tags which tells ocamlbuild what kind of file it is and what to do with it. A tag is simply a string, usually lowercase, for example ocaml or native. The set of tags attached to a file is computed by applying the tagging rules to the filename. Tagging rules are defined in _tags files in any parent directory of a file, up to the main project directory.
Each line in the _tags file is made of a glob pattern (see subsection 18.3.13) and a list of tags. More than one rule can apply to a file and rules are applied in the order in which they appear in a file. By preceding a tag with a minus sign, one may remove tags from one or more files.
<**/*.ml> or <**/*.mli> or <**/*.mlpack> or <**/*.ml.depends>: ocaml <**/*.byte>: ocaml, byte, program <**/*.odoc>: ocaml, doc <**/*.native>: ocaml, native, program <**/*.cma>: ocaml, byte, library <**/*.cmxa>: ocaml, native, library <**/*.cmo>: ocaml, byte <**/*.cmi>: ocaml, byte, native <**/*.cmx>: ocaml, native
Two special tags made from the path name of the file relative to the toplevel of the project are automatically defined for each file. For a file foo/bar.ml those tags will be file:foo/bar.ml, and extension:ml.
If you do not have subdirectories, you can put *.ml instead of **/*.ml.
Glob patterns have a syntax similar to those used by UNIX shells to select path names (like foo_*.ba?). They are used in ocamlbuild to define the files and directories to which tags apply. Glob expressions are glob patterns enclosed in brackets < and > combined using the standard boolean operators and, or, not. This allows one to describe sets of path names in more concise and more readable ways.
Please note that file and directory names are supposed to be made of the following characters: a, …, z, A, …, Z, 0, …, 9, _, - and .. This is called the pathname alphabet P.
Formal syntax Example Matches Does not match Meaning (formal meaning) u
A string of pathname charactersfoo.ml foo.ml fo.ml, bar/foo.ml The exact string u ({ u }, where u ∈ P*) *
The wild-card star* ε, foo, bar foo/bar, /bar Any string not containing a slash (P*) ?
The joker? a, b, z /, bar Any one-letter string, excluding the slash **/
The prefix inter-directory star**/foo.ml foo.ml, bar/foo.ml, bar/baz/foo.ml foo/bar, /bar The empty string, or any string ending with a slash (ε ∪ P*/) /**
The suffix inter-directory starfoo/** foo, foo/bar bar/foo Any string starting with a slash, or the empty string (ε ∪ /P*) /**/
The infix inter-directory starbar/**/foo.ml bar/foo.ml, bar/baz/foo.ml foo.ml Any string starting and ending with a slash (ε ∪ /P*/) [ r1 r2 ⋯ rk ] where ri is either c or c1−c2 (1 ≤ i ≤ k)
The positive character class[a-fA-F0-9_.] 3, F, . z, bar Any one-letter string made of characters from one of the ranges ri (1 ≤ i ≤ n). (L(r1) ∪ ⋯ ∪ L(rn)) [^r1 r2 ⋯ rk ] where ri is either c or c1−c2 (1 ≤ i ≤ k)
The negative character class[^a-fA-F0-9_.] z, bar 3, F, . Any one-letter string NOT made of characters from one of the ranges ri (1 ≤ i ≤ n). (Σ* ∖ (L(r1) ∪ ⋯ ∪ L(rn))) p1 p2
A concatenation of patternsfoo* foo, foob, foobar fo, bar Any string with a prefix matching p1 and the corresponding suffix matching p2, ({ uv ∣ u ∈ L(p1), v ∈ L(p2) }) { p1 , p2 , ⋯ , pk }
A union of patternstoto.{ml,mli} toto.ml, toto.mli toto. Any string matching one of the patterns pi for 1 ≤ i ≤ k. (L(p1) ∪ ⋯ ∪ L(pk))
Formal syntax Example Meaning (formal meaning) <p> <foo.ml> Pathnames matching the pattern p e1 or e2 <*.ml> or <foo/bar.ml> Pathnames matching at least one of the expressions e1 and e2 e1 and e2 <*.ml> and <foo_*> Pathnames matching both expressions e1 and e2 not e not <*.mli> Pathnames not matching the expression e true true All pathnames false false No pathnames
If the files of your project are held in one or more subdirectories, ocamlbuild must be made aware of that fact using the -I or -Is options or by adding an include tag. For instance, assume your project is made of three subdirectories, foo, bar and baz containing various .ml files, the main file being foo/main.ml. Then you can either type:
% ocamlbuild -Is foo,bar,baz foo/main.native
or add the following line in the _tags file
<foo> or <bar> or <baz>: include
and call
% ocamlbuild foo/main.native
There are then two cases. If no other modules named Bar or Baz exist elsewhere in the project, then you are done. Just use Foo, Foo.Bar and Foo.Baz in your code. Otherwise, you will need to use the plugin mechanism and define the mutual visibility of the subdirectories using the Pathname.define_context function.
ocamlbuild used to traverse by default any subdirectory not explicitly excluded. This is no longer the case. Note that you can still have a fine grained control using your _tags file and the traverse tag.
There is no longer the true: traverse tag declaration by default. To make ocamlbuild recursive use one of these:
You can create a file named foo.itarget containing a list of targets, one per line, such as
main.native main.byte stuff.docdir/index.html
Requesting the target foo.otarget will then build every target listed in the file foo.itarget. Blank lines and lines starting with a sharp (#) are ignored.
OCaml’s -pack option allows you to structure the contents of a module in a subdirectory. For instance, assume you have a directory foo containing two modules bar.ml and baz.ml. You want from these to build a module Foo containing Bar and Baz as submodules. In the case where no modules named Bar or Baz exist outside of Foo, to do this you must write a file foo.mlpack, preferably sitting in the same directory as the directory Foo and containing the list of modules (one per line) it must contain:
Bar Baz
Then when you will request for building foo.cmo the package will be made from bar.cmo and baz.cmo.
In a similar way than for packaged modules you can make a library by putting it’s contents in a file (with the mllib extension). For instance, assume you have a two modules bar.ml and baz.ml. You want from these to build a library foo.cmx?a containing Bar and Baz modules. To do this you must write a file foo.mllib containing the list of modules (one per line) it must contain:
Bar Baz
Then when you will request for building foo.cma the library will be made from bar.cmo and baz.cmo.
Making a toplevel is almost the same thing than making a packaged module or a library. Just write a file with the mltop extension (like foo.mltop) and request for building the toplevel using the top extension (foo.top in this example).
You can specify preprocessor options with -pp followed by the preprocessor string, for instance ocamlbuild -pp camlp4o.opt -unsafe would run your sources through CamlP4 with the -unsafe option. Another way is to use the tags file.
Tag | Preprocessor command | Remark |
pp(cmd...) | cmd... | Arbitrary preprocessor command1 |
camlp4o | camlp4o | Original OCaml syntax |
camlp4r | camlp4r | Revised OCaml syntax |
camlp4of | camlp4of | Original OCaml syntax with extensions |
camlp4rf | camlp4rf | Revised OCaml syntax with extensions |
The preferred way of compiling code suitable for debugging with ocamldebug or profiling native code with ocamlprof is to use the appropriate target extensions, .d.byte for debugging or .p.native.
Another way is to add use the debug or profile tags. Note that these tags must be applied at the compilation and linking stages. Hence you must either use -tag debug or -tag profile on the command line, or add a
true: debug
line to your _tags file. Please note that the byte-code profiler works in a wholly different way and is not supported by ocamlbuild.
Write the names of the modules whose interfaces will be documented in a file whose extension is .odocl, for example foo.odocl, then invoke ocamlbuild on the target foo.docdir/index.html. This will collect all the documentation from the interfaces (which will be build, if necessary) using ocamldoc and generate a set of HTML files under the directory foo.docdir/, which is actually a link to _build/foo.docdir/. As for packing subdirectories into modules, the module names must be written one per line, without extensions and correctly capitalized. Note that generating documentation in formats other than HTML or from implementations is not supported.
Provided ocamlbuild runs in a terminal under a POSIX environment, it will display a sophisticated progress-indicator line that graciously interacts with the output of subcommands. This line looks like this:
00:00:02 210 (180 ) main.cmx ONbp–il /
Here, 00:00:02 is the elapsed time in hour:minute:second format since ocamlbuild has been invoked; 210 is the number of external commands, typically calls to the compiler or the like, that may or may not have been invoked; 180 is the number of external commands that have not been invoked since their result is already in the build directory; main.cmx is the name of the last target built; ONbp--il is a short string that describes the tags that have been encountered and the slash at the end is a frame from a rotating ticker. Hence, the display line has the following structure:
HH:MM:SS JOBS (CACHED) PATHNAME TAGS TICKER
The tag string is made of 8 indicators which each monitor a tag. These tags are ocaml, native, byte, program, pp, debug, interf and link. Initially, each indicator displays a dash -. If the current target has the monitored tag, then the indicator displays the corresponding character (see table 18.3) in uppercase. Otherwise, it displays that character in lowercase. This allows you to see the set of tags that have been applied to files in your project during the current invocation of ocamlbuild.
Hence the tag string ONbp--il means that the current target main.cmx has the tags ocaml and native, and that the tags ocaml, native, byte, program, interf and link have already been seen.
Tag Display character ocaml O native N byte B program P pp R debug D interf I link L
ocamlbuild knows how to run the standard lexer and parser generator tools ocamllex and ocamlyacc when your files have the standard .mll and .mly extensions. If you want to use menhir instead of ocamlyacc, you can either launch ocamlbuild with the -use-menhir option or add a
true: use_menhir
line to your _tags file. Note that there is currently no way of using menhir and ocamlyacc in the same execution of ocamlbuild.
As ocamlbuild is part of your OCaml distribution, it knows if it can call the native compilers and tools (ocamlc.opt, ocamlopt.opt...) or not. However you may want ocamlbuild to use another ocaml compiler for different reasons (such as cross-compiling or using a wrapper such as ocamlfind). Here is the list of relevant options:
Here are tips for configuring your version control system to ignore the files and directories generated by ocamlbuild.
The directory _build and any symbolic links pointing into _build should be ignored. To do this, you must add the following ignore patterns to your version control system’s ignore set:
_build *.native *.byte *.d.native *.p.byte
For CVS, add the above lines to the .cvsignore file. For Subversion (SVN), type svn propedit svn:ignore . and add the above lines.
To shell or to make ? Traditionally, makefiles have two major functions. The first one is the dependency-ordering, rule-matching logic used for compiling. The second one is as a dispatcher for various actions defined using phony targets with shell script actions. These actions include cleaning, cleaning really well, archiving, uploading and so on. Their characteristic is that they rely little or not on the building process – they either need the building to have been completed, or they don’t need anything. As /bin/sh scripts have been here for three to four decades and are not going anywhere, why not replace that functionality of makefiles with a shell script ? We have thought of three bad reasons:
We also have bad reasons for not using an OCaml script to drive everything:
Anyway you are of course free to use a makefile or an OCaml script to call ocamlbuild. Here is an example shell driver script:
#!/bin/sh set -e TARGET=epoch FLAGS="-libs unix,nums" OCAMLBUILD=ocamlbuild ocb() { $OCAMLBUILD $FLAGS $* } rule() { case $1 in clean) ocb -clean;; native) ocb $TARGET.native;; byte) ocb $TARGET.byte;; all) ocb $TARGET.native $TARGET.byte;; depend) echo "Not needed.";; *) echo "Unknown action $1";; esac; } if [ $# -eq 0 ]; then rule all else while [ $# -gt 0 ]; do rule $1; shift done fi
This inflammatory appendix describes the frustration that led us to write ocamlbuild.
Many people have painfully found that the utilities of the make family, namely GNU Make, BSD Make, and their derivatives, fail to scale to large projects, especially when using multi-stage compilation rules, such as custom pre-processors, unless dependencies are hand-defined. But as your project gets larger, more modular, and uses more diverse pre-processing tools, it becomes increasingly difficult to correctly define dependencies by hand. Hence people tend to use language-specific tools that attempt to extract dependencies. However another problem then appears: make was designed with the idea of a static dependency graph. Dependency extracting tools, however, are typically run by a rule in make itself; this means that make has to reload the dependency information. This is the origin of the make clean; make depend; make mantra. This approach tends to work quite well as long as all the files sit in a single directory and there is only one stage of pre-processing. If there are two or more stages, then dependency extracting tools must be run two or more times - and this means multiple invocations of make. Also, if one distributes the modules of a large project into multiple subdirectories, it becomes difficult to distribute the makefiles themselves, because the language of make was not conceived to be modular; the only two mechanisms permitted, inclusion of makefile fragments, and invocation of other make instances, must be skillfully coordinated with phony target names (depend1, depend2...) to insure inclusion of generated dependencies with multi-stage programming; changes in the structure of the project must be reflected by hand and the order of variable definitions must be well-thought ahead to avoid long afternoons spent combinatorially fiddling makefiles until it works but no one understands why.
These problems become especially apparent with OCaml: to ensure type safety and to allow a small amount of cross-unit optimization when compiling native code, interface and object files include cryptographical digests of interfaces they are to be linked with. This means that linking is safer, but that makefile sloppiness leads to messages such as:
Files foo.cmo and bar.cmo make inconsistent assumptions over interface Bar
The typical reaction is then to issue the mantra make clean; make depend; make and everything compiles just fine... from the beginning. Hence on medium projects, the programmer often has to wait for minutes instead of the few seconds that would be taken if make could correctly guess the small number of files that really had to be recompiled.
It is not surprising that hacking a build tool such as make to include a programming language while retaining the original syntax and semantics gives an improvised and cumbersome macro language of dubious expressive power. For example, using GNU make, suppose you have a list of .mls that you want to convert into a list including both .cmos and .cmis, that is you want to transform a.ml b.ml c.ml into a.cmi a.cmo b.cmi b.cmo c.cmi c.cmo while preserving the dependency order which must be hand specified for linking 2. Unfortunately $patsubst %.ml, %.cmi %.cmo, a.ml b.ml c.ml won’t work since the %-sign in the right-hand of a patsubst gets substituted only once. You then have to delve into something that is hardly lambda calculus: an intricate network of foreach, eval, call and defines may get you the job done, unless you chicken out and opt for an external awk, sed or perl call. People who at this point have not lost their temper or sanity usually resort to metaprogramming by writing Makefile generators using a mixture of shell and m4. One such an attempt gave something that is the nightmare of wannabe package maintainers: it’s called autotools.
Note that it is also difficult to write Makefiles to build object files in a separate directory. It is not impossible since the language of make is Turing-complete, a proof of which is left as an exercise. Note that building things in a separate directory is not necessarily a young enthusiast’s way of giving a different look and feel to his projects – it may be a good way of telling the computer that foo.mli is generated by ocamlyacc using foo.mly and can thus be removed.
The contents of this table give a summary of the most important default rules. To get the most accurate and up-to-date information, launch ocamlbuild with the -documentation option.
Tags | Dependencies | Targets |
%.itarget | %.otarget | |
ocaml | %.mli %.mli.depends | %.cmi |
byte, debug, ocaml | %.mlpack %.cmi | %.d.cmo |
byte, ocaml | %.mlpack | %.cmo %.cmi |
byte, ocaml | %.mli %.ml %.ml.depends %.cmi | %.d.cmo |
byte, ocaml | %.mli %.ml %.ml.depends %.cmi | %.cmo |
native, ocaml, profile | %.mlpack %.cmi | %.p.cmx %.p.o |
native, ocaml | %.mlpack %.cmi | %.cmx %.o |
native, ocaml, profile | %.ml %.ml.depends %.cmi | %.p.cmx %.p.o |
native, ocaml | %.ml %.ml.depends %.cmi | %.cmx %.o |
debug, ocaml | %.ml %.ml.depends %.cmi | %.d.cmo |
ocaml | %.ml %.ml.depends | %.cmo %.cmi |
byte, debug, ocaml, program | %.d.cmo | %.d.byte |
byte, ocaml, program | %.cmo | %.byte |
native, ocaml, profile, program | %.p.cmx %.p.o | %.p.native |
native, ocaml, program | %.cmx %.o | %.native |
byte, debug, library, ocaml | %.mllib | %.d.cma |
byte, library, ocaml | %.mllib | %.cma |
byte, debug, library, ocaml | %.d.cmo | %.d.cma |
byte, library, ocaml | %.cmo | %.cma |
lib%(libname).clib | lib%(libname).a dll%(libname).so | |
%(path)/lib%(libname).clib | %(path)/lib%(libname).a %(path)/dll%(libname).so | |
library, native, ocaml, profile | %.mllib | %.p.cmxa %.p.a |
library, native, ocaml | %.mllib | %.cmxa %.a |
library, native, ocaml, profile | %.p.cmx %.p.o | %.p.cmxa %.p.a |
library, native, ocaml | %.cmx %.o | %.cmxa %.a |
%.ml | %.ml.depends | |
%.mli | %.mli.depends | |
ocaml | %.mll | %.ml |
doc, ocaml | %.mli %.mli.depends | %.odoc |
%.odocl | %.docdir/index.html | |
ocaml | %.mly | %.ml %.mli |
%.c | %.o | |
%.ml %.ml.depends | %.inferred.mli |
This chapter describes how user-defined primitives, written in C, can be linked with OCaml code and called from OCaml functions.
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 OCaml function.
The arity (number of arguments) of a primitive is automatically determined from its OCaml 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 OCaml values).
Type abbreviations are not expanded when determining the arity of a primitive. For instance,
type int_endo = int -> int external f : int_endo -> int_endo = "f" external g : (int -> int) -> (int -> int) = "f"
f has arity 1, but g has arity 2. This allows a primitive to return a functional value (as in the f example above): just remember to name the functional return type in a type abbreviation.
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 OCaml values. It encodes objects of several base types (integers, floating-point numbers, strings, …), as well as OCaml 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:
CAMLprim value input(value channel, value buffer, value offset, value length) { ... }
When the primitive function is applied in an OCaml 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 OCaml 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 OCaml 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:
CAMLprim value add_nat_native(value nat1, value ofs1, value len1, value nat2, value ofs2, value len2, value carry_in) { ... } CAMLprim value add_nat_bytecode(value * argv, int argn) { return add_nat_native(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]); }
The names of the two C functions must be given in the primitive declaration, as follows:
external name : type = bytecode-C-function-name native-code-C-function-name
For instance, in the case of add_nat, the declaration is:
external add_nat: nat -> int -> int -> nat -> int -> int -> int -> int = "add_nat_bytecode" "add_nat_native"
Implementing a user primitive is actually two separate tasks: on the one hand, decoding the arguments to extract C values from the given OCaml values, and encoding the return value as an OCaml 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 OCaml values to C values, call the first function, and convert the returned C value to OCaml value. For instance, here is the stub code for the input primitive:
CAMLprim value input(value channel, value buffer, value offset, value length) { return Val_long(getblock((struct channel *) channel, &Byte(buffer, Long_val(offset)), Long_val(length))); }
(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 OCaml.) 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 OCaml values, the following include files are provided:
Include file | Provides |
caml/mlvalues.h | definition of the value type, and conversion macros |
caml/alloc.h | allocation functions (to create structured OCaml objects) |
caml/memory.h | miscellaneous memory-related functions and macros (for GC interface, in-place modification of structures, etc). |
caml/fail.h | functions for raising exceptions (see section 19.4.5) |
caml/callback.h | callback from C to OCaml (see section 19.7). |
caml/custom.h | operations on custom blocks (see section 19.9). |
caml/intext.h | operations for writing user-defined serialization and deserialization functions for custom blocks (see section 19.9). |
caml/threads.h | operations for interfacing in the presence of multiple threads (see section 19.10). |
These files reside in the caml/ subdirectory of the OCaml standard library directory (usually /usr/local/lib/ocaml).
The OCaml 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 OCaml 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 19.1.4 below.)
In the “custom runtime” mode, the OCaml 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:
This builds a runtime system with the required primitives. The OCaml 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:
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 OCaml/C executable, execute the ocamlopt command with:
Starting with Objective Caml 3.00, it is possible to record the -custom option as well as the names of C libraries in an OCaml library file .cma or .cmxa. For instance, consider an OCaml library mylib.cma, built from the OCaml 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 Objective Caml 3.03, an alternative to static linking of C code using the -custom code is provided. In this mode, the OCaml 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 OCaml 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, MacOS X, and Windows. It is supported, but not fully tested yet, under FreeBSD, Tru64, Solaris and Irix. It is not supported yet under other Unixes.
To dynamically link C code with OCaml 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 (when required by the operating system), 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
Do not set the -custom flag, otherwise you’re back to static linking as described in section 19.1.3. The ocamlmklib tool (see section 19.11) 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 an OCaml .cma library archive. Consider again an OCaml library mylib.cma, built from the OCaml 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 OCaml code, we now review the pros and cons of each, to help developers of mixed OCaml/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 19.11) 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 OCaml 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:
ocamlc -use-runtime /home/me/ocamlunixrun -o myprog \ unix.cma threads.cma your .cmo and .cma files
The bytecode executable myprog can then be launched as usual: myprog args or /home/me/ocamlunixrun myprog args.
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).
All OCaml objects are represented by the C type value, defined in the include file caml/mlvalues.h, along with macros to manipulate values of that type. An object of type value is either:
caml_alloc_*
functions below);
Integer values encode 31-bit signed integers (63-bit on 64-bit architectures). They are unboxed (unallocated).
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 OCaml 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. |
String_tag | A character string. |
Double_tag | A double-precision floating-point number. |
Double_array_tag | An array or record of double-precision floating-point numbers. |
Abstract_tag | A block representing an abstract datatype. |
Custom_tag | A block representing an abstract datatype with user-defined finalization, comparison, hashing, serialization and deserialization functions atttached. |
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 OCaml, explicit deallocation of the pointer using free is potentially dangerous, because the pointer may still be accessible from the OCaml world. Worse, the memory space deallocated by free can later be reallocated as part of the OCaml heap; the pointer, formerly pointing outside the OCaml heap, now points inside the OCaml heap, and this can confuse the garbage collector. To avoid these problems, it is preferable to wrap the pointer in a OCaml block with tag Abstract_tag or Custom_tag.
This section describes how OCaml data types are encoded in the value type.
OCaml type | Encoding |
int | Unboxed integer values. |
char | Unboxed integer values (ASCII code). |
float | Blocks with tag Double_tag. |
string | Blocks with tag String_tag. |
int32 | Blocks with tag Custom_tag. |
int64 | Blocks with tag Custom_tag. |
nativeint | Blocks with tag Custom_tag. |
Tuples are represented by pointers to blocks, with tag 0.
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 caml_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. A non-constant constructors declared with n arguments is represented by a block of size n, tagged with the constructor number; the n fields contain its arguments. 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.
The following artificial example illustrates the assignment of integers and block tags to constructors:
type t = | A (* First constant constructor -> integer "Val_int(0)" *) | B of string (* First non-constant constructor -> block with tag 0 *) | C (* Second constant constructor -> integer "Val_int(1)" *) | D of bool (* Second non-constant constructor -> block with tag 1 *) | E of t * t (* Third non-constant constructor -> block with tag 2 *)
Objects are represented as blocks with tag Object_tag. 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 second field contains a unique object ID, used for comparisons. The remaining fields of the object contain the values of the instance variables of the object. It is unsafe to access directly instance variables, as the type system provides no guaranteee about the instance variables contained by an object.
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:
callback(caml_get_public_method(foo, hash_variant("bar")), foo);
Like constructed terms, polymorphic variant values are represented either as integers (for polymorphic variants without arguments), or as blocks (for polymorphic variants with an argument). Unlike constructed terms, variant constructors are not numbered starting from 0, but identified by a hash value (an OCaml 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, polymorphic variant values taking several arguments are not flattened. That is, `VConstr(v, w) is represented by a block of size 2, whose field number 1 contains the representation of the pair (v, w), rather than a block of size 3 containing v and w in fields 1 and 2.
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).
char **
). p must
be NULL-terminated.
The following functions are slightly more efficient than caml_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.
Max_young_wosize
. (It
can also be smaller, but in this case it is more efficient to call
caml_alloc_small instead of caml_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 caml_initialize function described below)
before the next allocation.
Two functions are provided to raise two standard exceptions:
char *
), raises exception Failure with argument s.
char *
), raises exception Invalid_argument
with argument s.
Raising arbitrary exceptions from C is more delicate: the exception identifier is dynamically allocated by the OCaml program, and therefore must be communicated to the C function using the registration facility described below in section 19.7.3. Once the exception identifier is recovered in C, the following functions actually raise the exception:
Unused blocks in the heap are automatically reclaimed by the garbage collector. This requires some cooperation from C code that manipulates heap-allocated blocks.
All the macros described in this section are declared in the memory.h header file.
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, CAMLreturn0, and CAMLreturnT are used to replace the C keyword return. Every occurence of return x must be replaced by CAMLreturn (x) if x has type value, or CAMLreturnT (t, x) (where t is the type of 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).
some C compilers give bogus warnings about unused variables caml__dummy_xxx at each use of CAMLparam and CAMLlocal. You should ignore them.
Example:
void foo (value v1, value v2, value v3) { CAMLparam3 (v1, v2, v3); ... CAMLreturn0; }
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).
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.
Example:
value bar (value v1, value v2, value v3) { CAMLparam3 (v1, v2, v3); CAMLlocal1 (result); result = caml_alloc (3, 0); ... CAMLreturn (result); }
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).
Example:
value bar (value v1, value v2, value v3) { CAMLparam3 (v1, v2, v3); CAMLlocal1 (result); result = caml_alloc (3, 0); Store_field (result, 0, v1); Store_field (result, 1, v2); Store_field (result, 2, v3); CAMLreturn (result); }
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.
Registration of a global variable v is achieved by calling caml_register_global_root(&v) just before or just after a valid value is stored in v for the first time. You must not call any of the OCaml runtime functions or macros between registering and storing the value.
A registered global variable v can be un-registered by calling caml_remove_global_root(&v).
If the contents of the global variable v are not modified after registration, better performance can be achieved by calling caml_register_generational_global_root(&v) to register v, and caml_remove_generational_global_root(&v) to un-register it. The garbage collector takes advantage of the guarantee that v is not modified to scan it less often. This improves performance if many global variables need to be registered.
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 caml_alloc_small and caml_alloc_shr. You can ignore those rules if you stick to the simplified allocation function caml_alloc.
Field(v, n) = vn;If the block has been allocated with caml_alloc_shr, filling is performed through the caml_initialize function:
caml_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).
Field(v, n) = w;is safe only if v is a block newly allocated by caml_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 caml_alloc_shr, use caml_initialize to assign a value to a field for the first time:
caml_initialize(&Field(v, n), w);Otherwise, you are updating a field that previously contained a well-formed value; then, call the caml_modify function:
caml_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:
value alloc_list_int(int i1, int i2) { CAMLparam0 (); CAMLlocal2 (result, r); r = caml_alloc(2, 0); /* Allocate a cons cell */ Store_field(r, 0, Val_int(i2)); /* car = the integer i2 */ Store_field(r, 1, Val_int(0)); /* cdr = the empty list [] */ result = caml_alloc(2, 0); /* Allocate the other cons cell */ Store_field(result, 0, Val_int(i1)); /* car = the integer i1 */ Store_field(result, 1, r); /* cdr = the first cons cell */ CAMLreturn (result); }
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 caml_alloc_small, and filled by direct assignments on their fields.
value alloc_list_int(int i1, int i2) { CAMLparam0 (); CAMLlocal2 (result, r); r = caml_alloc_small(2, 0); /* Allocate a cons cell */ Field(r, 0) = Val_int(i2); /* car = the integer i2 */ Field(r, 1) = Val_int(0); /* cdr = the empty list [] */ result = caml_alloc_small(2, 0); /* Allocate the other cons cell */ Field(result, 0) = Val_int(i1); /* car = the integer i1 */ Field(result, 1) = r; /* cdr = the first cons cell */ CAMLreturn (result); }
In the two examples above, the list is built bottom-up. Here is an alternate way, that proceeds top-down. It is less efficient, but illustrates the use of caml_modify.
value alloc_list_int(int i1, int i2) { CAMLparam0 (); CAMLlocal2 (tail, r); r = caml_alloc_small(2, 0); /* Allocate a cons cell */ Field(r, 0) = Val_int(i1); /* car = the integer i1 */ Field(r, 1) = Val_int(0); /* A dummy value tail = caml_alloc_small(2, 0); /* Allocate the other cons cell */ Field(tail, 0) = Val_int(i2); /* car = the integer i2 */ Field(tail, 1) = Val_int(0); /* cdr = the empty list [] */ caml_modify(&Field(r, 1), tail); /* cdr of the result = tail */ CAMLreturn (r); }
It would be incorrect to perform Field(r, 1) = tail directly, because the allocation of tail has taken place since r was allocated.
This section outlines how the functions from the Unix curses library can be made available to OCaml programs. First of all, here is the interface curses.mli that declares the curses primitives and data types:
type window (* The type "window" remains abstract *) external initscr: unit -> window = "curses_initscr" external endwin: unit -> unit = "curses_endwin" external refresh: unit -> unit = "curses_refresh" external wrefresh : window -> unit = "curses_wrefresh" external newwin: int -> int -> int -> int -> window = "curses_newwin" external addch: char -> unit = "curses_addch" external mvwaddch: window -> int -> int -> char -> unit = "curses_mvwaddch" external addstr: string -> unit = "curses_addstr" external mvwaddstr: window -> int -> int -> string -> unit = "curses_mvwaddstr" (* lots more omitted *)
To compile this interface:
ocamlc -c curses.mli
To implement these functions, we just have to provide the stub code; the core functions are already implemented in the curses library. The stub code file, curses_stubs.c, looks like this:
#include <curses.h> #include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/alloc.h> #include <caml/custom.h> /* Encapsulation of opaque window handles (of type WINDOW *) as OCaml custom blocks. */ static struct custom_operations curses_window_ops = { "fr.inria.caml.curses_windows", custom_finalize_default, custom_compare_default, custom_hash_default, custom_serialize_default, custom_deserialize_default }; /* Accessing the WINDOW * part of an OCaml custom block */ #define Window_val(v) (*((WINDOW **) Data_custom_val(v))) /* Allocating an OCaml custom block to hold the given WINDOW * */ static value alloc_window(WINDOW * w) { value v = alloc_custom(&curses_window_ops, sizeof(WINDOW *), 0, 1); Window_val(v) = w; return v; } value caml_curses_initscr(value unit) { CAMLparam1 (unit); CAMLreturn (alloc_window(initscr())); } value caml_curses_endwin(value unit) { CAMLparam1 (unit); endwin(); CAMLreturn (Val_unit); } value caml_curses_refresh(value unit) { CAMLparam1 (unit); refresh(); CAMLreturn (Val_unit); } value caml_curses_wrefresh(value win) { CAMLparam1 (win); wrefresh(Window_val(win)); CAMLreturn (Val_unit); } value caml_curses_newwin(value nlines, value ncols, value x0, value y0) { CAMLparam4 (nlines, ncols, x0, y0); CAMLreturn (alloc_window(newwin(Int_val(nlines), Int_val(ncols), Int_val(x0), Int_val(y0)))); } value caml_curses_addch(value c) { CAMLparam1 (c); addch(Int_val(c)); /* Characters are encoded like integers */ CAMLreturn (Val_unit); } value caml_curses_mvwaddch(value win, value x, value y, value c) { CAMLparam4 (win, x, y, c); mvwaddch(Window_val(win), Int_val(x), Int_val(y), Int_val(c)); CAMLreturn (Val_unit); } value caml_curses_addstr(value s) { CAMLparam1 (s); addstr(String_val(s)); CAMLreturn (Val_unit); } value caml_curses_mvwaddstr(value win, value x, value y, value s) { CAMLparam4 (win, x, y, s); mvwaddstr(Window_val(win), Int_val(x), Int_val(y), String_val(s)); CAMLreturn (Val_unit); } /* This goes on for pages. */
The file curses_stubs.c can be compiled with:
cc -c -I`ocamlc -where` curses.c
or, even simpler,
ocamlc -c curses.c
(When passed a .c file, the ocamlc command simply calls the C compiler on that file, with the right -I option.)
Now, here is a sample OCaml program test.ml that uses the curses module:
open Curses let main_window = initscr () in let small_window = newwin 10 5 20 10 in mvwaddstr main_window 10 2 "Hello"; mvwaddstr small_window 4 3 "world"; refresh(); Unix.sleep 5; endwin()
To compile and link this program, run:
ocamlc -custom -o test unix.cma test.ml curses_stubs.o -cclib -lcurses
(On some machines, you may need to put -cclib -ltermcap or -cclib -lcurses -cclib -ltermcap instead of -cclib -lcurses.)
So far, we have described how to call C functions from OCaml. In this section, we show how C functions can call OCaml functions, either as callbacks (OCaml calls C which calls OCaml), or because the main program is written in C.
C functions can apply OCaml function values (closures) to OCaml values. The following functions are provided to perform the applications:
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 OCaml code, skipping over the C code. That is, if an OCaml function f calls a C function g that calls back an OCaml 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 OCaml function, it can use the functions caml_callback_exn, caml_callback2_exn, caml_callback3_exn, caml_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 caml_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 OCaml function. If Is_exception_result(v) returns “true”, an exception escaped, and its value (the exception descriptor) can be recovered using Extract_exception(v).
If the OCaml function returned with an exception, Extract_exception should be applied to the exception result prior to calling a function that may trigger garbage collection. Otherwise, if v is reachable during garbage collection, the runtime can crash since v does not contain a valid value.
Example:
value call_caml_f_ex(value closure, value arg) { CAMLparam2(closure, arg); CAMLlocal2(res, tmp); res = caml_callback_exn(closure, arg); if(Is_exception_result(res)) { res = Extract_exception(res); tmp = caml_alloc(3, 0); /* Safe to allocate: res contains valid value. */ ... } CAMLreturn (res); }
There are two ways to obtain OCaml function values (closures) to be passed to the callback functions described above. One way is to pass the OCaml function as an argument to a primitive function. For example, if the OCaml code contains the declaration
external apply : ('a -> 'b) -> 'a -> 'b = "caml_apply"
the corresponding C stub can be written as follows:
CAMLprim value caml_apply(value vf, value vx) { CAMLparam2(vf, vx); CAMLlocal1(vy); vy = caml_callback(vf, vx); CAMLreturn(vy); }
Another possibility is to use the registration mechanism provided by OCaml. This registration mechanism enables OCaml code to register OCaml functions under some global name, and C code to retrieve the corresponding closure by this global name.
On the OCaml side, registration is performed by evaluating Callback.register n v. Here, n is the global name (an arbitrary string) and v the OCaml value. For instance:
let f x = print_string "f is applied to "; print_int x; print_newline() let _ = Callback.register "test function" f
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 OCaml 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 OCaml function f above:
void call_caml_f(int arg) { caml_callback(*caml_named_value("test function"), Val_int(arg)); }
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:
void call_caml_f(int arg) { static value * closure_f = NULL; if (closure_f == NULL) { /* First time around, look up by name */ closure_f = caml_named_value("test function"); } caml_callback(*closure_f, Val_int(arg)); }
The registration mechanism described above can also be used to communicate exception identifiers from OCaml to C. The OCaml code registers the exception by evaluating Callback.register_exception n exn, where n is an arbitrary name and exn is an exception value of the exception to register. For example:
exception Error of string let _ = Callback.register_exception "test exception" (Error "any string")
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 19.4.5) to actually raise the exception. For example, here is a C function that raises the Error exception with the given argument:
void raise_error(char * msg) { caml_raise_with_string(*caml_named_value("test exception"), msg); }
In normal operation, a mixed OCaml/C program starts by executing the OCaml initialization code, which then may proceed to call C functions. We say that the main program is the OCaml code. In some applications, it is desirable that the C code plays the role of the main program, calling OCaml functions when needed. This can be achieved as follows:
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 OCaml 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 19.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, .obj under Windows) containing the bytecode for the OCaml 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 OCaml runtime and execute the OCaml 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 -output-obj option can also be used to obtain the C source file. More interestingly, the same option can also produce directly a shared library (.so file, .dll under Windows) that contains the OCaml code, the OCaml runtime system and any other static C code given to ocamlc (.o, .a, respectively, .obj, .lib). This use of -output-obj is very similar to a normal linking step, but instead of producing a main program that automatically runs the OCaml code, it produces a shared library that can run the OCaml code on demand. The three possible behaviors of -output-obj are selected according to the extension of the resulting file (given with -o).
The native-code compiler ocamlopt also supports the -output-obj option, causing it to output a C object file or a shared library containing the native code for all OCaml modules on the command-line, as well as the OCaml 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 OCaml runtime library (libcamlrun.a for bytecode, libasmrun.a for native-code), as well as all C libraries that are required by the OCaml libraries used. For instance, assume the OCaml part of your program uses the Unix library. With ocamlc, you should do:
ocamlc -output-obj -o camlcode.o unix.cma other .cmo and .cma files cc -o myprog C objects and libraries \ camlcode.o -L/usr/local/lib/ocaml -lunix -lcamlrun
With ocamlopt, you should do:
ocamlopt -output-obj -o camlcode.o unix.cmxa other .cmx and .cmxa files cc -o myprog C objects and libraries \ camlcode.o -L/usr/local/lib/ocaml -lunix -lasmrun
The shared libraries produced by ocamlc -output-obj or by ocamlopt -output-obj already contains the OCaml runtime library as well as all the needed C libraries.
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 OCaml, 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:
When OCaml bytecode produced by ocamlc -g is embedded in a C program, no debugging information is included, and therefore it is impossible to print stack backtraces on uncaught exceptions. This is not the case when native code produced by ocamlopt -g is embedded in a C program: stack backtrace information is available, but the backtrace mechanism needs to be turned on programmatically. This can be achieved from the OCaml side by calling Printexc.record_backtrace true in the initialization of one of the OCaml modules. This can also be achieved from the C side by calling caml_record_backtrace(Val_int(1)); in the OCaml-C glue code.
This section illustrates the callback facilities described in section 19.7. We are going to package some OCaml functions in such a way that they can be linked with C code and called from C just like any C functions. The OCaml functions are defined in the following mod.ml OCaml source:
(* File mod.ml – some "useful" OCaml functions *) let rec fib n = if n < 2 then 1 else fib(n-1) + fib(n-2) let format_result n = Printf.sprintf "Result is: %d\n" n (* Export those two functions to C *) let _ = Callback.register "fib" fib let _ = Callback.register "format_result" format_result
Here is the C stub code for calling these functions from C:
/* File modwrap.c – wrappers around the OCaml functions */ #include <stdio.h> #include <string.h> #include <caml/mlvalues.h> #include <caml/callback.h> int fib(int n) { static value * fib_closure = NULL; if (fib_closure == NULL) fib_closure = caml_named_value("fib"); return Int_val(caml_callback(*fib_closure, Val_int(n))); } char * format_result(int n) { static value * format_result_closure = NULL; if (format_result_closure == NULL) format_result_closure = caml_named_value("format_result"); return strdup(String_val(caml_callback(*format_result_closure, Val_int(n)))); /* We copy the C string returned by String_val to the C heap so that it remains valid after garbage collection. */ }
We now compile the OCaml code to a C object file and put it in a C library along with the stub code in modwrap.c and the OCaml runtime system:
ocamlc -custom -output-obj -o modcaml.o mod.ml ocamlc -c modwrap.c cp /usr/local/lib/ocaml/libcamlrun.a mod.a ar r mod.a modcaml.o modwrap.o
(One can also use ocamlopt -output-obj instead of ocamlc -custom -output-obj. In this case, replace libcamlrun.a (the bytecode runtime library) by libasmrun.a (the native-code runtime library).)
Now, we can use the two functions fib and format_result in any C program, just like regular C functions. Just remember to call caml_startup once before.
/* File main.c – a sample client for the OCaml functions */ #include <stdio.h> int main(int argc, char ** argv) { int result; /* Initialize OCaml code */ caml_startup(argv); /* Do some computation */ result = fib(10); printf("fib(10) = %s\n", format_result(result)); return 0; }
To build the whole program, just invoke the C compiler as follows:
cc -o prog main.c mod.a -lcurses
(On some machines, you may need to put -ltermcap or -lcurses -ltermcap instead of -lcurses.)
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:
The compare field can be set to custom_compare_default; this default comparison function simply raises Failure.
The compare_ext field can be set to custom_compare_ext_default; this default comparison function simply raises Failure.
The hash field can be set to custom_hash_default, in which case the custom block is ignored during hash computation.
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.
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).
Note: the finalize, compare, hash, serialize and deserialize functions attached to custom block descriptors must never trigger a garbage collection. Within these functions, do not call any of the OCaml allocation functions, and do not perform a callback into OCaml code. Do not use CAMLparam to register the parameters to these functions, and do not use CAMLreturn to return the result.
Custom blocks must be allocated via the caml_alloc_custom function:
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 OCaml 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 OCaml heap. In other terms, never store an OCaml value in a custom block, and do not use Field, Store_field nor caml_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 |
caml_serialize_int_1 | Write a 1-byte integer |
caml_serialize_int_2 | Write a 2-byte integer |
caml_serialize_int_4 | Write a 4-byte integer |
caml_serialize_int_8 | Write a 8-byte integer |
caml_serialize_float_4 | Write a 4-byte float |
caml_serialize_float_8 | Write a 8-byte float |
caml_serialize_block_1 | Write an array of 1-byte quantities |
caml_serialize_block_2 | Write an array of 2-byte quantities |
caml_serialize_block_4 | Write an array of 4-byte quantities |
caml_serialize_block_8 | Write an array of 8-byte quantities |
caml_deserialize_uint_1 | Read an unsigned 1-byte integer |
caml_deserialize_sint_1 | Read a signed 1-byte integer |
caml_deserialize_uint_2 | Read an unsigned 2-byte integer |
caml_deserialize_sint_2 | Read a signed 2-byte integer |
caml_deserialize_uint_4 | Read an unsigned 4-byte integer |
caml_deserialize_sint_4 | Read a signed 4-byte integer |
caml_deserialize_uint_8 | Read an unsigned 8-byte integer |
caml_deserialize_sint_8 | Read a signed 8-byte integer |
caml_deserialize_float_4 | Read a 4-byte float |
caml_deserialize_float_8 | Read an 8-byte float |
caml_deserialize_block_1 | Read an array of 1-byte quantities |
caml_deserialize_block_2 | Read an array of 2-byte quantities |
caml_deserialize_block_4 | Read an array of 4-byte quantities |
caml_deserialize_block_8 | Read an array of 8-byte quantities |
caml_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 OCaml 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 OCaml 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. caml_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 caml_alloc_custom.
Using multiple threads (shared-memory concurrency) in a mixed OCaml/C application requires special precautions, which are described in this section.
Callbacks from C to OCaml are possible only if the calling thread is known to the OCaml run-time system. Threads created from OCaml (through the Thread.create function of the system threads library) are automatically known to the run-time system. If the application creates additional threads from C and wishes to callback into OCaml code from these threads, it must first register them with the run-time system. The following functions are declared in the include file <caml/threads.h>.
The OCaml run-time system is not reentrant: at any time, at most one thread can be executing OCaml code or C code that uses the OCaml run-time system. Technically, this is enforced by a “master lock” that any thread must hold while executing such code.
When OCaml calls the C code implementing a primitive, the master lock is held, therefore the C code has full access to the facilities of the run-time system. However, no other thread can execute OCaml code concurrently with the C code of the primitive.
If a C primitive runs for a long time or performs potentially blocking input-output operations, it can explicitly release the master lock, enabling other OCaml threads to run concurrently with its operations. The C code must re-acquire the master lock before returning to OCaml. This is achieved with the following functions, declared in the include file <caml/threads.h>.
After caml_release_runtime_system() was called and until caml_acquire_runtime_system() is called, the C code must not access any OCaml data, nor call any function of the run-time system, nor call back into OCaml code. Consequently, arguments provided by OCaml to the C primitive must be copied into C data structures before calling caml_release_runtime_system(), and results to be returned to OCaml must be encoded as OCaml values after caml_acquire_runtime_system() returns.
Example: the following C primitive invokes gethostbyname to find the IP address of a host name. The gethostbyname function can block for a long time, so we choose to release the OCaml run-time system while it is running.
CAMLprim stub_gethostbyname(value vname) { CAMLparam1 (vname); CAMLlocal1 (vres); struct hostent * h; /* Copy the string argument to a C string, allocated outside the OCaml heap. */ name = stat_alloc(caml_string_length(vname) + 1); strcpy(name, String_val(vname)); /* Release the OCaml run-time system */ caml_release_runtime_system(); /* Resolve the name */ h = gethostbyname(name); /* Re-acquire the OCaml run-time system */ caml_acquire_runtime_system(); /* Encode the relevant fields of h as the OCaml value vres */ ... /* Omitted */ /* Return to OCaml */ CAMLreturn (vres); }
Callbacks from C to OCaml must be performed while holding the master lock to the OCaml run-time system. This is naturally the case if the callback is performed by a C primitive that did not release the run-time system. If the C primitive released the run-time system previously, or the callback is performed from other C code that was not invoked from OCaml (e.g. an event loop in a GUI application), the run-time system must be acquired before the callback and released after:
caml_acquire_runtime_system(); /* Resolve OCaml function vfun to be invoked */ /* Build OCaml argument varg to the callback */ vres = callback(vfun, varg); /* Copy relevant parts of result vres to C data structures */ caml_release_runtime_system();
Note: the acquire and release functions described above were introduced in OCaml 3.12. Older code uses the following historical names, declared in <caml/signals.h>:
Intuition: a “blocking section” is a piece of C code that does not use the OCaml run-time system, typically a blocking input/output operation.
The ocamlmklib command facilitates the construction of libraries containing both OCaml code and C code, and usable both in static linking and dynamic linking modes. This command is available under Windows since Objective Caml 3.11 and under other operating systems since Objective Caml 3.03.
The ocamlmklib command takes three kinds of arguments:
It generates the following outputs:
In addition, the following options are recognized:
Consider an OCaml 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 an OCaml 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 OCaml 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:
ocamlc -a -o zip.cma zip.cmo -dllib -lzip \ -cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib ocamlopt -a -o zip.cmxa zip.cmx -cclib -lzip \ -cclib -lzip -cclib -lz -ccopt -L/usr/local/zlib gcc -shared -o dllzip.so zipstubs.o -lz -L/usr/local/zlib ar rc libzip.a zipstubs.o
If shared libraries are not supported, the following commands are performed instead:
ocamlc -a -custom -o zip.cma zip.cmo -cclib -lzip \ -cclib -lz -ccopt -L/usr/local/zlib ocamlopt -a -o zip.cmxa zip.cmx -lzip \ -cclib -lz -ccopt -L/usr/local/zlib ar rc libzip.a zipstubs.o
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.
Part IV |
This chapter describes the OCaml 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:
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.
type int
The type of integer numbers.
type char
The type of characters.
type string
The type of character strings.
type float
The type of floating-point numbers.
type bool = false | true
The type of booleans (truth values).
type unit = ()
The type of the unit value.
type exn
The type of exception values.
type 'a array
The type of arrays whose elements have type 'a.
type 'a list = [] | :: of 'a * 'a list
The type of lists whose elements have type 'a.
type 'a option = None | Some of 'a
The type of optional values of type 'a.
type int32
The type of signed 32-bit integers. See the Int32[Int32] module.
type int64
The type of signed 64-bit integers. See the Int64[Int64] module.
type nativeint
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, 'e, 'f) format6
The type of format strings. 'a is the type of the parameters of the format, 'f is the result type for the printf-style functions, 'b is the type of the first argument given to %a and %t printing functions (see module Printf[Printf]), 'c is the result type of these functions, and also the type of the argument transmitted to the first argument of kprintf-style functions, 'd is the result type for the scanf-style functions (see module Scanf[Scanf]), and 'e is the type of the receiver function for the scanf-style functions.
type 'a lazy_t
This type is used to implement the Lazy[Lazy] module. It should not be used directly.
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 integer division and remainder operations when their second argument is zero.
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.8.) 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 OCaml 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 Pervasives 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.
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 OCaml 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
For interactive use of the unix library, do:
ocamlmktop -o mytop unix.cma ./mytop
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type #load "unix.cma";;.
Windows: A fairly complete emulation of the Unix system calls is provided in the Windows version of OCaml. The end of this chapter gives more information on the functions that are not supported under Windows.
Windows: The Cygwin port of OCaml 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 truncate, ftruncate not implemented link, symlink, readlink not implemented (no links under Windows) access execute permission X_OK cannot be tested, it just tests for read permission instead fchmod not implemented chown, fchown not implemented (make no sense on a DOS file system) umask not implemented mkfifo not implemented kill, pause not implemented (no inter-process signals in Windows) alarm not implemented times partially implemented, will not report timings for child processes getitimer, setitimer not implemented getuid, getgid always return 1 getgid, getegid, getgroups not implemented setuid, setgid not implemented getpwnam, getpwuid always raise Not_found getgrnam, getgrgid always raise Not_found type socket_domain the domains PF_UNIX and PF_INET6 are not supported; PF_INET is fully supported establish_server not implemented; use threads terminal functions (tc*) not implemented
The num library implements integer arithmetic and rational arithmetic in arbitrary precision.
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, http://hal.inria.fr/docs/00/07/00/27/PDF/RT-0141.pdf).
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
For interactive use of the nums library, do:
ocamlmktop -o mytop nums.cma ./mytop
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type #load "nums.cma";;.
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
For interactive use of the str library, do:
ocamlmktop -o mytop str.cma ./mytop
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type #load "str.cma";;.
The threads library allows concurrent programming in OCaml. 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:
Programs that use system threads must be linked as follows:
ocamlc -thread other options unix.cma threads.cma other files ocamlopt -thread other options unix.cmxa threads.cmxa other files
Compilation units that use the threads library must also be compiled with the -thread option (see chapter 8).
Programs that use VM-level threads must be compiled with the -vmthread option to ocamlc (see chapter 8), and be linked as follows:
ocamlc -vmthread other options threads.cma other files
Compilation units that use threads library must also be compiled with the -vmthread option (see chapter 8).
The graphics library provides a set of portable drawing primitives. Drawing takes place in a separate window that is created when Graphics.open_graph is called.
Unix: This library is implemented under the X11 windows system. Programs that use the graphics library must be linked as follows:ocamlc other options graphics.cma other filesFor interactive use of the graphics library, do:ocamlmktop -o mytop graphics.cma ./mytopor (if dynamic linking of C libraries is supported on your platform), start ocaml and type #load "graphics.cma";;.Here are the graphics mode specifications supported by Graphics.open_graph on the X11 implementation of this library: the argument to Graphics.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:
- Graphics.open_graph "foo:0"
- connects to the display foo:0 and creates a window with the default geometry
- Graphics.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)
- Graphics.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)
- Graphics.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 dynlink library supports type-safe dynamic loading and linking of bytecode object files (.cmo and .cma files) in a running bytecode program, or of native plugins (usually .cmxs files) in a running native 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. In native code, there are also some compatibility checks on the implementations (to avoid errors with cross-module optimizations); it might be useful to hide .cmx files when building native plugins so that they remain independent of the implementation of modules in the main program.
Programs that use the dynlink library simply need to link dynlink.cma or dynlink.cmxa with their object files and other libraries.
The labltk library provides access to the Tcl/Tk GUI from OCaml 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.
Programs that use the labltk library must be linked as follows:
ocamlc other options -I +labltk labltk.cma other files ocamlopt other options -I +labltk labltk.cmxa other files
Unix: 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.4. 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 -tkdefs switches, 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.4 -I/usr/local/include/tk8.4".
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.4. You must first have it installed on your system. It can be downloaded from
http://www.activestate.com/products/ActiveTcl/. After installing it, you must put the dynamically loaded libraries tcl84.dll and tk84.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.
# #directory "+labltk";; # #load "labltk.cma";;You can also load it directly from the command line.
C:\ocaml\bin> ocaml -I +labltk labltk.cma
The labltk library is composed of a large number of modules.
Bell Imagebitmap Place Button Imagephoto Radiobutton Canvas Label Scale Checkbutton Listbox Scrollbar Clipboard Menu Selection Dialog Menubutton Text Entry Message Tk Focus Option Tkwait Frame Optionmenu Toplevel Grab Pack Winfo Grid Palette Wm
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 OCaml arrays described in Module Array. The main differences between “big arrays” and standard OCaml arrays are as follows:
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
For interactive use of the bigarray library, do:
ocamlmktop -o mytop bigarray.cma ./mytop
or (if dynamic linking of C libraries is supported on your platform), start ocaml and type #load "bigarray.cma";;.
C stub code that interface C or Fortran code with OCaml code, as described in chapter 19, can exploit big arrays as follows.
The include file <caml/bigarray.h> must be included in the C stub file. It declares the functions, constants and macros discussed below.
If v is a OCaml 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 OCaml 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.
extern void my_c_function(double * data, int dimx, int dimy); extern void my_fortran_function_(double * data, int * dimx, int * dimy); value caml_stub(value bigarray) { int dimx = Bigarray_val(bigarray)->dim[0]; int dimy = Bigarray_val(bigarray)->dim[1]; /* C passes scalar parameters by value */ my_c_function(Data_bigarray_val(bigarray), dimx, dimy); /* Fortran passes all parameters by reference */ my_fortran_function_(Data_bigarray_val(bigarray), &dimx, &dimy); return Val_unit; }
A pointer p to an already-allocated C or Fortran array can be wrapped and returned to OCaml as a big array using the alloc_bigarray or alloc_bigarray_dims functions.
Return an OCaml 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.
Same as alloc_bigarray, but the sizes of the array in each dimension are listed as extra arguments in the function call, rather than being passed as an array.
The following example illustrates how statically-allocated C and Fortran arrays can be made available to OCaml.
extern long my_c_array[100][200]; extern float my_fortran_array_[300][400]; value caml_get_c_array(value unit) { long dims[2]; dims[0] = 100; dims[1] = 200; return alloc_bigarray(BIGARRAY_NATIVE_INT | BIGARRAY_C_LAYOUT, 2, my_c_array, dims); } value caml_get_fortran_array(value unit) { return alloc_bigarray_dims(BIGARRAY_FLOAT32 | BIGARRAY_FORTRAN_LAYOUT, 2, my_fortran_array_, 300L, 400L); }
Part V |
|
|
This document was translated from LATEX by HEVEA.