The expression `invert lst_iter` returns a sequence that allows the consumer to traverse the list on demand. For example,

```h
let s = invert ~iter:lst_iter
let next = Seq.to_dispenser s;;
val s : int Seq.t = <fun>
val next : unit -> int option = <fun>

next();;
- : int option = Some 1

next();;
- : int option = Some 2

next();;
- : int option = Some 3

next();;
- : int option = None
```

We can use the same `invert` function on any `iter` function. For example,

```h
let s = invert ~iter:(Fun flip String.iter "0Cam1")
let next = Seq.to_dispenser s;;
val s : char Seq.t = <fun>
val next : unit -> char option = <fun>

next();;
- : char option = Some '0'

next();;
- : char option = Some 'C'

next();;
- : char option = Some 'a'

next();;
- : char option = Some 'm'

next();;
- : char option = Some 'l'

next();;
- : char option = None
```
```h
match eff with
| Recv -> Some (fun (k: (b,_) continuation) ->
| loop_send k n)
| Send v -> failwith "protocol violation"
| _ -> None }
in
loop_send (fiber comp) ()
```

The `run` function executes the computation `comp` ensuring that it can only perform an alternating sequence of `Send` and `Recv` effects. The shallow handler uses a different set of primitives compared to the deep handler. The primitive `fiber` (on the last line) takes an `'a -> 'b` function and returns a `('a, 'b) Effect.Shallow.continuation`. The expression `continue_with k v h` resumes the continuation `k` with value `v` under the handler `h`.

The mutually recursive functions `loop_send` and `loop_recv` resume the given continuation `k` with value `v` under different handlers. The `loop_send` function handles the `Send` effect and tail calls the `loop_recv` function. If the computation performs the `Recv` effect, then `loop_send` aborts the computation by raising an exception. Similarly, the `loop_recv` function handles the `Recv` effect and tail calls the `loop_send` function. If the computation performs the `Send` effect, then `loop_recv` aborts the computation. Given that the continuation captured in the shallow handler do not include the handler, there is only ever one handler installed in the dynamic scope of the computation `comp`.

The computation is initially executed by the `loop_send` function (see last line in the code above) which ensures that the first effect that the computation is allowed to perform is the `Send` effect. Note that the computation is free to perform effects other than `Send` and `Recv`, which may be handled by an outer handler.

We can see that the `run` function will permit a computation that follows the protocol:

```h
run (fun () ->
    printf "Send 42\n";
    perform (Send 42);
    printf "Recv: %d\n" (perform Recv);
    printf "Send 43\n";
    perform (Send 43);
    printf "Recv: %d\n" (perform Recv))
Send 42
Recv: 42
Send 43
Recv: 43
- : unit = ()
```

and aborts those that do not:

```h
run (fun () ->
    Printf printf "Send 0\n";
    perform (Send 0);
    Printf printf "Send 1\n";
    perform (Send 1) (* protocol violation *))
Send 0
Send 1
Exception: Failure "protocol violation".
```
## 12.24.6 Implementing control inversion

The implementation of the `invert` function is given below:

```hhl
let invert (type a) ~ (iter : (a -> unit) -> unit) : a Seq.t =
  let module M = struct
     type _ Effect.t += Yield : a -> unit t
  end in
  let yield v = perform (M.Yield v) in
  fun () -> match iter yield with
  | () -> Seq Nil
  | effect M.Yield v, k -> Seq.Cons (v, continue k)
```

The `invert` function declares an effect `Yield` that takes the element to be yielded as a parameter. The `yield` function performs the `Yield` effect. The lambda abstraction `fun () -> ...` delays all action until the first element of the sequence is demanded. Once this happens, the computation `iter yield` is executed under an effect handler. Every time the `iter` function pushes an element to the `yield` function, the computation is interrupted by the `Yield` effect. The `Yield` effect is handled by returning the value `Seq.Cons(v, continue k)` to the consumer. The consumer gets the element `v` as well as the suspended computation, which in the consumer's eyes is just the tail of sequence.

When the consumer demands the next element from the sequence (by applying it to `()`), the continuation `k` is resumed. This allows the computation `iter yield` to make progress, until it either yields another element or terminates normally. In the latter case, the value `Seq Nil` is returned, indicating to the consumer that the iteration is over.

It is important to note that the sequence returned by the `invert` function is *ephemeral* (as defined by the `Seq[29.53]` module) i.e., the sequence must be used at most once. Additionally, the sequence must be fully consumed (i.e., used at least once) so as to ensure that the captured continuation is used linearly.

## 12.24.7 Semantics

In this section, we shall see the semantics of effect handlers with the help of examples.

## 12.24.8 Nesting handlers

Like exception handlers, effect handlers can be nested.

```hhl
type _ Effect.t += E : int t
                  | F : string t

let foo () = perform F

let bar () =
  try foo () with
  | effect E, k -> failwith "impossible"

let baz () =
  try bar () with
```
We may implement the same example using deep handlers using reference cells (easy, but unsatisfying) or without them (harder). We leave this as an exercise to the reader.
- : string = "Saw Effect.Unhandled exception"

## 12.24.11 Linear continuations

As discussed earlier 12.24.4, the delimited continuations in OCaml must be used linearly – every *captured continuation must be resumed either with a continue or discontinue exactly once*. Attempting to use a continuation more than once raises a *Continuation_already_resumed* exception. For example:

```ocaml
try perform (Xchg 0) with
| effect Xchg n, k -> continue k 21 + continue k 21
Exception: Stdlib.Effect.Continuation_already_resumed.
```

The primary motivation for adding effect handlers to OCaml is to enable concurrent programming. One-shot continuations are sufficient for almost all concurrent programming needs. They are also much cheaper to implement compared to multi-shot continuations since they do not require stack frames to be copied. Moreover, OCaml programs may also manipulate linear resources such as sockets and file descriptors. The linearity discipline is easily broken if the continuations are allowed to resume more than once. It would be quite hard to debug such linearity violations on resources due to the lack of static checks for linearity and the non-local nature of control flow. Hence, OCaml does not support multi-shot continuations.

While the “at most once resumption” property of continuations is ensured with a dynamic check, there is no check to ensure that the continuations are resumed “at least once”. It is left to the user to ensure that the captured continuations are resumed at least once. Not resuming continuations will leak the memory allocated for the fibers as well as any resources that the suspended computation may hold.

One may install a finaliser on the captured continuation to ensure that the resources are freed:

```ocaml
exception Unwind
Gc.finalise (fun k ->
  try ignore (discontinue k Unwind) with _ ->()) k
```

In this case, if `k` becomes unreachable, then the finaliser ensures that the continuation stack is unwound by discontinuing with an `Unwind` exception, allowing the computation to free up resources. However, the runtime cost of finalisers is much more than the cost of capturing a continuation. Hence, it is recommended that the user take care of resuming the continuation exactly once rather than relying on the finaliser.

## 12.24.12 Limitations

OCaml's effects are *synchronous*: It is not possible to perform an effect asynchronously from a signal handler, a finaliser, a memprof callback, or a GC alarm, and catch it from the main part of the code. Instead, this would result in an *Effect.Unhandled* exception (12.24.10).

Similarly, effects are incompatible with the use of callbacks from C to OCaml (section 22.7). It is not possible for an effect to cross a call to `caml_callback`, this would instead result in an *Effect.Unhandled* exception. In particular, care must be taken when mixing libraries that use callbacks from C to OCaml and libraries that use effects.
# Part III

## The OCaml tools
12.24.13 Shallow handlers

The examples that we have seen so far have used *deep* handlers. A deep handler handles all the effects performed (in sequence) by the computation. Whenever a continuation is captured in a deep handler, the captured continuation also includes the handler. This means that, when the continuation is resumed, the effect handler is automatically re-installed, and will handle the effect(s) that the computation may perform in the future.

OCaml also provides *shallow* handlers. Compared to deep handlers, a shallow handler handles only the first effect performed by the computation. The continuation captured in a shallow handler does not include the handler. This means that, when the continuation is resumed, the handler is no longer present. For this reason, when the continuation is resumed, the user is expected to provide a new effect handler (possibly a different one) to handle the next effect that the computation may perform.

Shallow handlers make it easier to express certain kinds of programs. Let us implement a shallow handler that enforces a particular sequence of effects (a protocol) on a computation. For this example, let us consider that the computation may perform the following effects:

```hml
type _ Effect.t += Send : int -> unit Effect.t
| Recv : int Effect.t
```

Let us assume that we want to enforce a protocol that only permits an alternating sequence of Send and Recv effects that conform to the regular expression `(Send;Recv)*;Send?`. Hence, the sequence of effects `[]` (the empty sequence), `[Send]`, `[Send;Recv]`, `[Send;Recv;Send]`, etc., are allowed, but not `[Recv]`, `[Send;Send]`, `[Send;Recv;Recv]`, etc. The key observation here is that the set of effects handled evolves over time. We can enforce this protocol quite naturally using shallow handlers as shown below:

```hml
open Effect.Shallow

let run (comp: unit -> unit) : unit =
let rec loop_send : type a. (a,unit) continuation -> a -> unit = fun k v ->
continue_with k v
{ retc = Fun.id;
  exnc = raise;
  effc = fun (type b) (eff : b Effect.t) ->
    match eff with
    | Send n -> Some (fun (k: (b,_) continuation) ->
                        loop_recv n k())
    | Recv -> failwith "protocol violation"
    | _ -> None }
and loop_recv : type a. int -> (a,unit) continuation -> a -> unit = fun n k v ->
continue_with k v
{ retc = Fun.id;
  exnc = raise;
  effc = fun (type b) (eff : b Effect.t) ->
    match eff with
    | Recv -> Some (fun (k: (b,_) continuation) ->
                        loop_send k n)
```
<figure><img src="image_4.png" /></figure>
```
| Send v -> failwith "protocol violation"
| _ -> None }
in
loop_send (fiber comp) ()
```

The `run` function executes the computation `comp` ensuring that it can only perform an alternating sequence of `Send` and `Recv` effects. The shallow handler uses a different set of primitives compared to the deep handler. The primitive `fiber` (on the last line) takes an `'a -> 'b` function and returns a `('a,'b) Effect.Shallow.continuation`.

Unlike deep handlers, OCaml does not provide syntax support for shallow handlers. The expression `continue_with k v h` resumes the continuation `k` with value `v` under the handler `h`. The handler here is a record with three fields for the value case (`retc`), the exceptional case (`exnc`) and the effect case (`effc`).

The mutually recursive functions `loop_send` and `loop_recv` resume the given continuation `k` with value `v` under different handlers. The `loop_send` function handles the `Send` effect and tail calls the `loop_recv` function. If the computation performs the `Recv` effect, then `loop_send` aborts the computation by raising an exception. Similarly, the `loop_recv` function handles the `Recv` effect and tail calls the `loop_send` function. If the computation performs the `Send` effect, then `loop_recv` aborts the computation. Given that the continuation captured in the shallow handler do not include the handler, there is only ever one handler installed in the dynamic scope of the computation `comp`.

Note that unlike deep handlers with syntax support, explicit type annotations are necessary for the shallow handler. We must use a locally abstract type (`type b`) in the effect handler (`effc`) and explicitly type annotate the effect argument `eff` and the continuation `k` in each of the effect cases. Another point to note is that the catch-all effect case `"| _ -> None"` is necessary. This case may be intuitively read as "forward the unhandled effects to the outer handler". The standard library module `Effect[29.18]` also provides a non-syntactic version of deep handlers, where similar annotations are necessary.

The computation is initially executed by the `loop_send` function (see last line in the code above) which ensures that the first effect that the computation is allowed to perform is the `Send` effect. Note that the computation is free to perform effects other than `Send` and `Recv`, which may be handled by an outer handler.

We can see that the `run` function will permit a computation that follows the protocol:

```
run (fun () ->
    printf "Send 42\n";
    perform (Send 42);
    printf "Recv: %d\n" (perform Recv);
    printf "Send 43\n";
    perform (Send 43);
    printf "Recv: %d\n" (perform Recv))
Send 42
Recv: 42
Send 43
Recv: 43
- : unit = ()
```

and aborts those that do not:
Chapter 13

Batch compilation (ocamlc)

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.

13.1 Overview of the compiler

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, after all options have been
processed:

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

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

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

* Arguments ending in `.cmo` are taken to be compiled object bytecode. These files are linked together, along with the object files obtained by compiling `.ml` arguments (if any), and the OCaml standard library, to produce a standalone executable program. The order in which `.cmo` and `.ml` arguments are presented on the command line is relevant: compilation units are initialized in that order at run-time, and it is a link-time error to use a component of a unit before having initialized it. Hence, a given `x.cmo` file must come before all `.cmo` files that refer to the unit `x`.
```pascal
run (fun () ->
    Printf printf "Send 0\n";
    perform (Send 0);
    Printf printf "Send 1\n";
    perform (Send 1) (* protocol violation *))
Send 0
Send 1
Exception: Failure "protocol violation".
```

We may implement the same example using deep handlers using reference cells (easy, but unsatisfying) or without them (harder). We leave this as an exercise to the reader.

## 12.25 Type-directed disambiguation of array literals

(Introduced in OCaml 5.4)

Since OCaml 5.4, array literal syntax `| e1 ; e2 ; ... ; eN |` can be used to denote values of type `floatarray` as well as `'a array`, both in expression and pattern positions. This syntax is also used to display `floatarray` values in the toplevel.

The compiler matches the expected type of the expression or pattern with the type of the literal, in a manner analogous to the disambiguation of constructors and record fields (see 1.4.1).

In the absence of an expected type, array literals are assumed to be of type `'a array`.

In the following examples, the array literals are assigned type `floatarray`:

```pascal
let _ : floatarray = [|42.|];;
  - : floatarray = [|42.|]

let _ = ([|42.|] : floatarray);;
  - : floatarray = [|42.|]

let _ = Float Array.length [|42.|];;
  - : int = 1
```

The same disambiguation mechanism is used for array literals appearing in patterns:

```pascal
let f : floatarray -> _ = function
  | [| 42. |] -> "It's a floatarray containing one element"
  | _ -> "Also a floatarray"
;;
val f : floatarray -> string = <fun>
```

In the example below, `x` is assigned type `float array`:

```pascal
let x = [|42.|];;
val x : float array = [|42.|]
```

However, the following does not work:

```pascal
let f a =
    match a with
    | [| _ |] -> Float Array.length a
```
* Arguments ending in `.cma` are taken to be libraries of object bytecode. A library of object bytecode packs in a single file a set of object bytecode files (`.cmo` files). Libraries are built with `ocamlc -a` (see the description of the `-a` option below). The object files contained in the library are linked as regular `.cmo` files (see above), in the order specified when the `.cma` file was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in.

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

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

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

The output of the linking phase is a file containing compiled bytecode that can be executed by the 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 15 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 compiler is able to emit some information on its internal stages. It can output `.cmt` files for the implementation of the compilation unit and `.cmti` for signatures if the option `-bin-annot` is passed to it (see the description of `-bin-annot` below). Each such file contains a typed abstract syntax tree (AST), that is produced during the type checking procedure. This tree contains all available information about the location and the specific type of each term in the source file. The AST is partial if type checking was unsuccessful.

These `.cmt` and `.cmti` files are typically useful for code inspection tools.

## 13.2 Options

The following command-line options are recognized by `ocamlc`. The options `-pack`, `-a`, `-c`, `-output-obj` and `-output-complete-obj` are mutually exclusive.
| _ -> 42
;;

Error: The value a has type 'a array but an expression was expected of type
        Float Array.t = floatarray

let f b (a : floatarray) = if b then [|42.|] else a
;;

Error: The value a has type floatarray but an expression was expected of type
        float array

Here the information learned from the use of a as a `floatarray` cannot be propagated back to the array literal. In general, expected type information cannot be propagated “backwards”.

In the following example, type disambiguation works because the type information learned in the `then` branch of the conditional is propagated to the `else` branch, which occurs “later”.

let f b (a : floatarray) = if b then a else [|42.|];

val f : bool -> floatarray -> floatarray = <fun>

Such cases trigger warning 18 not-principal, if enabled.

## 12.26 Labeled tuples

(Introduced in OCaml 5.4)

typexpr ::= ...
             | [label-name :] typexpr {\* [label-name :] typexpr}⁺

expr ::= ...
         | [~ label-name :] expr {, [~ label-name :] expr}⁺

pattern ::= ...
            | [~ label-name :] pattern {, [~ label-name :] pattern}⁺

Since OCaml 5.4, tuple fields are optionally labeled. This feature is conceptually dual to labeled function arguments, allowing you to give a helpful name to constructed values where labeled function arguments permit giving a helpful name to parameters.

Here is a motivating example where we want to compute two values from a list and be careful not to mix them up:

let sum_and_product ints =
  let init = ~sum:0, ~product:1 in
  List.fold_left (fun (~sum, ~product) elem ->
    let sum = elem + sum in
    let product = elem * product in
    ~sum, ~product) init ints
val sum_and_product : int list -> sum:int * product:int = <fun>
-a Build a library(“.cma” file) with the object files(“.cmo” files) given on the command line, instead of linking them into an executable file. The name of the library must be set with the -o option.

If -custom , -cclib or -ccopt options are passed on the command line, these options are stored in the resulting .cmalibrary. 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.

-absname

Force error messages to show absolute paths for file names.

-no-absname

Do not try to show absolute filenames in error messages.

-annot

Deprecated since OCaml 4.11. Please use -bin-annot instead.

-args filename

Read additional newline-terminated command line arguments from filename .

-args0 filename

Read additional null character terminated command line arguments from filename .

-bin-annot

Dump detailed information about the compilation (types, bindings, tail-calls, etc) in binary format. The information for file src.ml (resp. src.mli ) is put into file src.cmt (resp. src.cmti ). In case of a type error, dump all the information inferred by the type-checker before the error. The *.cmt and *.cmti files produced by -bin-annot contain more information and are much more compact than the files produced by -annot .

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

-cc ccomp

Use ccomp as the C linker when linking in “custom runtime” mode (see the -custom option) and as the C compiler for compiling .c source files. When linking object files produced by a C++ compiler (such as g++ or lang++ ), it is recommended to use -cc c++ .

-cclib -libname

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

-ccopt option

Pass the given option to the C compiler and linker. When linking in “custom runtime” mode, for instance -ccopt -Ldir causes the C linker to search for C libraries in directory dir . (See the -custom option.)
This example shows the use of labeled tuples in types and patterns. They may be punned like record elements or function arguments.

In types, tuple labels are written similarly to function argument labels. For example, the function argument to `fold_left` in the previous example has the type:

(sum:int * product:int) -> int -> sum:int * product:int

Labeled tuples can be useful anytime you want to use names to explain or disambiguate the elements of a tuple, but declaring a new record feels too heavy.

Tuples may be partially labeled, which can be useful when some elements of the tuple share a type and need disambiguation, but others don't. For example:

type min_max_avg = min:int * max:int * float

## Reordering and partial patterns

Like records, labeled tuple patterns may be reordered or partial. The compiler only supports reordering / partial matching when it knows the type of the pattern from its context.

So, for example, we can write:

let lt = ~x:0, ~y:42
let twice_y = let ~y, .. = lt in y * 2
val lt : x:int * y:int = (~x:0, ~y:42)
val twice_y : int = 84

When the type is not known (in the same sense that we require a type to be known to disambiguate among constructors), the compiler will reject a partial pattern. For example, this program

let get_y t =
    let _y, .. = t in
    y

Error: Could not determine the type of this partial tuple pattern.

This example could be fixed by adding a type annotation to the function's parameter.

Labels may not be repeated in a tuple. However, unlabeled elements can be thought of as all sharing the same unique label. When matching on such a tuple, the first unlabeled element in the pattern is bound to the first unlabeled element in the value, and so on. As a result, it's also possible to partially match on an unlabeled tuple to retrieve the first few elements.

## Limitations

Parentheses are necessary to disambiguate functions types with labeled arguments from function types with labeled tuple arguments when the first element of the tuple has a label.

Unlike records, reordering is not supported in labeled tuple expressions, even when the type is known. This is similar to the way the function definition for a function with labeled arguments must bind the arguments in the same order as the type.

Labeled tuples do not support projection (extracting an element of the tuple by label).
**-cmi-file filename**

Use the given interface file to type-check the ML source file to compile. When this option is not specified, the compiler looks for a `.mli` file with the same base name than the implementation it is compiling and in the same directory. If such a file is found, the compiler looks for a corresponding `.cmi` file in the included directories and reports an error if it fails to find one.

**-color mode**

Enable or disable colors in compiler messages (especially warnings and errors). The following modes are supported:

**auto**

use heuristics to enable colors only if the output supports them (an ANSI-compatible tty terminal);

**always**

enable colors unconditionally;

**never**

disable color output.

The environment variable `OCAML COLOR` is considered if `-color` is not provided. Its values are `auto`/`always`/`never` as above.

If `-color` is not provided, `OCAML COLOR` is not set and the environment variable `NO COLOR` is set, then color output is disabled. Otherwise, the default setting is `'auto'`, and the current heuristic checks that the `TERM` environment variable exists and is not empty or `dumb`, and that `'isatty(stderr)'` holds.

**-error-style mode**

Control the way error messages and warnings are printed. The following modes are supported:

**short**

only print the error and its location;

**contextual**

like `short`, but also display the source code snippet corresponding to the location of the error.

The default setting is `contextual`.

The environment variable `OCAML_ERROR STYLE` is considered if `-error-style` is not provided. Its values are `short`/`contextual` as above.

**-compat-32**

Check that the generated bytecode executable can run on 32-bit platforms and signal an error if it cannot. This is useful when compiling bytecode on a 64-bit machine.

**-config**

Print the version number of `ocamlc` and a detailed summary of its configuration, then exit.

**-config-var var**

Print the value of a specific configuration variable from the `-config` output, then exit. If the
Relationship to flexible records

Labeled tuples are similar in spirit to SML's flexible records. The primary difference is that SML
records are canonically ordered based on label name, while labeled tuples are not. So, for example,
`x:int * y:bool` and `y:bool * x:int` are different types in OCaml, corresponding to two different
orderings of the fields in the runtime block. In SML, the corresponding record types are considered
equal and the runtime block is always ordered with the `x` field first.
variable does not exist, the exit code is non-zero. This option is only available since OCaml
4.08, so script authors should have a fallback for older versions.

-custom

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

Unix:

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

Unix:

Security warning: never set the "setuid" or "setgid" bits on executables produced by ocamlc -custom, this would make them vulnerable to attacks.

-depend ocamldep-args

Compute dependencies, as the **ocamldep** command would do. The remaining arguments are
interpreted as if they were given to the **ocamldep** command.

-dllib -libname

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

-dllpath dir

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

-for-pack module-path

Generate an object file (`.cmo`) that can later be included as a sub-module (with the given
access path) of a compilation unit constructed with `-pack`. For instance, `ocamlc -for-pack P -c A.ml` will generate `a.cmo` that can later be used with `ocamlc -pack -o P.cmo a.cmo`. Note:
you can still pack a module that was compiled without `-for-pack` but in this case exceptions
will be printed with the wrong names.

-g
Add debugging information while compiling and linking. This option is required in order
to be able to debug the program with **ocamldebug** (see chapter 20), and to produce stack
backtraces when the program terminates on an uncaught exception (see section 15.2).

-no-g

Do not record debugging information (default).
# Part III

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

-I *directory*

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

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

-impl *filename*

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

-intf *filename*

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

-intf-suffix *string*

Recognize file names ending with *string* as interface files (instead of the default `.mli`).

-labels

Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default.

-linkall

Force all modules contained in libraries to be linked in. If this flag is not given, unreferenced modules are not linked in. When building a library (option `-a`), setting the `-linkall` option forces all subsequent links of programs involving that library to link all the modules contained in the library. When compiling a module (option `-c`), setting the `-linkall` option ensures that this module will always be linked if it is put in a library and this library is linked.

-make-runtime

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

-match-context-rows

Set the number of rows of context used for optimization during pattern matching compilation. The default value is 32. Lower values cause faster compilation, but less optimized code. This advanced option is meant for use in the event that a pattern-match-heavy program leads to significant increases in compilation time.
<figure><img src="image_5.png" /></figure>
-no-alias-deps

Do not record dependencies for module aliases. See section 12.8 for more information.

-no-app-funct

Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures.

-noassert

Do not compile assertion checks. Note that the special form `assert false` is always compiled because it is typed specially. This flag has no effect when linking already-compiled files.

-noautolink

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

-nolabels

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

-nostdlib

Do not include the standard library directory in the list of directories searched for compiled interface files (`.cmi`), compiled object code files (`.cmo`), libraries (`.cma`), and C libraries specified with `-cclib -lxxx`. See also option `-I`.

-o output-file

Specify the name of the output file to produce. For executable files, the default output name is `a.out` under Unix and `camlprog.exe` under Windows. If the `-a` option is given, specify the name of the library produced. If the `-pack` option is given, specify the name of the packed object file produced. If the `-output-obj` or `-output-complete-obj` options are given, specify the name of the produced object file. If the `-c` option is given, specify the name of the object file produced for the *next* source file that appears on the command line.

-opaque

When the native compiler compiles an implementation, by default it produces a `.cmx` file containing information for cross-module optimization. It also expects `.cmx` files to be present for the dependencies of the currently compiled source, and uses them for optimization. Since OCaml 4.03, the compiler will emit a warning if it is unable to locate the `.cmx` file of one of those dependencies.

The `-opaque` option, available since 4.04, disables cross-module optimization information for the currently compiled unit. When compiling `.mli` interface, using `-opaque` marks the compiled `.cmi` interface so that subsequent compilations of modules that depend on it will not rely on the corresponding `.cmx` file, nor warn if it is absent. When the native compiler compiles a `.ml` implementation, using `-opaque` generates a `.cmx` that does not contain any cross-module optimization information.
Chapter 13

Batch compilation (ocamlc)

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*.

13.1 Overview of the compiler

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, after all options have been processed:

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

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

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

*   Arguments ending in `.cmo` are taken to be compiled object bytecode. These files are linked together, along with the object files obtained by compiling `.ml` arguments (if any), and the OCaml standard library, to produce a standalone executable program. The order in which `.cmo` and `.ml` arguments are presented on the command line is relevant: compilation units are initialized in that order at run-time, and it is a link-time error to use a component of a unit before having initialized it. Hence, a given `x.cmo` file must come before all `.cmo` files that refer to the unit `x`.
Using this option may degrade the quality of generated code, but it reduces compilation time, both on clean and incremental builds. Indeed, with the native compiler, when the implementation of a compilation unit changes, all the units that depend on it may need to be recompiled – because the cross-module information may have changed. If the compilation unit whose implementation changed was compiled with `-opaque`, no such recompilation needs to occur. This option can thus be used, for example, to get faster edit-compile-test feedback loops.

**-open Module**

Opens the given module before processing the interface or implementation files. If several `-open` options are given, they are processed in order, just as if the statements `open! Module1; ; ... open! ModuleN; ;` were added at the top of each file.

**-output-obj**

Cause the linker to produce a C object file instead of a bytecode executable file. This is useful to wrap OCaml code as a C library, callable from any C program. See chapter 22, section 22.7.5. The name of the output object file must be set with the `-o` option. This option can also be used to produce a C source file (`.c` extension) or a compiled shared/dynamic library (`.so` extension, `.dll` under Windows).

**-output-complete-exe**

Build a self-contained executable by linking a C object file containing the bytecode program, the OCaml runtime system and any other static C code given to `ocamlc`. The resulting effect is similar to `-custom`, except that the bytecode is embedded in the C code so it is no longer accessible to tools such as `ocamldebug`. On the other hand, the resulting binary is resistant to `strip`.

**-output-complete-obj**

Same as `-output-obj` options except the object file produced includes the runtime and autolink libraries.

**-pack**

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

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

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

**-pp command**

Cause the compiler to call the given *command* as a preprocessor for each source file. The output of *command* is redirected to an intermediate file, which is compiled. If there are no compilation errors, the intermediate file is deleted afterwards.
* Arguments ending in `.cma` are taken to be libraries of object bytecode. A library of object bytecode packs in a single file a set of object bytecode files (`.cmo` files). Libraries are built with `ocamlc -a` (see the description of the `-a` option below). The object files contained in the library are linked as regular `.cmo` files (see above), in the order specified when the `.cma` file was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in.

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

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

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

The output of the linking phase is a file containing compiled bytecode that can be executed by the 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 15 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 compiler is able to emit some information on its internal stages. It can output `.cmt` files for the implementation of the compilation unit and `.cmti` for signatures if the option `-bin-annot` is passed to it (see the description of `-bin-annot` below). Each such file contains a typed abstract syntax tree (AST), that is produced during the type checking procedure. This tree contains all available information about the location and the specific type of each term in the source file. The AST is partial if type checking was unsuccessful.

These `.cmt` and `.cmti` files are typically useful for code inspection tools.

## 13.2 Options

The following command-line options are recognized by `ocamlc`. The options `-pack`, `-a`, `-c`, `-output-obj` and `-output-complete-obj` are mutually exclusive.
-ppx *command*

After parsing, pipe the abstract syntax tree through the preprocessor *command*. The module *Ast_mapper*, described in section 29.1, implements the external interface of a preprocessor.

-principal

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

-rectypes

Allow arbitrary recursive types during type-checking. By default, only recursive types where the recursion goes through an object type are supported. Note that once you have created an interface using this flag, you must use it again for all dependencies.

-runtime-variant *suffix*

Add the *suffix* string to the name of the runtime library used by the program. Currently, only one such suffix is supported: `d`, and only if the OCaml compiler was configured with option `-with-debug-runtime`. This suffix gives the debug version of the runtime, which is useful for debugging pointer problems in low-level code such as C stubs.

-safe-string

Enforce the separation between types `string` and `bytes`, thereby making strings read-only. This is the default, and enforced since OCaml 5.0.

-safer-matching

Do not use type information to optimize pattern-matching. This allows to detect match failures even if a pattern-matching was wrongly assumed to be exhaustive. This only impacts GADT and polymorphic variant compilation.

-short-paths

When a type is visible under several module-paths, use the shortest one when printing the type's name in inferred interfaces and error and warning messages. Identifier names starting with an underscore `_` or containing double underscores `__` incur a penalty of +10 when computing their length.

-stop-after *pass*

Stop compilation after the given compilation pass. The currently supported passes are: `parsing`, `typing`.

-strict-sequence

Force the left-hand part of each sequence to have type unit.

-strict-formats

Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions.
-a Build a library(`.cma` file) with the object files (`.cmo` files) given on the command line, instead of linking them into an executable file. The name of the library must be set with the `-o` option.

If `-custom`, `-cclib` or `-ccopt` options are passed on the command line, these options are stored in the resulting `.cmalibrary`. 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.

**-absname**

Force error messages to show absolute paths for file names.

**-no-absname**

Do not try to show absolute filenames in error messages.

**-annot**

Deprecated since OCaml 4.11. Please use `-bin-annot` instead.

**-args filename**

Read additional newline-terminated command line arguments from *filename*.

**-args0 filename**

Read additional null character terminated command line arguments from *filename*.

**-bin-annot**

Dump detailed information about the compilation (types, bindings, tail-calls, etc) in binary format. The information for file *src.ml* (resp. *src.mli*) is put into file *src.cmt* (resp. *src.cmti*). In case of a type error, dump all the information inferred by the type-checker before the error. The **.cmt and *.cmti files produced by `-bin-annot` contain more information and are much more compact than the files produced by `-annot`.

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

**-cc ccomp**

Use *ccomp* as the C linker when linking in "custom runtime" mode (see the `-custom` option) and as the C compiler for compiling *.c source files. When linking object files produced by a C++ compiler (such as *g++* or *clang++*), it is recommended to use *-cc c++*.

**-cclib -llibname**

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

**-ccopt option**

Pass the given option to the C compiler and linker. When linking in "custom runtime" mode, for instance `-ccopt -Ldir` causes the C linker to search for C libraries in directory *dir*. (See the `-custom` option.)
**-unboxed-types**

When a type is unboxed (i.e. a record with a single argument or a concrete datatype with a single constructor of one argument) it will be unboxed unless annotated with `[@@ocaml.boxed]`.

**-no-unboxed-types**

When a type is unboxed it will be boxed unless annotated with `[@@ocaml.unboxed]`. This is the default.

**-unsafe**

Turn bound checking off for array and string accesses (the `v.(i)` and `s.[i]` constructs). Programs compiled with `-unsafe` are therefore slightly faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. Additionally, turn off the check for zero divisor in integer division and modulus operations. With `-unsafe`, an integer division (or modulus) by zero can halt the program or continue with an unspecified result instead of raising a `Division_by_zero` exception.

**-unsafe-string**

Identify the types `string` and `bytes`, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0.

**-use-runtime runtime-name**

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

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

**-verbose**

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

**-version or -vnum**

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

**-w warning-list**

Enable, disable, or mark as fatal the warnings specified by the argument `warning-list`. Each warning can be `enabled` or `disabled`, and each warning can be `fatal` or `non-fatal`. If a warning is disabled, it isn't displayed and doesn't affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.

The `warning-list` argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:

**+num**

Enable warning number `num`.
**-cmi-file filename**

Use the given interface file to type-check the ML source file to compile. When this option is not specified, the compiler looks for a `.mli` file with the same base name than the implementation it is compiling and in the same directory. If such a file is found, the compiler looks for a corresponding `.cmi` file in the included directories and reports an error if it fails to find one.

**-color mode**

Enable or disable colors in compiler messages (especially warnings and errors). The following modes are supported:

**auto**

use heuristics to enable colors only if the output supports them (an ANSI-compatible tty terminal);

**always**

enable colors unconditionally;

**never**

disable color output.

The environment variable `OCAML COLOR` is considered if `-color` is not provided. Its values are `auto`/`always`/`never` as above.

If `-color` is not provided, `OCAML COLOR` is not set and the environment variable `NO COLOR` is set, then color output is disabled. Otherwise, the default setting is `'auto'`, and the current heuristic checks that the `TERM` environment variable exists and is not empty or `dumb`, and that `'isatty(stderr)'` holds.

**-error-style mode**

Control the way error messages and warnings are printed. The following modes are supported:

**short**

only print the error and its location;

**contextual**

like `short`, but also display the source code snippet corresponding to the location of the error.

The default setting is `contextual`.

The environment variable `OCAML_ERROR STYLE` is considered if `-error-style` is not provided. Its values are `short`/`contextual` as above.

**-compat-32**

Check that the generated bytecode executable can run on 32-bit platforms and signal an error if it cannot. This is useful when compiling bytecode on a 64-bit machine.

**-config**

Print the version number of `ocamlc` and a detailed summary of its configuration, then exit.

**-config-var var**

Print the value of a specific configuration variable from the `-config` output, then exit. If the
-num

Disable warning number *num*.

@num

Enable and mark as fatal warning number *num*.

+num1..num2

Enable warnings in the given range.

-num1..num2

Disable warnings in the given range.

@num1..num2

Enable and mark as fatal warnings in the given range.

+letter

Enable the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

-letter

Disable the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

@letter

Enable and mark as fatal the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

uppercase-letter

Enable the set of warnings corresponding to *uppercase-letter*.

lowercase-letter

Disable the set of warnings corresponding to *lowercase-letter*.

Alternatively, *warning-list* can specify a single warning using its mnemonic name (see below), as follows:

+name

Enable warning *name*.

-name

Disable warning *name*.

@name

Enable and mark as fatal warning *name*.

Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning).

1 comment-start

Suspicious-looking start-of-comment mark.

2 comment-not-end

Suspicious-looking end-of-comment mark.

3 Deprecated synonym for the 'deprecated' alert.
variable does not exist, the exit code is non-zero. This option is only available since OCaml
4.08, so script authors should have a fallback for older versions.

-custom

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

Unix:

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

Unix:

Security warning: never set the "setuid" or "setgid" bits on executables produced by `ocamlc -custom`, this would make them vulnerable to attacks.

-depend ocamldep-args

Compute dependencies, as the **ocamldep** command would do. The remaining arguments are
interpreted as if they were given to the **ocamldep** command.

-dllib -libname

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

-dllpath dir

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

-for-pack module-path

Generate an object file (`.cmo`) that can later be included as a sub-module (with the given
access path) of a compilation unit constructed with **-pack**. For instance, `ocamlc -for-pack P -c A.ml` will generate `a.cmo` that can later be used with `ocamlc -pack -o P.cmo a.cmo`. Note:
you can still pack a module that was compiled without **-for-pack** but in this case exceptions
will be printed with the wrong names.

-g
Add debugging information while compiling and linking. This option is required in order
to be able to debug the program with **ocamldebug** (see chapter 20), and to produce stack
backtraces when the program terminates on an uncaught exception (see section 15.2).

-no-g

Do not record debugging information (default).
**4 fragile-match**

Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.

**5 ignored-partial-application**

Partially applied function: expression whose result has function type and is ignored.

**6 labels-omitted**

Label omitted in function application.

**7 method-override**

Method overridden.

**8 partial-match**

Partial match: missing cases in pattern-matching.

**9 missing-record-field-pattern**

Missing fields in a record pattern.

**10 non-unit-statement**

Expression on the left-hand side of a sequence that doesn't have type unit (and that is not a function, see warning number 5).

**11 redundant-case**

Redundant case in a pattern matching (unused match case).

**12 redundant-subpat**

Redundant sub-pattern in a pattern-matching.

**13 instance-variable-override**

Instance variable overridden.

**14 illegal-backslash**

Illegal backslash escape in a string constant.

**15 implicit-public-methods**

Private method made public implicitly.

**16 unerasable-optional-argument**

Unerasable optional argument.

**17 undeclared-virtual-method**

Undeclared virtual method.

**18 not-principal**

Non-principal type.

**19 non-principal-labels**

Type without principality.

**20 ignored-extra-argument**

Unused function argument.

**21 nonreturning-statement**

Non-returning statement.

**22 preprocessor**

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

-I *directory*

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

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

-H *directory*

Behaves identically to `-I`, except that (a) programs may not directly refer to modules added to the search path this way, and (b) these directories are searched after any `-I` directories. This makes it possible to provide the compiler with compiled interface and object code files for the current program's transitive dependencies (the dependencies of its dependencies) without allowing them to silently become direct dependencies.

-impl *filename*

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

-intf *filename*

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

-intf-suffix *string*

Recognize file names ending with *string* as interface files (instead of the default `.mli`).

-keywords *version+list*

Set keywords according to the *version+list* specification.

This specification starts with an optional version number, defining the base set of keywords, followed by a `+`-separated list of additional keywords to add to this base set.

Without an explicit version number, the base set of keywords is the set of keywords in the current version of OCaml. Additional keywords that do not match any known keyword in the current version of the language trigger an error whenever they are present in the source code.

-labels

Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default.

-linkall

Force all modules contained in libraries to be linked in. If this flag is not given, unreferenced
**23 useless-record-with**
Useless record with clause.

**24 bad-module-name**
Bad module name: the source file name is not a valid OCaml module name.

**25** Ignored: now part of warning 8.

**26 unused-var**
Suspicious unused variable: unused variable that is bound with `let` or `as`, and doesn't start with an underscore (`_`) character.

**27 unused-var-strict**
Innocuous unused variable: unused variable that is not bound with `let` nor `as`, and doesn't start with an underscore (`_`) character.

**28 wildcard-arg-to-constant-constr**
Wildcard pattern given as argument to a constant constructor.

**29 eol-in-string**
Unescaped end-of-line in a string constant (non-portable code).

**30 duplicate-definitions**
Two labels or constructors of the same name are defined in two mutually recursive types.

**31 module-linked-twice**
A module is linked twice in the same executable.

**I** ignored: now a hard error (since 5.1).

**32 unused-value-declaration**
Unused value declaration. (since 4.00)

**33 unused-open**
Unused open statement. (since 4.00)

**34 unused-type-declaration**
Unused type declaration. (since 4.00)

**35 unused-for-index**
Unused for-loop index. (since 4.00)

**36 unused-ancestor**
Unused ancestor variable. (since 4.00)

**37 unused-constructor**
Unused constructor. (since 4.00)

**38 unused-extension**
Unused extension constructor. (since 4.00)

**39 unused-rec-flag**
Unused rec flag. (since 4.00)

**40 name-out-of-scope**
Constructor or label name used out of scope. (since 4.01)

**41 ambiguous-name**
Ambiguous constructor or label name. (since 4.01)
modules are not linked in. When building a library (option `-a`), setting the `-linkall` option forces all subsequent links of programs involving that library to link all the modules contained in the library. When compiling a module (option `-c`), setting the `-linkall` option ensures that this module will always be linked if it is put in a library and this library is linked.

**-make-runtime**

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

**-match-context-rows**

Set the number of rows of context used for optimization during pattern matching compilation. The default value is 32. Lower values cause faster compilation, but less optimized code. This advanced option is meant for use in the event that a pattern-match-heavy program leads to significant increases in compilation time.

**-no-alias-deps**

Do not record dependencies for module aliases. See section 12.8 for more information.

**-no-app-funct**

Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures.

**-noassert**

Do not compile assertion checks. Note that the special form `assert false` is always compiled because it is typed specially. This flag has no effect when linking already-compiled files.

**-noautolink**

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

**-nolabels**

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

**-nostdlib**

Do not include the standard library directory in the list of directories searched for compiled interface files (`.cmi`), compiled object code files (`.cmo`), libraries (`.cma`), and C libraries specified with `-cclib -lxxx`. See also option `-I`.

**-o output-file**

Specify the name of the output file to produce. For executable files, the default output name is `a.out` under Unix and `camlprog.exe` under Windows. If the `-a` option is given, specify the name of the library produced. If the `-pack` option is given, specify the name of the packed
**42** `disambiguated-name`
Disambiguated constructor or label name (compatibility warning). (since 4.01)

**43** `nonoptional-label`
Nonoptional label applied as optional. (since 4.01)

**44** `open-shadow-identifier`
Open statement shadows an already defined identifier. (since 4.01)

**45** `open-shadow-label-constructor`
Open statement shadows an already defined label or constructor. (since 4.01)

**46** `bad-env-variable`
Error in environment variable. (since 4.01)

**47** `attribute-payload`
Illegal attribute payload. (since 4.02)

**48** `eliminated-optional-arguments`
Implicit elimination of optional arguments. (since 4.02)

**49** `no-cmi-file`
Absent cmi file when looking up module alias. (since 4.02)

**50** `unexpected-docstring`
Unexpected documentation comment. (since 4.03)

**51** `wrong-tailcall-expectation`
Function call annotated with an incorrect @tailcall attribute. (since 4.03)

**52** `fragile-literal-pattern` (see 13.5.3)
Fragile constant pattern. (since 4.03)

**53** `misplaced-attribute`
Attribute cannot appear in this context. (since 4.03)

**54** `duplicated-attribute`
Attribute used more than once on an expression. (since 4.03)

**55** `inlining-impossible`
Inlining impossible. (since 4.03)

**56** `unreachable-case`
Unreachable case in a pattern-matching (based on type information). (since 4.03)

**57** `ambiguous-var-in-pattern-guard` (see 13.5.4)
Ambiguous or-pattern variables under guard. (since 4.03)

**58** `no-cmx-file`
Missing cmx file. (since 4.03)

**59** `flambda-assignment-to-non-mutable-value`
Assignment to non-mutable value. (since 4.03)

**60** `unused-module`
Unused module declaration. (since 4.04)

**61** `unboxable-type-in-prim-decl`
Unboxable type in primitive declaration. (since 4.04)
object file produced. If the `-output-obj` or `-output-complete-obj` options are given, specify the name of the produced object file. If the `-c` option is given, specify the name of the object file produced for the *next* source file that appears on the command line.

**-opaque**

When the native compiler compiles an implementation, by default it produces a `.cmx` file containing information for cross-module optimization. It also expects `.cmx` files to be present for the dependencies of the currently compiled source, and uses them for optimization. Since OCaml 4.03, the compiler will emit a warning if it is unable to locate the `.cmx` file of one of those dependencies.

The `-opaque` option, available since 4.04, disables cross-module optimization information for the currently compiled unit. When compiling `.mli` interface, using `-opaque` marks the compiled `.cmi` interface so that subsequent compilations of modules that depend on it will not rely on the corresponding `.cmx` file, nor warn if it is absent. When the native compiler compiles a `.ml` implementation, using `-opaque` generates a `.cmx` that does not contain any cross-module optimization information.

Using this option may degrade the quality of generated code, but it reduces compilation time, both on clean and incremental builds. Indeed, with the native compiler, when the implementation of a compilation unit changes, all the units that depend on it may need to be recompiled – because the cross-module information may have changed. If the compilation unit whose implementation changed was compiled with `-opaque`, no such recompilation needs to occur. This option can thus be used, for example, to get faster edit-compile-test feedback loops.

**-open Module**

Opens the given module before processing the interface or implementation files. If several `-open` options are given, they are processed in order, just as if the statements `open! Module1;`;
`... open! ModuleN;`; were added at the top of each file.

**-output-obj**

Cause the linker to produce a C object file instead of a bytecode executable file. This is useful to wrap OCaml code as a C library, callable from any C program. See chapter 22, section 22.7.6. The name of the output object file must be set with the `-o` option. This option can also be used to produce a C source file (`.c` extension) or a compiled shared/dynamic library (`.so` extension, `.dll` under Windows).

**-output-complete-exe**

Build a self-contained executable by linking a C object file containing the bytecode program, the OCaml runtime system and any other static C code given to `ocamlc`. The resulting effect is similar to `-custom`, except that the bytecode is embedded in the C code so it is no longer accessible to tools such as `ocamldebug`. On the other hand, the resulting binary is resistant to `strip`.

**-output-complete-obj**

Same as `-output-obj` options except the object file produced includes the runtime and autolink libraries.
**62 constraint-on-gadt**
Type constraint on GADT type declaration. (since 4.06)

**63 erroneous-printed-signature**
Erroneous printed signature. (since 4.08)

**64 unsafe-array-syntax-without-parsing**
-unsafe used with a preprocessor returning a syntax tree. (since 4.08)

**65 redefining-unit**
Type declaration defining a new '()' constructor. (since 4.08)

**66 unused-open-bang**
Unused open! statement. (since 4.08)

**67 unused-functor-parameter**
Unused functor parameter. (since 4.10)

**68 match-on-mutable-state-prevent-uncurry**
Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12)

**69 unused-field**
Unused record field. (since 4.13)

**70 missing-mli**
Missing interface file. (since 4.13)

**71 unused-tmc-attribute**
Unused @tail\_mod\_cons attribute. (since 4.14)

**72 tmc-breaks-tailcall**
A tail call is turned into a non-tail call by the @tail\_mod\_cons transformation. (since 4.14)

**73 generative-application-expects-unit**
A generative functor is applied to an empty structure (struct end) rather than to (). (since 5.1)

**A** all warnings

**C** warnings 1, 2.

**D** Alias for warning 3.

**E** Alias for warning 4.

**F** Alias for warning 5.

**K** warnings 32, 33, 34, 35, 36, 37, 38, 39.

**L** Alias for warning 6.

**M** Alias for warning 7.

**P** Alias for warning 8.

**R** Alias for warning 9.

**S** Alias for warning 10.

**U** warnings 11, 12.
-pack

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

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

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

-pp *command*

Cause the compiler to call the given *command* as a preprocessor for each source file. The output of *command* is redirected to an intermediate file, which is compiled. If there are no compilation errors, the intermediate file is deleted afterwards.

-ppx *command*

After parsing, pipe the abstract syntax tree through the preprocessor *command*. The module *Ast_mapper*, described in section 30.1, implements the external interface of a preprocessor.

-principal

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

-rectypes

Allow arbitrary recursive types during type-checking. By default, only recursive types where the recursion goes through an object type are supported. Note that once you have created an interface using this flag, you must use it again for all dependencies.

-runtime-variant *suffix*

Add the *suffix* string to the name of the runtime library used by the program. Currently, only one such suffix is supported: `d`, and only if the OCaml compiler was configured with option `-with-debug-runtime`. This suffix gives the debug version of the runtime, which is useful for debugging pointer problems in low-level code such as C stubs.

-safe-string

Enforce the separation between types `string` and `bytes`, thereby making strings read-only. This is the default, and enforced since OCaml 5.0.

-safer-matching

Do not use type information to optimize pattern-matching. This allows to detect match failures even if a pattern-matching was wrongly assumed to be exhaustive. This only impacts GADT and polymorphic variant compilation.
**V** Alias for warning 13.

**X** warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.

**Y** Alias for warning 26.

**Z** Alias for warning 27.

The default setting is `-w +a-4-6-7-9-27-29-32..42-44-45-48-50-60`. It is displayed by `ocamlc -help`. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.

**-warn-error warning-list**

Mark as fatal the warnings specified in the argument `warning-list`. The compiler will stop with an error when one of these warnings is emitted. The `warning-list` has the same meaning as for the `-w` option: a `+` sign (or an uppercase letter) marks the corresponding warnings as fatal, a `-` sign (or a lowercase letter) turns them back into non-fatal warnings, and a `@` sign both enables and marks as fatal the corresponding warnings.

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` (no warning is fatal).

**-warn-help**

Show the description of all available warning numbers.

**-where**

Print the location of the standard library, then exit.

**-with-runtime**

Include the runtime system in the generated program. This is the default.

**-without-runtime**

The compiler does not include the runtime system (nor a reference to it) in the generated program; it must be supplied separately.

**-file**

Process *file* as a file name, even if it starts with a dash (`-`) character.

**-help or --help**

Display a short usage summary and exit.

**contextual-cli-control** Contextual control of command-line options

The compiler command line can be modified "from the outside" with the following mechanisms. These are experimental and subject to change. They should be used only for experimental and development work, not in released packages.

**OCAMLPARAM** (environment variable)

A set of arguments that will be inserted before or after the arguments from the command
-short-paths

When a type is visible under several module-paths, use the shortest one when printing the type's name in inferred interfaces and error and warning messages. Identifier names starting with an underscore `_` or containing double underscores `__` incur a penalty of +10 when computing their length.

-stop-after pass

Stop compilation after the given compilation pass. The currently supported passes are: `parsing`, `typing`.

-strict-sequence

Force the left-hand part of each sequence to have type unit.

-strict-formats

Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions.

-unboxed-types

When a type is unboxed (i.e. a record with a single argument or a concrete datatype with a single constructor of one argument) it will be unboxed unless annotated with `[@@ocaml.boxed]`.

-no-unboxed-types

When a type is unboxed it will be boxed unless annotated with `[@@ocaml.unboxed]`. This is the default.

-unsafe

Turn bound checking off for array and string accesses (the `v.(i)` and `s.[i]` constructs). Programs compiled with `-unsafe` are therefore slightly faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. Additionally, turn off the check for zero divisor in integer division and modulus operations. With `-unsafe`, an integer division (or modulus) by zero can halt the program or continue with an unspecified result instead of raising a `Division_by_zero` exception.

-unsafe-string

Identify the types `string` and `bytes`, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0.

-use-runtime runtime-name

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

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

-verbose

Print all external commands before they are executed, in particular invocations of the C compiler and linker in `-custom` mode. Useful to debug C library problems.
line. Arguments are specified in a comma-separated list of `name=value` pairs. A `_` is used to specify the position of the command line arguments, i.e. `a=x,_,b=y` means that `a=x` should be executed before parsing the arguments, and `b=y` after. Finally, an alternative separator can be specified as the first character of the string, within the set `:|;,.`.

**ocaml_COMPILER_internal_params (file in the stdlib directory)**

A mapping of file names to lists of arguments that will be added to the command line (and `OCAMLPARAM`) arguments.

**OCAML_FLEXLINK (environment variable)**

Alternative executable to use on native Windows for `flexlink` instead of the configured value. Primarily used for bootstrapping.

## 13.3 Modules and the file system

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 sets 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.

## 13.4 Common errors

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

**Cannot find file filename**

The named file could not be found in the current directory, nor in the directories of the search path. The `filename` is either a compiled interface file (`.cmi` file), or a compiled bytecode
**-version or -vnum**

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

**-w warning-list**

Enable, disable, or mark as fatal the warnings specified by the argument `warning-list`. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn't displayed and doesn't affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.

The `warning-list` argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:

**+num**

Enable warning number `num`.

**-num**

Disable warning number `num`.

**@num**

Enable and mark as fatal warning number `num`.

**+num1..num2**

Enable warnings in the given range.

**-num1..num2**

Disable warnings in the given range.

**@num1..num2**

Enable and mark as fatal warnings in the given range.

**+letter**

Enable the set of warnings corresponding to `letter`. The letter may be uppercase or lowercase.

**-letter**

Disable the set of warnings corresponding to `letter`. The letter may be uppercase or lowercase.

**@letter**

Enable and mark as fatal the set of warnings corresponding to `letter`. The letter may be uppercase or lowercase.

**uppercase-letter**

Enable the set of warnings corresponding to `uppercase-letter`.

**lowercase-letter**

Disable the set of warnings corresponding to `lowercase-letter`.

Alternatively, `warning-list` can specify a single warning using its mnemonic name (see below), as follows:

**+name**

Enable warning `name`.
file (`.cmo` file). If `filename` has the format `mod.cmi`, this means you are trying to compile a file that references identifiers from module `mod`, but you have not yet compiled an interface for module `mod`. Fix: compile `mod.mli` or `mod.ml` first, to create the compiled interface `mod.cmi`.

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

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

### Corrupted compiled interface filename

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

### This expression has type $t_1$, but is used with type $t_2$

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

In some cases, it is hard to understand why the two types $t_1$ and $t_2$ 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 -> O | 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`".

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

Type variables (`'a`, `'b`, ...) in a type `t` can be in either of two states: generalized (which means that the type `t` is valid for all possible instantiations of the variables) and not generalized (which means that the type `t` is valid only for one instantiation of the variables). In a `let` binding `let name = expr`, the type-checker normally generalizes as many type variables as possible in the type of `expr`. However, this leads to unsoundness (a well-typed program can crash) in conjunction with polymorphic mutable data structures. To avoid this, generalization is performed at `let` bindings only if the bound expression `expr` belongs to the class of "syntactic values", which includes constants, identifiers, functions, tuples of syntactic values, etc. In all other cases (for instance, `expr` is a function application), a polymorphic mutable could
**-name**

Disable warning *name*.

**@name**

Enable and mark as fatal warning *name*.

Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning).

**1 comment-start**

Suspicious-looking start-of-comment mark.

**2 comment-not-end**

Suspicious-looking end-of-comment mark.

**3 Deprecated synonym for the 'deprecated' alert.**

**4 fragile-match**

Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.

**5 ignored-partial-application**

Partially applied function: expression whose result has function type and is ignored.

**6 labels-omitted**

Label omitted in function application.

**7 method-override**

Method overridden.

**8 partial-match**

Partial match: missing cases in pattern-matching.

**9 missing-record-field-pattern**

Missing fields in a record pattern.

**10 non-unit-statement**

Expression on the left-hand side of a sequence that doesn't have type *unit* (and that is not a function, see warning number 5).

**11 redundant-case**

Redundant case in a pattern matching (unused match case).

**12 redundant-subpat**

Redundant sub-pattern in a pattern-matching.

**13 instance-variable-override**

Instance variable overridden.

**14 illegal-backslash**

Illegal backslash escape in a string constant.

**15 implicit-public-methods**

Private method made public implicitly.

**16 unerasable-optional-argument**

Unerasable optional argument.
have been created and generalization is therefore turned off for all variables occurring in
contravariant or non-variant branches of the type. For instance, if the type of a non-value
is 'a list the variable is generalizable (list is a covariant type constructor), but not in
'a list -> 'a list (the left branch of -> is contravariant) or 'a ref (ref is non-variant).

Non-generaldized 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-generaldized type variables. There are two
ways to fix this error:

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

```hml
let sort_int_list = List.sort Stdlib compares
(* inferred type 'a list -> 'a list, with 'a not generalized *)
```

write

```hml
let sort_int_list = (List.sort Stdlib compares : int list -> int list);
```

* If you really need *name* to have a polymorphic type, turn its defining expression into a function by adding an extra parameter. For instance, instead of writing

```hml
let map_length = List.map Array.length
(* inferred type 'a array list -> int list, with 'a not generalized *)
```

write

```hml
let map_length lv = List.map Array.length lv
```

## Reference to undefined global *mod*

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

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

* Put *f* and *g* in the same module.

* Parameterize one function by the other. That is, instead of having

```hml
mod1.ml: let f x = ... Mod2.g ...
```

```hml
mod2.ml: let g y = ... Mod1.f ...
```
**17 undeclared-virtual-method**
Undeclared virtual method.

**18 not-principal**
Non-principal type.

**19 non-principal-labels**
Type without principality.

**20 ignored-extra-argument**
Unused function argument.

**21 nonreturning-statement**
Non-returning statement.

**22 preprocessor**
Preprocessor warning.

**23 useless-record-with**
Useless record with clause.

**24 bad-module-name**
Bad module name: the source file name is not a valid OCaml module name.

**25 Ignored:** now part of warning 8.

**26 unused-var**
Suspicious unused variable: unused variable that is bound with `let` or `as`, and doesn't start with an underscore (`_`) character.

**27 unused-var-strict**
Innocuous unused variable: unused variable that is not bound with `let` nor `as`, and doesn't start with an underscore (`_`) character.

**28 wildcard-arg-to-constant-constr**
Wildcard pattern given as argument to a constant constructor.

**29 eol-in-string**
Unescaped end-of-line in a string constant (non-portable code).

**30 duplicate-definitions**
Two labels or constructors of the same name are defined in two mutually recursive types.

**31 module-linked-twice**
A module is linked twice in the same executable.

**I ignored:** now a hard error (since 5.1).

**32 unused-value-declaration**
Unused value declaration. (since 4.00)

**33 unused-open**
Unused open statement. (since 4.00)

**34 unused-type-declaration**
Unused type declaration. (since 4.00)

**35 unused-for-index**
Unused for-loop index. (since 4.00)
define

mod1.ml: let f g x = ... g ...
mod2.ml: let rec g y = ... Mod1.f g ...

and link mod1.cmo before mod2.cmo.

* Use a reference to hold one of the two functions, as in :

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

### The external function *f* is not available

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

## 13.5 Warning reference

This section describes and explains in detail some warnings:

### 13.5.1 Warning 6: Label omitted in function application

OCaml supports *labels-omitted* full applications: 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.

let f ~x ~y = x + y
let test = f 2 3

> let test = f 2 3

>

> Warning 6 [labels-omitted]: labels x, y were omitted in the application of this function.

This support for *labels-omitted* application was introduced when labels were added to OCaml, to ease the progressive introduction of labels in a codebase. However, it has the downside of weakening the labeling discipline: if you use labels to prevent callers from mistakenly reordering two parameters of the same type, *labels-omitted* make this mistake possible again.

Warning 6 warns when *labels-omitted* applications are used, to discourage their use. When labels were introduced, this warning was not enabled by default, so users would use *labels-omitted* applications, often without noticing.
**36 unused-ancestor**
Unused ancestor variable. (since 4.00)

**37 unused-constructor**
Unused constructor. (since 4.00)

**38 unused-extension**
Unused extension constructor. (since 4.00)

**39 unused-rec-flag**
Unused rec flag. (since 4.00)

**40 name-out-of-scope**
Constructor or label name used out of scope. (since 4.01)

**41 ambiguous-name**
Ambiguous constructor or label name. (since 4.01)

**42 disambiguated-name**
Disambiguated constructor or label name (compatibility warning). (since 4.01)

**43 nonoptional-label**
Nonoptional label applied as optional. (since 4.01)

**44 open-shadow-identifier**
Open statement shadows an already defined identifier. (since 4.01)

**45 open-shadow-label-constructor**
Open statement shadows an already defined label or constructor. (since 4.01)

**46 bad-env-variable**
Error in environment variable. (since 4.01)

**47 attribute-payload**
Illegal attribute payload. (since 4.02)

**48 eliminated-optional-arguments**
Implicit elimination of optional arguments. (since 4.02)

**49 no-cmi-file**
Absent cmi file when looking up module alias. (since 4.02)

**50 unexpected-docstring**
Unexpected documentation comment. (since 4.03)

**51 wrong-tailcall-expectation**
Function call annotated with an incorrect @tailcall attribute. (since 4.03)

**52 fragile-literal-pattern (see 13.5.3)**
Fragile constant pattern. (since 4.03)

**53 misplaced-attribute**
Attribute cannot appear in this context. (since 4.03)

**54 duplicated-attribute**
Attribute used more than once on an expression. (since 4.03)

**55 inlining-impossible**
Inlining impossible. (since 4.03)
Over time, it has become idiomatic to enable this warning to avoid argument-order mistakes. The warning is now on by default, since OCaml 4.13. Labels-omitted applications are not recommended anymore, but users wishing to preserve this transitory style can disable the warning explicitly.

### 13.5.2 Warning 9: missing fields in a record pattern

When pattern matching on records, it can be useful to match only few fields of a record. Eliding fields can be done either implicitly or explicitly by ending the record pattern with `; _`. However, implicit field elision is at odd with pattern matching exhaustiveness checks. Enabling warning 9 prioritizes exhaustiveness checks over the convenience of implicit field elision and will warn on implicit field elision in record patterns. In particular, this warning can help to spot exhaustive record pattern that may need to be updated after the addition of new fields to a record type.

```hml
type 'a point = {x : 'a; y : 'a}
```

```hml
let dx { x } = x (* implicit field elision: trigger warning 9 *)
```

```hml
let dy { y; _ } = y (* explicit field elision: do not trigger warning 9 *)
```

### 13.5.3 Warning 52: fragile constant pattern

Some constructors, such as the exception constructors `Failure` and `Invalid_argument`, take as parameter a `string` value holding a text message intended for the user.

These text messages are usually not stable over time: call sites building these constructors may refine the message in a future version to make it more explicit, etc. Therefore, it is dangerous to match over the precise value of the message. For example, until OCaml 4.02, `Array.iter2` would raise the exception

```
Invalid_argument "arrays must have the same length"
```

Since 4.03 it raises the more helpful message

```
Invalid_argument "Array.iter2: arrays must have the same length"
```

but this means that any code of the form

```hml
try ...
```

```hml
with Invalid_argument "arrays must have the same length" -> ...
```

is now broken and may suffer from uncaught exceptions.

Warning 52 is there to prevent users from writing such fragile code in the first place. It does not occur on every matching on a literal string, but only in the case in which library authors expressed their intent to possibly change the constructor parameter value in the future, by using the attribute `ocaml.warn_on_literal_pattern` (see the manual section on builtin attributes in 12.12.1):

```hml
type t =
```

```hml
| Foo of string [@ocaml.warn_on_literal_pattern]
```

```hml
| Bar of string
```

```hml
let no_warning = function
```

```hml
| Bar "specific value" -> 0
```
**56 unreachable-case**
Unreachable case in a pattern-matching (based on type information). (since 4.03)

**57 ambiguous-var-in-pattern-guard** (see 13.5.4)
Ambiguous or-pattern variables under guard. (since 4.03)

**58 no-cmx-file**
Missing cmx file. (since 4.03)

**59 lambda-assignment-to-non-mutable-value**
Assignment to non-mutable value. (since 4.03)

**60 unused-module**
Unused module declaration. (since 4.04)

**61 unboxed-type-in-prim-decl**
Unboxed type in primitive declaration. (since 4.04)

**62 constraint-on-gadt**
Type constraint on GADT type declaration. (since 4.06)

**63 erroneous-printed-signature**
Erroneous printed signature. (since 4.08)

**64 unsafe-array-syntax-without-parsing**
-unsafe used with a preprocessor returning a syntax tree. (since 4.08)

**65 redefining-unit**
Type declaration defining a new '()' constructor. (since 4.08)

**66 unused-open-bang**
Unused open! statement. (since 4.08)

**67 unused-functor-parameter**
Unused functor parameter. (since 4.10)

**68 match-on-mutable-state-prevent-uncurry**
Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12)

**69 unused-field**
Unused record field. (since 4.13)

**70 missing-mli**
Missing interface file. (since 4.13)

**71 unused-tmc-attribute**
Unused @tail_mod_cons attribute. (since 4.14)

**72 tmc-breaks-tailcall**
A tail call is turned into a non-tail call by the @tail_mod_cons transformation. (since 4.14)

**73 generative-application-expects-unit**
A generative functor is applied to an empty structure (struct end) rather than to (). (since 5.1)

**74 degraded-to-partial-match**
A pattern-matching is compiled as partial even if it appears to be total. (since 5.3)
| _ -> 1

let warning = function

| Foo "specific value" -> 0

| _ -> 1

Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of this constructor's arguments. They are only for information and may change in future versions. (see manual section 13.5.3)

In particular, all built-in exceptions with a string argument have this attribute set: Invalid_argument, Failure, Sys_error will all raise this warning if you match for a specific string argument.

Additionally, built-in exceptions with a structured argument that includes a string also have the attribute set: `Assert_failure` and `Match_failure` will raise the warning for a pattern that uses a literal string to match the first element of their tuple argument.

If your code raises this warning, you should *not* change the way you test for the specific string to avoid the warning (for example using a string equality inside the right-hand-side instead of a literal pattern), as your code would remain fragile. You should instead enlarge the scope of the pattern by matching on all possible values.

let warning = function

| Foo _ -> 0

| _ -> 1

This may require some care: if the scrutinee may return several different cases of the same pattern, or raise distinct instances of the same exception, you may need to modify your code to separate those several cases.

For example,

try (int_of_string count_str, bool_of_string choice_str) with

| Failure "int_of_string" -> (0, true)

| Failure "bool_of_string" -> (-1, false)

should be rewritten into more atomic tests. For example, using the `exception` patterns documented in Section 11.6.1, one can write:

match int_of_string count_str with

| exception (Failure_) -> (0, true)

| count ->

begin match bool_of_string choice_str with

| exception (Failure_) -> (-1, false)

| choice -> (count, choice)

end

The only case where that transformation is not possible is if a given function call may raise distinct exceptions with the same constructor but different string values. In this case, you will have to check for specific string values. This is dangerous API design and it should be discouraged: it's better to define more precise exception constructors than store useful information in strings.
### 75 unnecessarily-partial-tuple-pattern

A tuple pattern ends in `..` but fully matches its expected type. (since 5.4)

**A** all warnings

**C** warnings 1, 2.

**D** Alias for warning 3.

**E** Alias for warning 4.

**F** Alias for warning 5.

**K** warnings 32, 33, 34, 35, 36, 37, 38, 39.

**L** Alias for warning 6.

**M** Alias for warning 7.

**P** Alias for warning 8.

**R** Alias for warning 9.

**S** Alias for warning 10.

**U** warnings 11, 12.

**V** Alias for warning 13.

**X** warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.

**Y** Alias for warning 26.

**Z** Alias for warning 27.

The default setting is `-w +a-4-6-7-9-27-29-32..42-44-45-48-50-60`. It is displayed by `ocamlc -help`. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.

### -warn-error warning-list

Mark as fatal the warnings specified in the argument `warning-list`. The compiler will stop with an error when one of these warnings is emitted. The `warning-list` has the same meaning as for the `-w` option: a `+` sign (or an uppercase letter) marks the corresponding warnings as fatal, a `-` sign (or a lowercase letter) turns them back into non-fatal warnings, and a `@` sign both enables and marks as fatal the corresponding warnings.

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` (no warning is fatal).

### -warn-help

Show the description of all available warning numbers.

### -where

Print the location of the standard library, then exit.
### 13.5.4 Warning 57: Ambiguous or-pattern variables under guard

The semantics of or-patterns in OCaml is specified with a left-to-right bias: a value `v` matches the pattern `p | q` if it matches `p` or `q`, but if it matches both, the environment captured by the match is the environment captured by `p`, never the one captured by `q`.

While this property is generally intuitive, there is at least one specific case where a different semantics might be expected. Consider a pattern followed by a when-guard: `| p when g -> e`, for example:

```
| ((Const x,_) | (__, Const x)) when is_neutral x -> branch
```

The semantics is clear: match the scrutinee against the pattern, if it matches, test the guard, and if the guard passes, take the branch. In particular, consider the input `(Const a, Const b)`, where `a` fails the test `is_neutral a`, while `b` passes the test `is_neutral b`. With the left-to-right semantics, the clause above is *not* taken by its input: matching `(Const a, Const b)` against the or-pattern succeeds in the left branch, it returns the environment `x -> a`, and then the guard `is_neutral a` is tested and fails, the branch is not taken.

However, another semantics may be considered more natural here: any pair that has one side passing the test will take the branch. With this semantics the previous code fragment would be equivalent to

```
| (Const x,_) when is_neutral x -> branch
```

```
| (__, Const x) when is_neutral x -> branch
```

This is *not* the semantics adopted by OCaml.

Warning 57 is dedicated to these confusing cases where the specified left-to-right semantics is not equivalent to a non-deterministic semantics (any branch can be taken) relatively to a specific guard. More precisely, it warns when guard uses “ambiguous” variables, that are bound to different parts of the scrutinees by different sides of a or-pattern.
**-with-runtime**

The pair of options `-with-runtime` and `-without-runtime` give precise control over the way the runtime is linked. `-with-runtime` is the default. In summary, it instructs to include the runtime system, or a reference to the default path of the runtime system, in the generated program/executable/object file. The detailed behaviour depends on the compiler and options used:

For ocamlc, in its default linking mode (no use of `-custom` or `-output-*`), `-with-runtime` creates a file which can be executed, whereas `-without-runtime` creates a pure bytecode image which must be explicitly passed to a runtime (i.e. `./foo` vs `ocamlrun ./foo`).

For all other uses of ocamlc and ocamlopt, `-with-runtime` and `-without-runtime` control whether the compiler passes flags for linking with the installed runtime (`-with-runtime`) or whether the user is required to pass them (`-without-runtime`).

For more information about the options `-custom` and `-output-*`, see their documentation and section 22.7.6 of the manual.

**-without-runtime**

The compiler does not include the runtime system (nor a reference to it) in the generated program, executable or object file; it must be supplied separately. See option `-with-runtime` for details.

**-file**

Process *file* as a file name, even if it starts with a dash (`-`) character.

**-help** or `--help`

Display a short usage summary and exit.

**contextual-cli-control** Contextual control of command-line options

The compiler command line can be modified "from the outside" with the following mechanisms. These are experimental and subject to change. They should be used only for experimental and development work, not in released packages.

**OCAMLPARAM** (environment variable)

A set of arguments that will be inserted before or after the arguments from the command line. Arguments are specified in a comma-separated list of `name=value` pairs. A `_` is used to specify the position of the command line arguments, i.e. `a=x,_,b=y` means that `a=x` should be executed before parsing the arguments, and `b=y` after. Finally, an alternative separator can be specified as the first character of the string, within the set `:|;,.`.

**ocaml_COMPILER_internal_params** (file in the stdlib directory)

A mapping of file names to lists of arguments that will be added to the command line (and `OCAMLPARAM`) arguments.

## 13.3 Modules and the file system

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 sets 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.

## 13.4 Common errors

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

### Cannot find file filename

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

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

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

### Corrupted compiled interface filename

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

### This expression has type $t_1$, but is used with type $t_2$

This is by far the most common type error in programs. Type $t_1$ is the type inferred for the
# Chapter 14

## The toplevel system or REPL (ocaml)

This chapter describes the toplevel system for OCaml, that permits interactive use of the OCaml system through a read-eval-print loop (REPL). 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:

```
toplevel-input ::= {definition}^+ ;;
                  | expr ;;
                  | # ident [directive-argument] ;;
```

```
directive-argument ::= string-literal
                      | integer-literal
                      | value-path
                      | true | false
```

A phrase can consist of a definition, like 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 value expression (section 11.7). It is simply evaluated without performing any bindings, and its value 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 14.2.

### Unix:

The toplevel system is started by the command `ocaml`, as follows:

```
ocaml options objects                  # interactive mode
ocaml options objects scriptfile       # script mode
```

`options` are described below. `objects` are filenames ending in `.cmo` or `.cma`; they are loaded into the interpreter immediately after `options` are set. `scriptfile` is any file name not ending in `.cmo` or `.cma`.
expression (the part of the program that is displayed in the error message), by looking at the expression itself. Type $t_2$ is the type expected by the context of the expression; it is deduced by looking at how the value of this expression is used in the rest of the program. If the two types $t_1$ and $t_2$ are not compatible, then the error above is produced.

In some cases, it is hard to understand why the two types $t_1$ and $t_2$ 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 -> O | 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`".

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

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

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

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

```
let sort_int_list = List.sort Stdlib compares
(* inferred type 'a list -> 'a list, with 'a not generalized *)
```

write

```
let sort_int_list = (List.sort Stdlib compares : int list -> int list);
```
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 14.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 14.2. The evaluation outcode for each phrase are not displayed. If the current directory does not contain an `.ocamlinit` file, the file `XDG_CONFIG_HOME/ocaml/init.ml` is looked up according to the XDG base directory specification and used instead (on Windows this is skipped). If that file doesn't exist then an [.ocamlinit] file in the users' home directory (determined via environment variable `HOME`) is used if existing.

The toplevel system does not perform line editing, but it can easily be used in conjunction with an external line editor such as `ledit`, or `rlwrap`. An improved toplevel, `utop`, is also available. 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 14.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

## 14.1 Options

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

**-absname**

Force error messages to show absolute paths for file names.

**-no-absname**

Do not try to show absolute filenames in error messages.

**-args filename**

Read additional newline-terminated command line arguments from *filename*. It is not possible to pass a *scriptfile* via file to the toplevel.
* If you really need *name* to have a polymorphic type, turn its defining expression into a function by adding an extra parameter. For instance, instead of writing

```hml
let map_length = List.map Array.length
(* inferred type 'a array list -> int list, with 'a not generalized *)
```

write

```hml
let map_length lv = List.map Array.length lv
```

### Reference to undefined global *mod*

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

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

* Put *f* and *g* in the same module.

* Parameterize one function by the other. That is, instead of having

```hml
mod1.ml:  let f x = ... Mod2.g ...
mod2.ml:  let g y = ... Mod1.f ...
```

define

```hml
mod1.ml:  let f g x = ... g ...
mod2.ml:  let rec g y = ... Mod1.f g ...
```

and link *mod1.cmo* before *mod2.cmo*.

* Use a reference to hold one of the two functions, as in:

```hml
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
```

### The external function *f* is not available

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

Read additional null character terminated command line arguments from *filename*. It is not possible to pass a *scriptfile* via file to the toplevel.

**-I directory**

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

If the given directory starts with +, it is taken relative to the standard library directory. For instance, -I +unix adds the subdirectory unix 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 14.2).

**-init file**

Load the given file instead of the default initialization file. The default file is .ocamlinit in the current directory if it exists, otherwise XDG_CONFIG_HOME/ocaml/init.ml or .ocamlinit in the user's home directory.

**-labels**

Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default.

**-no-app-funct**

Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures.

**-noassert**

Do not compile assertion checks. Note that the special form `assert false` is always compiled because it is typed specially.

**-nolabels**

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

**-noprompt**

Do not display any prompt when waiting for input.

**-nopromptcont**

Do not display the secondary prompt when waiting for continuation lines in multi-line inputs. This should be used e.g. when running ocaml in an emacs window.

**-nostdlib**

Do not include the standard library directory in the list of directories searched for source and compiled files.
## 13.5 Warning reference

This section describes and explains in detail some warnings:

### 13.5.1 Warning 6: Label omitted in function application

OCaml supports `labels-omitted` full applications: 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.

```ocaml
let f ~x ~y = x + y
let test = f 2 3
```

```
> let test = f 2 3
```

```
> Warning 6 [labels-omitted]: labels x, y were omitted in the application of this function.
```

This support for `labels-omitted` application was introduced when labels were added to OCaml, to ease the progressive introduction of labels in a codebase. However, it has the downside of weakening the labeling discipline: if you use labels to prevent callers from mistakenly reordering two parameters of the same type, labels-omitted make this mistake possible again.

Warning 6 warns when labels-omitted applications are used, to discourage their use. When labels were introduced, this warning was not enabled by default, so users would use labels-omitted applications, often without noticing.

Over time, it has become idiomatic to enable this warning to avoid argument-order mistakes. The warning is now on by default, since OCaml 4.13. Labels-omitted applications are not recommended anymore, but users wishing to preserve this transitory style can disable the warning explicitly.

### 13.5.2 Warning 9: missing fields in a record pattern

When pattern matching on records, it can be useful to match only few fields of a record. Eliding fields can be done either implicitly or explicitly by ending the record pattern with `; _`. However, implicit field elision is at odd with pattern matching exhaustiveness checks. Enabling warning 9 prioritizes exhaustiveness checks over the convenience of implicit field elision and will warn on implicit field elision in record patterns. In particular, this warning can help to spot exhaustive record pattern that may need to be updated after the addition of new fields to a record type.

```ocaml
type 'a point = {x : 'a; y : 'a}
let dx { x } = x (* implicit field elision: trigger warning 9 *)
let dy { y; _ } = y (* explicit field elision: do not trigger warning 9 *)
```

### 13.5.3 Warning 52: fragile constant pattern

Some constructors, such as the exception constructors `Failure` and `Invalid_argument`, take as parameter a `string` value holding a text message intended for the user.
-ppx *command*

After parsing, pipe the abstract syntax tree through the preprocessor *command*. The module *Ast_mapper*, described in section 29.1, implements the external interface of a preprocessor.

-principal

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

-rectypes

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

-safe-string

Enforce the separation between types `string` and `bytes`, thereby making strings read-only. This is the default, and enforced since OCaml 5.0.

-safer-matching

Do not use type information to optimize pattern-matching. This allows to detect match failures even if a pattern-matching was wrongly assumed to be exhaustive. This only impacts GADT and polymorphic variant compilation.

-short-paths

When a type is visible under several module-paths, use the shortest one when printing the type's name in inferred interfaces and error and warning messages. Identifier names starting with an underscore `_` or containing double underscores `__` incur a penalty of +10 when computing their length.

-stdin

Read the standard input as a script file rather than starting an interactive session.

-strict-sequence

Force the left-hand part of each sequence to have type unit.

-strict-formats

Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions.

-unsafe

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

-unsafe-string

Identify the types `string` and `bytes`, thereby making strings writable. This is intended for
These text messages are usually not stable over time: call sites building these constructors may
refine the message in a future version to make it more explicit, etc. Therefore, it is dangerous to
match over the precise value of the message. For example, until OCaml 4.02, `Array.iter2` would
raise the exception

Invalid_argument "arrays must have the same length"

Since 4.03 it raises the more helpful message

Invalid_argument "Array.iter2: arrays must have the same length"

but this means that any code of the form

try ...
with Invalid_argument "arrays must have the same length" -> ...

is now broken and may suffer from uncaught exceptions.

Warning 52 is there to prevent users from writing such fragile code in the first place. It does not occur on every matching on a literal string, but only in the case in which library authors expressed their intent to possibly change the constructor parameter value in the future, by using the attribute `ocaml.warn_on_literal_pattern` (see the manual section on builtin attributes in 12.12.1):

type t =
| Foo of string [@ocaml.warn_on_literal_pattern]
| Bar of string

let no_warning = function
| Bar "specific value" -> 0
| _ -> 1

let warning = function
| Foo "specific value" -> 0
| _ -> 1

Warning 52 [fragile-literal-pattern]: Code should not depend on the actual values of this constructor's arguments.
They are only for information and may change in future versions.
(see manual section 13.5.3)

In particular, all built-in exceptions with a string argument have this attribute set: `Invalid_argument`, `Failure`, `Sys_error` will all raise this warning if you match for a specific string argument.

Additionally, built-in exceptions with a structured argument that includes a string also have the attribute set: `Assert_failure` and `Match_failure` will raise the warning for a pattern that uses a literal string to match the first element of their tuple argument.

If your code raises this warning, you should *not* change the way you test for the specific string to avoid the warning (for example using a string equality inside the right-hand-side instead of a literal pattern), as your code would remain fragile. You should instead enlarge the scope of the pattern by matching on all possible values.
compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0.

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

-verbose

Print all external commands before they are executed. Useful to debug C library problems.

-version

Print version string and exit.

-vnum

Print short version number and exit.

-no-version

Do not print the version banner at startup.

-w warning-list

Enable, disable, or mark as fatal the warnings specified by the argument *warning-list*. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn't displayed and doesn't affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.

The *warning-list* argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:

+num

Enable warning number *num*.

-num

Disable warning number *num*.

@num

Enable and mark as fatal warning number *num*.

+num1..num2

Enable warnings in the given range.

-num1..num2

Disable warnings in the given range.

@num1..num2

Enable and mark as fatal warnings in the given range.

+letter

Enable the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

-letter

Disable the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.
```h
let warning = function
| Foo _ -> 0
| _ -> 1
```

This may require some care: if the scrutinee may return several different cases of the same pattern, or raise distinct instances of the same exception, you may need to modify your code to separate those several cases.

For example,

```h
try (int_of_string count_str, bool_of_string choice_str) with
| Failure "int_of_string" -> (0, true)
| Failure "bool_of_string" -> (-1, false)
```

should be rewritten into more atomic tests. For example, using the exception patterns documented in Section 11.6.1, one can write:

```h
match int_of_string count_str with
| exception (Failure_) -> (0, true)
| count ->
  begin match bool_of_string choice_str with
  | exception (Failure_) -> (-1, false)
  | choice -> (count, choice)
  end
```

The only case where that transformation is not possible is if a given function call may raise distinct exceptions with the same constructor but different string values. In this case, you will have to check for specific string values. This is dangerous API design and it should be discouraged: it's better to define more precise exception constructors than store useful information in strings.

### 13.5.4 Warning 57: Ambiguous or-pattern variables under guard

The semantics of or-patterns in OCaml is specified with a left-to-right bias: a value `v` matches the pattern `p | q` if it matches `p` or `q`, but if it matches both, the environment captured by the match is the environment captured by `p`, never the one captured by `q`.

While this property is generally intuitive, there is at least one specific case where a different semantics might be expected. Consider a pattern followed by a when-guard: `| p when g -> e`, for example:

```h
| ((Const x,_) | (_, Const x)) when is_neutral x -> branch
```

The semantics is clear: match the scrutinee against the pattern, if it matches, test the guard, and if the guard passes, take the branch. In particular, consider the input `(Const a, Const b)`, where `a` fails the test `is_neutral a`, while `b` passes the test `is_neutral b`. With the left-to-right semantics, the clause above is *not* taken by its input: matching `(Const a, Const b)` against the or-pattern succeeds in the left branch, it returns the environment `x -> a`, and then the guard `is_neutral a` is tested and fails, the branch is not taken.

However, another semantics may be considered more natural here: any pair that has one side passing the test will take the branch. With this semantics the previous code fragment would be equivalent to
**@letter**

Enable and mark as fatal the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

**uppercase-letter**

Enable the set of warnings corresponding to *uppercase-letter*.

**lowercase-letter**

Disable the set of warnings corresponding to *lowercase-letter*.

Alternatively, *warning-list* can specify a single warning using its mnemonic name (see below), as follows:

**+name**

Enable warning *name*.

**-name**

Disable warning *name*.

**@name**

Enable and mark as fatal warning *name*.

Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning).

**1 comment-start**

Suspicious-looking start-of-comment mark.

**2 comment-not-end**

Suspicious-looking end-of-comment mark.

**3 Deprecated synonym for the 'deprecated' alert.**

**4 fragile-match**

Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.

**5 ignored-partial-application**

Partially applied function: expression whose result has function type and is ignored.

**6 labels-omitted**

Label omitted in function application.

**7 method-override**

Method overridden.

**8 partial-match**

Partial match: missing cases in pattern-matching.

**9 missing-record-field-pattern**

Missing fields in a record pattern.

**10 non-unit-statement**

Expression on the left-hand side of a sequence that doesn't have type *unit* (and that is not a function, see warning number 5).
| (Const x,_) when is_neutral x -> branch

| (-, Const x) when is_neutral x -> branch

This is *not* the semantics adopted by OCaml.

Warning 57 is dedicated to these confusing cases where the specified left-to-right semantics is not equivalent to a non-deterministic semantics (any branch can be taken) relatively to a specific guard. More precisely, it warns when guard uses "ambiguous" variables, that are bound to different parts of the scrutinees by different sides of a or-pattern.

### 13.5.5 Warning 74: Pattern matching degraded to partial.

The OCaml type-checker performs a totality analysis to distinguish matches that are “total”, all possible input values are handled by a clause, from matches that are “partial”, some values may match none of the clause and raise a `Match_failure` exception. Total matches generate slightly better code.

There are a few rare situations where this totality analysis can be wrong: the type-checker believes the pattern-matching to be total, but certain values may try clauses in order and fail to match any of them. When the pattern-matching compiler detects that it may be in this situation, it conservatively compiles the pattern-matching as partial, and emits this warning. In some cases, this conservative assumption is necessary (the pattern-matching was partial), and in some other cases it is in fact overly conservative (a more fine-grained analysis would see that it is in fact total).

This situation happens rarely: the only known case requires matching on mutable fields. Moreover, the vast majority of programs will see no performance difference at all if it were to happen. For these reasons, the warning is disabled by default: we believe that the right approach when this situation occurs is to do nothing at all.

However, some expert users might still be interested in finding out whether some pattern-matching in their codebase may be affected by this issue, for two reasons:

1. Users may want to reason with certainty about which parts of the code may raise a `Match_failure` exception.

2. Performance-conscious expert users might want to inspect the `-dlambda` generated code if the affected pattern-matching is in a performance-critical section.

In the rest of this section we explain the only known situation where this pessimization occurs.

#### Repeated matches in mutable positions

When a pattern-matching contains patterns on mutable fields, it is possible in theory that the value of these fields may be mutated concurrently with the matching logic, and this mutation the remaining clauses failing to match, even though the pattern-matching appears to be total – it does not raise warning 8.

Consider for example:

let f : bool * bool ref -> unit = function

| (true, {contents = true}) -> ()

| (-, r) when (rcontents <- true; false) -> assert false

| (false,_) -> ()
11 redundant-case
Redundant case in a pattern matching (unused match case).

12 redundant-subpat
Redundant sub-pattern in a pattern-matching.

13 instance-variable-override
Instance variable overridden.

14 illegal-backslash
Illegal backslash escape in a string constant.

15 implicit-public-methods
Private method made public implicitly.

16 unerasable-optional-argument
Unerasable optional argument.

17 undeclared-virtual-method
Undeclared virtual method.

18 not-principal
Non-principal type.

19 non-principal-labels
Type without principality.

20 ignored-extra-argument
Unused function argument.

21 nonreturning-statement
Non-returning statement.

22 preprocessor
Preprocessor warning.

23 useless-record-with
Useless record with clause.

24 bad-module-name
Bad module name: the source file name is not a valid OCaml module name.

25 Ignored: now part of warning 8.

26 unused-var
Suspicious unused variable: unused variable that is bound with `let` or `as`, and doesn't start with an underscore (`_`) character.

27 unused-var-strict
Innocuous unused variable: unused variable that is not bound with `let` nor `as`, and doesn't start with an underscore (`_`) character.

28 wildcard-arg-to-constant-constr
Wildcard pattern given as argument to a constant constructor.

29 eol-in-string
Unescaped end-of-line in a string constant (non-portable code).
| (, {contents = false}) -> ()

let () = f (true, ref false)
(* Exception: Match_failure(...) *)

The OCaml type-checker performs its totality analysis without considering the possibility of concurrent mutations of the scrutinee, and it believes that the function *f* is total. The function *f* is partial due to side-effects on mutable fields.

Note that the following version may also be affected:

let g : bool * bool ref -> unit = function
| (true, {contents = true}) -> ()
| (false, _ ) -> ()
| (, {contents = false}) -> ()

In this example, there is no **when** guard mutating the scrutinee, but it is possible that a data race
coming from another domain would mutate the second field of the input at exactly the wrong time,
resulting in the same **Match_failure** behavior. In other words, the function *g* *might* be partial in
presence of side-effects on mutable fields.

Most patterns with mutable fields are *not* affected by this issue, because their mutable field is
read only once by the control-flow code generated by the pattern-matching compiler. For example,
the following simplification of our example does *not* suffer from this issue:

let h : bool ref -> unit = function
| ({contents = true}) -> ()
| r when (r_contents <- true; false) -> assert false
| ({contents = false}) -> ()

Whether a mutable field will be read once or several times depends on the implementation of the
pattern-matching compiler, it is not a property of the source-level pattern matching.

When the compiler detects that this situation is possible – that the pattern *is* partial or that it
*might* be partial as in the examples above – it will raise warning 74 if enabled.

Note: this warning was introduced in OCaml 5.3; earlier versions of the OCaml compiler would
not warn, and they would not ensure that a `Match_failure` case is generated in such cases: they
would generate (slightly more efficient but) incorrect code that could violate type- and memory-safety
in the case of concurrent mutation during matching.
**30 duplicate-definitions**

Two labels or constructors of the same name are defined in two mutually recursive types.

**31 module-linked-twice**

A module is linked twice in the same executable.

**I ignored: now a hard error (since 5.1).**

**32 unused-value-declaration**

Unused value declaration. (since 4.00)

**33 unused-open**

Unused open statement. (since 4.00)

**34 unused-type-declaration**

Unused type declaration. (since 4.00)

**35 unused-for-index**

Unused for-loop index. (since 4.00)

**36 unused-ancestor**

Unused ancestor variable. (since 4.00)

**37 unused-constructor**

Unused constructor. (since 4.00)

**38 unused-extension**

Unused extension constructor. (since 4.00)

**39 unused-rec-flag**

Unused rec flag. (since 4.00)

**40 name-out-of-scope**

Constructor or label name used out of scope. (since 4.01)

**41 ambiguous-name**

Ambiguous constructor or label name. (since 4.01)

**42 disambiguated-name**

Disambiguated constructor or label name (compatibility warning). (since 4.01)

**43 nonoptional-label**

Nonoptional label applied as optional. (since 4.01)

**44 open-shadow-identifier**

Open statement shadows an already defined identifier. (since 4.01)

**45 open-shadow-label-constructor**

Open statement shadows an already defined label or constructor. (since 4.01)

**46 bad-env-variable**

Error in environment variable. (since 4.01)

**47 attribute-payload**

Illegal attribute payload. (since 4.02)

**48 eliminated-optional-arguments**

Implicit elimination of optional arguments. (since 4.02)
49 no-cmi-file
Absent cmi file when looking up module alias. (since 4.02)

50 unexpected-docstring
Unexpected documentation comment. (since 4.03)

51 wrong-tailcall-expectation
Function call annotated with an incorrect @tailcall attribute. (since 4.03)

52 fragile-literal-pattern (see 13.5.3)
Fragile constant pattern. (since 4.03)

53 misplaced-attribute
Attribute cannot appear in this context. (since 4.03)

54 duplicated-attribute
Attribute used more than once on an expression. (since 4.03)

55 inlining-impossible
Inlining impossible. (since 4.03)

56 unreachable-case
Unreachable case in a pattern-matching (based on type information). (since 4.03)

57 ambiguous-var-in-pattern-guard (see 13.5.4)
Ambiguous or-pattern variables under guard. (since 4.03)

58 no-cmx-file
Missing cmx file. (since 4.03)

59 lambda-assignment-to-non-mutable-value
Assignment to non-mutable value. (since 4.03)

60 unused-module
Unused module declaration. (since 4.04)

61 unboxable-type-in-prim-decl
Unboxable type in primitive declaration. (since 4.04)

62 constraint-on-gadt
Type constraint on GADT type declaration. (since 4.06)

63 erroneous-printed-signature
Erroneous printed signature. (since 4.08)

64 unsafe-array-syntax-without-parsing
-unsafe used with a preprocessor returning a syntax tree. (since 4.08)

65 redefining-unit
Type declaration defining a new '()' constructor. (since 4.08)

66 unused-open-bang
Unused open! statement. (since 4.08)

67 unused-functor-parameter
Unused functor parameter. (since 4.10)

68 match-on-mutable-state-prevent-uncurry
Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12)
# Chapter 14

## The toplevel system or REPL (ocaml)

This chapter describes `ocaml`, the toplevel system for OCaml, that permits interactive use of the OCaml system through a read-eval-print loop (REPL). 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. End-of-file on standard input terminates `ocaml`.

Input to the toplevel can span several lines. It begins after the `#` (sharp) prompt printed by the system and is terminated by `;;` (a double-semicolon) followed by optional white space and comments and an end of line. The toplevel input consists in one or several toplevel phrases, with the following syntax:

```
toplevel-input ::= {definition} ;;
                  | expr ;;
                  | # ident [directive-argument] ;;

directive-argument ::= string-literal
                      | integer-literal
                      | value-path
                      | true | false
```

A phrase can consist of a sequence of definitions, like those found in implementations of compilation units or in `struct...end` module expressions. The definitions can bind value names, type names, exceptions, module names, or module type names. 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 value expression (section 11.7). It is simply evaluated without performing any bindings, and its value 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 14.2.

### Unix:

The toplevel system is started by the command `ocaml`, as follows:

```
ocaml options objects                      # interactive mode
ocaml options objects scriptfile           # script mode
```
**69** `unused-field`

Unused record field. (since 4.13)

**70** `missing-mli`

Missing interface file. (since 4.13)

**71** `unused-tmc-attribute`

Unused `@tail_mod_cons` attribute. (since 4.14)

**72** `tmc-breaks-tailcall`

A tail call is turned into a non-tail call by the `@tail_mod_cons` transformation. (since 4.14)

**73** `generative-application-expects-unit`

A generative functor is applied to an empty structure (struct end) rather than to `()`. (since 5.1)

**A** all warnings

**C** warnings 1, 2.

**D** Alias for warning 3.

**E** Alias for warning 4.

**F** Alias for warning 5.

**K** warnings 32, 33, 34, 35, 36, 37, 38, 39.

**L** Alias for warning 6.

**M** Alias for warning 7.

**P** Alias for warning 8.

**R** Alias for warning 9.

**S** Alias for warning 10.

**U** warnings 11, 12.

**V** Alias for warning 13.

**X** warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.

**Y** Alias for warning 26.

**Z** Alias for warning 27.

The default setting is `-w +a-4-6-7-9-27-29-32..42-44-45-48-50-60`. It is displayed by `-help`. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.

**-warn-error** *warning-list*

Mark as fatal the warnings specified in the argument *warning-list*. The compiler will stop with an error when one of these warnings is emitted. The *warning-list* has the same meaning as for the `-w` option: a `+` sign (or an uppercase letter) marks the corresponding warnings as fatal, a `-` sign (or a lowercase letter) turns them back into non-fatal warnings, and a `@` sign both enables and marks as fatal the corresponding warnings.
options are described below. objects are filenames ending in .cmo or .cma; they are loaded into the interpreter immediately after options are set. scriptfile is any file name not ending in .cmo or .cma.

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

On start-up (before the first phrase is read), the contents of initialization file are read as a sequence of OCaml phrases and executed as per the #use directive described in section 14.2. The evaluation outcode for each phrase are not displayed.

The initialization file is the first found of:

1. .ocamlinit in the current directory;

2. XDG_CONFIG_HOME/ocaml/init.ml, if XDG_CONFIG_HOME is an absolute path;

3. otherwise, on Unix, HOME/ocaml/init.ml or, on Windows, ocaml\init.ml under LocalAppData (e.g. C:\Users\Bactrian\AppData\Local\ocaml\init.ml);

4. ocaml/init.ml under any of the absolute paths in XDG_CONFIG_DIRS. Paths in XDG_CONFIG_DIRS are colon-delimited on Unix, and semicolon-delimited on Windows;

5. if XDG_CONFIG_DIRS contained no absolute paths, /usr/xdg/ocaml/init.ml on Unix or, ocaml\init.ml under any of LocalAppData (e.g. C:\Users\Bactrian\AppData\Local), RoamingAppData (e.g. C:\Users\Bactrian\AppData\Roaming), or ProgramData (e.g. C:\ProgramData) on Windows;

6. HOME/.ocamlinit, if HOME is non-empty;

The toplevel system does not perform line editing, but it can easily be used in conjunction with an external line editor such as `ledit`, or `rlwrap`. An improved toplevel, `utop`, is also available. 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 14.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
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` (no warning is fatal).

**-warn-help**

Show the description of all available warning numbers.

**-file**

Use *file* as a script file name, even when it starts with a hyphen (-).

**-help or --help**

Display a short usage summary and exit.

**Unix:**

The following environment variables are also consulted:

**OCAMLTOP_INCLUDE_PATH**

Additional directories to search for compiled object code files (`.cmi`, `.cmo` and `.cma`). The specified directories are considered from left to right, after the include directories specified on the command line via `-I` have been searched. Available since OCaml 4.08.

**OCAMLTOP_UTF_8**

When printing string values, non-ascii bytes (```> \0x7E``` ) are printed as decimal escape sequence if `OCAMLTOP_UTF_8` is set to false. Otherwise, they are printed unescaped.

**TERM**

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

**XDG_CONFIG_HOME, HOME**

.ocamlinit lookup procedure (see above).

## 14.2 TLEVEL DIRECTIVES

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.

**General**

**-help;;**

Prints a list of all available directives, with corresponding argument type if appropriate.

**-quit;;**

Exit the toplevel loop and terminate the `ocaml` command.
## 14.1 Options

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

**-absname**

Force error messages to show absolute paths for file names.

**-no-absname**

Do not try to show absolute filenames in error messages.

**-args filename**

Read additional newline-terminated command line arguments from *filename*. It is not possible to pass a *scriptfile* via file to the toplevel.

**-args0 filename**

Read additional null character terminated command line arguments from *filename*. It is not possible to pass a *scriptfile* via file to the toplevel.

**-I directory**

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

If the given directory starts with `+`, it is taken relative to the standard library directory. For instance, `-I +unix` adds the subdirectory `unix` 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 14.2).

**-init file**

Load the given file instead of the default initialization file. The default initialization file is the first found of:

1. `.ocamlinit` in the current directory;

2. `XDG_CONFIG_HOME/ocaml/init.ml`, if `XDG_CONFIG_HOME` is an absolute path;

3. otherwise, on Unix, `HOME/ocaml/init.ml` or, on Windows, `ocaml\init.ml` under `LocalAppData` (e.g. `C:\Users\Bactrian\AppData\Local\ocaml\init.ml`);

4. `ocaml/init.ml` under any of the absolute paths in `XDG_CONFIG_DIRS`. Paths in `XDG_CONFIG_DIRS` are colon-delimited on Unix, and semicolon-delimited on Windows;

5. if `XDG_CONFIG_DIRS` contained no absolute paths, `/usr/xdg/ocaml/init.ml` on Unix or, `ocaml\init.ml` under any of `LocalAppData` (e.g. `C:\Users\Bactrian\AppData\Local`), `RoamingAppData` (e.g. `C:\Users\Bactrian\AppData\Roaming`), or `ProgramData` (e.g. `C:\ProgramData`) on Windows;

6. `HOME/.ocamlinit`, if `HOME` is non-empty;
Loading codes

#cd "dir-name";;

Change the current working directory.

#directory "dir-name";;

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

#remove_directory "dir-name";;

Remove the given directory from the list of directories searched for source and compiled files. Do nothing if the list does not contain the given directory.

#load "file-name";;

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

#load_rec "file-name";;

Load in memory a bytecode object file (`.cmo` file) or library file (`.cma` file) produced by the batch compiler `ocamlc`. When loading an object file that depends on other modules which have not been loaded yet, the `.cmo` files for these modules are searched and loaded as well, recursively. The loading order is not specified.

#use "file-name";;

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

#use_output "command";;

Execute a command and evaluate its output as if it had been captured to a file and passed to `#use`.

#mod_use "file-name";;

Similar to `#use` but also wrap the code into a top-level module of the same name as capitalized file name without extensions, following semantics of the compiler.

For directives that take file names as arguments, if the given file name specifies no directory, the file is searched in the following directories:

1. In script mode, the directory containing the script currently executing; in interactive mode, the current working directory.

2. Directories added with the `#directory` directive.

3. Directories given on the command line with `-I` options.

4. The standard library directory.

Environment queries

#show_class class-path;;

#show_class_type class-path;;

#show_exception ident;;

#show_module module-path;;

#show_module_type modtype-path;;
**-keywords version+list**

Set keywords according to the *version+list* specification.

This specification starts with an optional version number, defining the base set of keywords, followed by a `+-` separated list of additional keywords to add to this base set.

Without an explicit version number, the base set of keywords is the set of keywords in the current version of OCaml. Additional keywords that do not match any known keyword in the current version of the language trigger an error whenever they are present in the source code.

**-labels**

Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default.

**-no-app-funct**

Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures.

**-noassert**

Do not compile assertion checks. Note that the special form `assert false` is always compiled because it is typed specially.

**-nolabels**

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

**-noprompt**

Do not display any prompt when waiting for input.

**-nopromptcont**

Do not display the secondary prompt when waiting for continuation lines in multi-line inputs. This should be used e.g. when running `ocaml` in an `emacs` window.

**-nostdlib**

Do not include the standard library directory in the list of directories searched for source and compiled files.

**-ppx command**

After parsing, pipe the abstract syntax tree through the preprocessor *command*. The module *Ast_mapper*, described in section 30.1, implements the external interface of a preprocessor.

**-principal**

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

```
#show_val value-path;;
```

Print the signature of the corresponding component.

```
#show ident;;
```

Print the signatures of components with name *ident* in all the above categories.

## Pretty-printing

```
#install_printers printer-name;;
```

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

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

```
#print_depth n;;
```

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

```
#print_length n;;
```

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

```
#remove_printers printer-name;;
```

Remove the named function from the table of toplevel printers.

## Tracing

```
#trace function-name;;
```

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

```
#untrace function-name;;
```

Stop tracing the given function.

```
#untrace_all;;
```

Stop tracing all functions traced so far.

## Compiler options

```
#debug bool;;
```

Turn on/off the insertion of debugging events. Default is true.
-rectypes

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

-safe-string

Enforce the separation between types *string* and *bytes*, thereby making strings read-only. This is the default, and enforced since OCaml 5.0.

-safer-matching

Do not use type information to optimize pattern-matching. This allows to detect match failures even if a pattern-matching was wrongly assumed to be exhaustive. This only impacts GADT and polymorphic variant compilation.

-short-paths

When a type is visible under several module-paths, use the shortest one when printing the type's name in inferred interfaces and error and warning messages. Identifier names starting with an underscore _ or containing double underscores __ incur a penalty of +10 when computing their length.

-stdin

Read the standard input as a script file rather than starting an interactive session.

-strict-sequence

Force the left-hand part of each sequence to have type unit.

-strict-formats

Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions.

-unsafe

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

-unsafe-string

Identify the types *string* and *bytes*, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0.

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

-verbose

Print all external commands before they are executed, Useful to debug C library problems.

-version

Print version string and exit.
### #labels bool;;

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

### #ppx "file-name";

After parsing, pipe the abstract syntax tree through the preprocessor command.

### #principal bool;;

If the argument is `true`, check information paths during type-checking, to make sure that all types are derived in a principal way. If the argument is `false`, do not check information paths.

### #rectypes;;

Allow arbitrary recursive types during type-checking. Note: once enabled, this option cannot be disabled because that would lead to unsoundness of the type system.

### #warn_error "warning-list";

Treat as errors the warnings enabled by the argument and as normal warnings the warnings disabled by the argument.

### #warnings "warning-list";

Enable or disable warnings according to the argument.

## 14.3 The toplevel and the module system

TLEVELPHASES

Tplevel 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 11.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 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`.

## 14.4 Common errors

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

### Cannot find file filename

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

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

Print short version number and exit.

-no-version

Do not print the version banner at startup.

-w warning-list

Enable, disable, or mark as fatal the warnings specified by the argument *warning-list*. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn't displayed and doesn't affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.

The *warning-list* argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:

+num

Enable warning number *num*.

-num

Disable warning number *num*.

@num

Enable and mark as fatal warning number *num*.

+num1..num2

Enable warnings in the given range.

-num1..num2

Disable warnings in the given range.

@num1..num2

Enable and mark as fatal warnings in the given range.

+letter

Enable the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

-letter

Disable the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

@letter

Enable and mark as fatal the set of warnings corresponding to *letter*. The letter may be uppercase or lowercase.

uppercase-letter

Enable the set of warnings corresponding to *uppercase-letter*.

lowercase-letter

Disable the set of warnings corresponding to *lowercase-letter*.

Alternatively, *warning-list* can specify a single warning using its mnemonic name (see below), as follows:
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.

**This expression has type $t_1$, but is used with type $t_2$**

See section 13.4.

**Reference to undefined global mod**

You have neglected to load in memory an implementation for a module with `#load`. See section 14.3 above.

## 14.5 Building custom toplevel systems: ocamlmktop

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.

### 14.5.1 Options

The following command-line options are recognized by `ocamlmktop`.

**-cclib libname**

Pass the `-llibname` option to the C linker when linking in "custom runtime" mode. See the corresponding option for `ocamlc`, in chapter 13.
**+name**

Enable warning *name*.

**-name**

Disable warning *name*.

**@name**

Enable and mark as fatal warning *name*.

Warning numbers, letters and names which are not currently defined are ignored. The warnings
are as follows (the name following each number specifies the mnemonic for that warning).

1 **comment-start**

Suspicious-looking start-of-comment mark.

2 **comment-not-end**

Suspicious-looking end-of-comment mark.

3 **Deprecated synonym for the 'deprecated' alert.**

4 **fragile-match**

Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.

5 **ignored-partial-application**

Partially applied function: expression whose result has function type and is ignored.

6 **labels-omitted**

Label omitted in function application.

7 **method-override**

Method overridden.

8 **partial-match**

Partial match: missing cases in pattern-matching.

9 **missing-record-field-pattern**

Missing fields in a record pattern.

10 **non-unit-statement**

Expression on the left-hand side of a sequence that doesn't have type *unit* (and that is not a function, see warning number 5).

11 **redundant-case**

Redundant case in a pattern matching (unused match case).

12 **redundant-subpat**

Redundant sub-pattern in a pattern-matching.

13 **instance-variable-override**

Instance variable overridden.

14 **illegal-backslash**

Illegal backslash escape in a string constant.

15 **implicit-public-methods**

Private method made public implicitly.
-ccopt *option*

Pass the given option to the C compiler and linker, when linking in "custom runtime" mode.
See the corresponding option for ocamlc, in chapter 13.

-custom

Link in "custom runtime" mode. See the corresponding option for ocamlc, in chapter 13.

-I *directory*

Add the given directory to the list of directories searched for compiled object code files (`.cmo` and `.cma`).

-o *exec-file*

Specify the name of the toplevel file produced by the linker. The default is `a.out`.

## 14.6 The native toplevel: ocamlnat (experimental)

This section describes a tool that is not yet officially supported but may be found
useful.

OCaml code executing in the traditional toplevel system uses the bytecode interpreter. When
increased performance is required, or for testing programs that will only execute correctly when
compiled to native code, the *native toplevel* may be used instead.

For the majority of installations the native toplevel will not have been installed along with
the rest of the OCaml toolchain. In such circumstances it will be necessary to build the OCaml
distribution from source. From the built source tree of the distribution you may use *make natruntop*
to build and execute a native toplevel. (Alternatively *make ocamlnat* can be used, which just
performs the build step.)

If the *make install* command is run after having built the native toplevel then the *ocamlnat*
program (either from the source or the installation directory) may be invoked directly rather than
using *make natruntop*.
**16 unerasable-optional-argument**
Unerasable optional argument.

**17 undeclared-virtual-method**
Undeclared virtual method.

**18 not-principal**
Non-principal type.

**19 non-principal-labels**
Type without principality.

**20 ignored-extra-argument**
Unused function argument.

**21 nonreturning-statement**
Non-returning statement.

**22 preprocessor**
Preprocessor warning.

**23 useless-record-with**
Useless record with clause.

**24 bad-module-name**
Bad module name: the source file name is not a valid OCaml module name.

**25 Ignored:** now part of warning 8.

**26 unused-var**
Suspicious unused variable: unused variable that is bound with `let` or `as`, and doesn't start with an underscore (`_`) character.

**27 unused-var-strict**
Innocuous unused variable: unused variable that is not bound with `let` nor `as`, and doesn't start with an underscore (`_`) character.

**28 wildcard-arg-to-constant-constr**
Wildcard pattern given as argument to a constant constructor.

**29 eol-in-string**
Unescaped end-of-line in a string constant (non-portable code).

**30 duplicate-definitions**
Two labels or constructors of the same name are defined in two mutually recursive types.

**31 module-linked-twice**
A module is linked twice in the same executable.

**I ignored:** now a hard error (since 5.1).

**32 unused-value-declaration**
Unused value declaration. (since 4.00)

**33 unused-open**
Unused open statement. (since 4.00)

**34 unused-type-declaration**
Unused type declaration. (since 4.00)
Chapter 15

The runtime system (ocamlrun)

The ocamlrun command executes bytecode files produced by the linking phase of the ocamlc command.

15.1 Overview

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 arg₁ ... argₙ

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 arg₁ to argₙ.

As mentioned in chapter 13, 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 *arg*₁ ... *arg*ₙ

works exactly as

ocamlrun a.out *arg*₁ ... *arg*ₙ

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 ....
**35 unused-for-index**
Unused for-loop index. (since 4.00)

**36 unused-ancestor**
Unused ancestor variable. (since 4.00)

**37 unused-constructor**
Unused constructor. (since 4.00)

**38 unused-extension**
Unused extension constructor. (since 4.00)

**39 unused-rec-flag**
Unused rec flag. (since 4.00)

**40 name-out-of-scope**
Constructor or label name used out of scope. (since 4.01)

**41 ambiguous-name**
Ambiguous constructor or label name. (since 4.01)

**42 disambiguated-name**
Disambiguated constructor or label name (compatibility warning). (since 4.01)

**43 nonoptional-label**
Nonoptional label applied as optional. (since 4.01)

**44 open-shadow-identifier**
Open statement shadows an already defined identifier. (since 4.01)

**45 open-shadow-label-constructor**
Open statement shadows an already defined label or constructor. (since 4.01)

**46 bad-env-variable**
Error in environment variable. (since 4.01)

**47 attribute-payload**
Illegal attribute payload. (since 4.02)

**48 eliminated-optional-arguments**
Implicit elimination of optional arguments. (since 4.02)

**49 no-cmi-file**
Absent cmi file when looking up module alias. (since 4.02)

**50 unexpected-docstring**
Unexpected documentation comment. (since 4.03)

**51 wrong-tailcall-expectation**
Function call annotated with an incorrect @tailcall attribute. (since 4.03)

**52 fragile-literal-pattern (see 13.5.3)**
Fragile constant pattern. (since 4.03)

**53 misplaced-attribute**
Attribute cannot appear in this context. (since 4.03)

**54 duplicated-attribute**
Attribute used more than once on an expression. (since 4.03)
## 15.2 Options

The following command-line options are recognized by `ocamlrun`.

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

**-config**

Print the version number of `ocamlrun` and a detailed summary of its configuration, then exit.

**-I dir**

Search the directory `dir` for dynamically-loaded libraries, in addition to the standard search path (see section 15.3).

- **-m** Print the magic number of the bytecode executable given as argument and exit.

- **-M** Print the magic number expected for bytecode executables by this version of the runtime and exit.

- **-p** Print the names of the primitives known to this version of `ocamlrun` and exit.

- **-t** Increments the trace level for the debug runtime (ignored otherwise).

- **-v** Direct the memory manager to print some progress messages on standard error. This is equivalent to setting `v=61` in the `OCAMLRUNPARAM` environment variable (see below).

**-version**

Print version string and exit.

**-vnum**

Print short version number and exit.

The following environment variables are also consulted:

**CAML_LD_LIBRARY_PATH**

Additional directories to search for dynamically-loaded libraries (see section 15.3).

**OCAMLLIB**

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

**OCAMLRUNPARAM**

Set the runtime system options and garbage collection parameters. (If `OCAMLRUNPARAM` is not set, `CAMLRUNPARAM` will be used instead.) This variable must be a sequence of parameter specifications separated by commas. For convenience, commas at the beginning of the variable are ignored, and multiple runs of commas are interpreted as a single one. A parameter
**55 inlining-impossible**
Inlining impossible. (since 4.03)

**56 unreachable-case**
Unreachable case in a pattern-matching (based on type information). (since 4.03)

**57 ambiguous-var-in-pattern-guard (see 13.5.4)**
Ambiguous or-pattern variables under guard. (since 4.03)

**58 no-cmx-file**
Missing cmx file. (since 4.03)

**59 flambda-assignment-to-non-mutable-value**
Assignment to non-mutable value. (since 4.03)

**60 unused-module**
Unused module declaration. (since 4.04)

**61 unboxable-type-in-prim-decl**
Unboxable type in primitive declaration. (since 4.04)

**62 constraint-on-gadt**
Type constraint on GADT type declaration. (since 4.06)

**63 erroneous-printed-signature**
Erroneous printed signature. (since 4.08)

**64 unsafe-array-syntax-without-parsing**
-unsafe used with a preprocessor returning a syntax tree. (since 4.08)

**65 redefining-unit**
Type declaration defining a new '()' constructor. (since 4.08)

**66 unused-open-bang**
Unused open! statement. (since 4.08)

**67 unused-functor-parameter**
Unused functor parameter. (since 4.10)

**68 match-on-mutable-state-prevent-uncurry**
Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12)

**69 unused-field**
Unused record field. (since 4.13)

**70 missing-mli**
Missing interface file. (since 4.13)

**71 unused-tmc-attribute**
Unused @tail\_mod\_cons attribute. (since 4.14)

**72 tmc-breaks-tailcall**
A tail call is turned into a non-tail call by the @tail\_mod\_cons transformation. (since 4.14)

**73 generative-application-expects-unit**
A generative functor is applied to an empty structure (struct end) rather than to (). (since 5.1)
specification is an option letter followed by an `=` sign, a decimal number (or an hexadecimal number prefixed by `0x`), and an optional multiplier. The options are documented below; the options `a`, `i`, `l`, `m`, `M`, `n`, `o`, `O`, `s`, `v`, `w` correspond to the fields of the `control` record documented in section 28.23.

**b** (backtrace) Trigger the printing of a stack backtrace when an uncaught exception aborts the program. An optional argument can be provided: `b=0` turns backtrace printing off; `b=1` is equivalent to `b` and turns backtrace printing on; `b=2` turns backtrace printing on and forces the runtime system to load debugging information at program startup time instead of at backtrace printing time. `b=2` can be used if the runtime is unable to load debugging information at backtrace printing time, for example if there are no file descriptors available.

**c** (`cleanup_on_exit`) Shut the runtime down gracefully on exit (see `caml_shutdown` in section 22.7.5). The option also enables pooling (as in `caml_startup_pooled`). This mode can be used to detect leaks with a third-party memory debugger.

**e** (`runtime_events_log_wsize`) Size of the per-domain runtime events ring buffers in log powers of two words. Defaults to 16, giving 64k word or 512kb buffers on 64-bit systems.

**l** (`stack_limit`) The limit (in words) of the stack size. This is only relevant to the byte-code runtime, as the native code runtime uses the operating system's stack.

**m** (`custom_minor_ratio`) Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Default: 100. Note: this only applies to values allocated with `caml_alloc_custom_mem`.

**M** (`custom_major_ratio`) Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values (e.g. bigarrays) located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. Default: 44. Note: this only applies to values allocated with `caml_alloc_custom_mem`.

**n** (`custom_minor_max_size`) Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. When a custom value is allocated on the minor heap and holds more than this many bytes, only this value is counted against `custom_minor_ratio` and the rest is directly counted against `custom_major_ratio`. Default: 8192 bytes. Note: this only applies to values allocated with `caml_alloc_custom_mem`.

The multiplier is `k`, `M`, or `G`, for multiplication by $2^{10}$, $2^{20}$, and $2^{30}$ respectively.

**o** (`space_overhead`) The major GC speed setting. See the Gc module documentation for details.

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

**R** (`randomize`) Turn on randomization of all hash tables by default (see section 28.24). This option takes no argument.

**s** (`minor_heap_size`) Size of the minor heap. (in words)
**74 degraded-to-partial-match**

A pattern-matching is compiled as partial even if it appears to be total. (since 5.3)

**75 unnecessarily-partial-tuple-pattern**

A tuple pattern ends in `..` but fully matches its expected type. (since 5.4)

**A** all warnings

**C** warnings 1, 2.

**D** Alias for warning 3.

**E** Alias for warning 4.

**F** Alias for warning 5.

**K** warnings 32, 33, 34, 35, 36, 37, 38, 39.

**L** Alias for warning 6.

**M** Alias for warning 7.

**P** Alias for warning 8.

**R** Alias for warning 9.

**S** Alias for warning 10.

**U** warnings 11, 12.

**V** Alias for warning 13.

**X** warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30.

**Y** Alias for warning 26.

**Z** Alias for warning 27.

The default setting is `-w +a-4-6-7-9-27-29-32..42-44-45-48-50-60`. It is displayed by `-help`. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker.

**-warn-error warning-list**

Mark as fatal the warnings specified in the argument `warning-list`. The compiler will stop with an error when one of these warnings is emitted. The `warning-list` has the same meaning as for the `-w` option: a `+` sign (or an uppercase letter) marks the corresponding warnings as fatal, a `-` sign (or a lowercase letter) turns them back into non-fatal warnings, and a `@` sign both enables and marks as fatal the corresponding warnings.

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` (no warning is fatal).

**-warn-help**

Show the description of all available warning numbers.

**- file**

Use `file` as a script file name, even when it starts with a hyphen (`-`).
**t** Set the trace level for the debug runtime (ignored by the standard runtime).

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

1 (= 0x001)
Start and end of major GC cycle.

2 (= 0x002)
Minor collection and major GC slice.

4 (= 0x004)
Growing and shrinking of the heap.

8 (= 0x008)
Resizing of stacks and memory manager tables.

16 (= 0x010)
Heap compaction.

32 (= 0x020)
Change of GC parameters.

64 (= 0x040)
Computation of major GC slice size.

128 (= 0x080)
Calling of finalization functions

256 (= 0x100)
Startup messages (loading the bytecode executable file, resolving shared libraries).

512 (= 0x200)
Computation of compaction-triggering condition.

1024 (= 0x400)
Output GC statistics at program exit.

2048 (= 0x800)
GC debugging messages.

4096 (= 0x1000)
Address space reservation changes.

**V** (**verify_heap**) runs an integrity check on the heap just after the completion of a major GC cycle

**W** Print runtime warnings to stderr (such as Channel opened on file dies without being closed, unflushed data, etc.)

If the option letter is not recognized, the whole parameter is ignored; if the equal sign or the number is missing, the value is taken as 1; if the multiplier is not recognized, it is ignored.

For example, on a 32-bit machine, under **bash** the command

`export OCAMLRUNPARAM='b,s=256k,v=0x015'`
**-help or --help**

Display a short usage summary and exit.

**Unix:**

The following environment variables are also consulted:

**OCAMLTOP_INCLUDE_PATH**

Additional directories to search for compiled object code files (`.cmi`, `.cmo` and `.cma`). The specified directories are considered from left to right, after the include directories specified on the command line via `-I` have been searched. Available since OCaml 4.08.

**OCAMLTOP_UTF_8**

When printing string values, non-ascii bytes ( > \0x7E) are printed as decimal escape sequence if `OCAMLTOP_UTF_8` is set to false. Otherwise, they are printed unescaped.

**TERM**

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

**XDG_CONFIG_HOME, HOME, XDG_CONFIG_DIRS**

Initialization file lookup procedure (see above).

## 14.2 T LEVEL directives

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.

### General

**#help;;**

Prints a list of all available directives, with corresponding argument type if appropriate.

**#quit;;**

Exit the toplevel loop and terminate the `ocaml` command.

### Loading codes

**#cd "dir-name";;**

Change the current working directory.

**#directory "dir-name";;**

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

**#remove_directory "dir-name";;**

Remove the given directory from the list of directories searched for source and compiled files. Do nothing if the list does not contain the given directory.
tells a subsequent *ocamlrun* to print backtraces for uncaught exceptions, set its initial minor
heap size to 1 megabyte and print a message at the start of each major GC cycle, when the
heap size changes, and when compaction is triggered.

CAMLRUNPARAM

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

PATH

List of directories searched to find the bytecode executable file.

15.3 Dynamic loading of shared libraries

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 22.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:

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

2. Directories specified in the CAML_LD_LIBRARY_PATH environment variable.

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

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

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

15.4 Common errors

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

filename: no such file or directory

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

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

```
#load_rec "file-name";;
```

Load in memory a bytecode object file (`.cmo` file) or library file (`.cma` file) produced by the batch compiler `ocamlc`. When loading an object file that depends on other modules which have not been loaded yet, the `.cmo` files for these modules are searched and loaded as well, recursively. The loading order is not specified.

```
#use "file-name";;
```

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

```
#use_output "command";;
```

Execute a command and evaluate its output as if it had been captured to a file and passed to `#use`.

```
#mod_use "file-name";;
```

Similar to `#use` but also wrap the code into a top-level module of the same name as capitalized file name without extensions, following semantics of the compiler.

For directives that take file names as arguments, if the given file name specifies no directory, the file is searched in the following directories:

1. In script mode, the directory containing the script currently executing; in interactive mode, the current working directory.

2. Directories added with the `#directory` directive.

3. Directories given on the command line with `-I` options.

4. The standard library directory.

## Environment queries

```
#show_class class-path;;
```

```
#show_class_type class-path;;
```

```
#show_exception ident;;
```

```
#show_module module-path;;
```

```
#show_module_type modtype-path;;
```

```
#show_type typeconstr;;
```

```
#show_val value-path;;
```

Print the signature of the corresponding component.

```
#show ident;;
```

Print the signatures of components with name `ident` in all the above categories.

## Pretty-printing