**Cannot exec ocamrun**

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

**Cannot find the bytecode file**

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

**Truncated bytecode file**

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

**Uncaught exception**

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

**Out of memory**

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

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

## `#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
Chapter 16

Native-code compilation (ocamlopt)

This chapter describes the OCaml high-performance native-code compiler ocamlopt, which compiles
OCaml source files to native code object files and links these object files to produce standalone
executables.

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

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

16.1 Overview of the compiler

The ocamlopt command has a command-line interface very close to that of ocamlc. It accepts the
same types of arguments, and processes them sequentially, 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 `ocamlopt` compiler produces a compiled interface in the file `x.cmi`. The interface produced is identical to that produced by the bytecode compiler `ocamlc`.

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

The implementation is checked against the interface file `x.mli` (if it exists) as described in the
manual for `ocamlc` (chapter 13).
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

T LEVELPHRASES 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`.

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

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

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

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

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

The compiler is able to emit some information on its internal stages:

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

* `.cmir-linear` files for the implementation of the compilation unit if the option `-save-ir-after scheduling` is passed to it. Each such file contains a low-level intermediate representation, produced by the instruction scheduling pass.

An external tool can perform low-level optimisations, such as code layout, by transforming a `.cmir-linear` file. To continue compilation, the compiler can be invoked with (a possibly modified) `.cmir-linear` file as an argument, instead of the corresponding source file.

## 16.2 Options

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

* `-a` Build a library (`.cmxa` and `.a/..lib` files) with the object files (`.cmx` and `.o/..obj` 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.
**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.

**-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`.
If `-cclib` or `-ccopt` options are passed on the command line, these options are stored in the resulting `.cmxalibrary`. Then, linking with this library automatically adds back the `-cclib` and `-ccopt` options as if they had been provided on the command line, unless the `-noautolink` option is given.

**-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 called to build the final executable 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 linker. This causes the given C library to be linked with the program.

**-ccopt option**

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

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

**-compact**

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

**-config**

Print the version number of `ocamlopt` 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 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.

**-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.
-for-pack *module-path*

Generate an object file (`.cmx` and `.o`/.`obj` files) that can later be included as a sub-module (with the given access path) of a compilation unit constructed with `-pack`. For instance, `ocamlopt -for-pack P -c A.ml` will generate `a..cmx` and `a.o` files that can later be used with `ocamlopt -pack -o P.cmx a.cmx`. 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 produce stack backtraces when the program terminates on an uncaught exception (see section 15.2).

-no-g

Do not record debugging information (default).

-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 (`.cmx`), and libraries (`.cmxa`). By default, the current directory is searched first, then the standard library directory. Directories added with `-I` are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. 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`.

-inline *n*

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

-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`).
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 ....
-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.

-linscan

Use linear scan register allocation. Compiling with this allocator is faster than with the usual
graph coloring allocator, sometimes quite drastically so for long functions and modules. On
the other hand, the generated code can be a bit slower.

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

-no-float-const-prop

Deactivates the constant propagation for floating-point operations. This option should be
given if the program changes the float rounding mode during its execution.

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

-nodynlink

Allow the compiler to use some optimizations that are valid only for code that is statically linked
to produce a non-relocatable executable. The generated code cannot be linked to produce a
shared library nor a position-independent executable (PIE). Many operating systems produce
## 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
PIEs by default, causing errors when linking code compiled with `-nodynlink`. Either do not use `-nodynlink` or pass the option `-ccopt -no-pie` at link-time.

**-nolabels**

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

**-nostdlib**

Do not automatically add the standard library directory to the list of directories searched for compiled interface files (`.cmi`), compiled object code files (`.cmx`), and libraries (`.cmxa`). 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 `-shared` option is given, specify the name of plugin file produced.

**-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 an executable file. This is useful to wrap
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 `l`, `m`, `M`, `n`, `o`, `s`, `v` correspond to fields of the `control` record documented in section 29.25.

**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.6). The option also enables pooling (as in `caml_startup_pooled`). This mode can be used to detect leaks with a third-party memory debugger.

**d** (`max_domain`) Maximum number of domains that can be active concurrently. Defaults to 128 on 64-bit platforms and 16 on 32-bit platforms.

**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 relevant to both the byte-code runtime and the native code runtime: OCaml always uses its own stack and not 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.
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 compiled shared/dynamic library (`.so` extension, `.dll` under Windows).

**-output-complete-obj**

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

**-pack**

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

```
ocamlopt -pack -o P.cmx A.cmx B.cmx C.cmx
```

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

The `.cmx` object files being combined must have been compiled with the appropriate `-for-pack` option. In the example above, `A.cmx`, `B.cmx` and `C.cmx` must have been compiled with `ocamlopt -for-pack P`.

Multiple levels of packing can be achieved by combining `-pack` with `-for-pack`. Consider the following example:

```
ocamlopt -for-pack P.Q -c A.ml ocamlopt -pack -o Q.cmx -for-pack P A.cmx
ocamlopt -for-pack P -c B.ml ocamlopt -pack -o P.cmx Q.cmx B.cmx
```

The resulting `P.cmx` object file has sub-modules `P.Q`, `P.Q.A` and `P.B`.

**-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 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.
**R** (randomize) Turn on randomization of all hash tables by default (see section 29.26). This option takes no argument.

**s** (`minor_heap_size`) Size of the minor heap. (in words)

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

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

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

-save-ir-after pass

Save intermediate representation after the given compilation pass to a file. The currently supported passes and the corresponding file extensions are: `scheduling` (`.cmir-linear`).

This experimental feature enables external tools to inspect and manipulate compiler's intermediate representation of the program using `compiler-libs` library (see section 29).

-shared

Build a plugin (usually `.cmxs`) that can be dynamically loaded with the `Dynlink` module. The name of the plugin must be set with the `-o` option. A plugin can include a number of OCaml modules and libraries, and extra native objects (`.o`, `.obj`, `.a`, `.lib` files). Building native plugins is only supported for some operating system. Under some systems (currently, only Linux AMD 64), all the OCaml code linked in a plugin must have been compiled without the `-nodynlink` flag. Some constraints might also apply to the way the extra native objects have been compiled (under Linux AMD 64, they must contain only position-independent code).

-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`, `scheduling`, `emit`.
```
export OCAMLRUNPARAM='b,s=256k,v=0x015'
```

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

### CAMLRUNPARAM

If `OCAMLRUNPARAM` is not found in the environment, then `CAMLRUNPARAM` will be used instead. If `CAMLRUNPARAM` is 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.
-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 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.

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

-verbose

Print all external commands before they are executed, in particular invocations of the assembler,
C compiler, and linker. 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:
**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.

**Cannot exec ocamrun**

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

**Cannot find the bytecode file**

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

**Truncated bytecode file**

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

**Uncaught exception**

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

**Out of memory**

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

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

**-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.
# Chapter 16

## Native-code compilation (ocamlopt)

This chapter describes the OCaml high-performance native-code compiler `ocamlopt`, which compiles OCaml source files to native code object files and links these object files to produce standalone executables.

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

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

### 16.1 Overview of the compiler

The `ocamlopt` command has a command-line interface very close to that of `ocamlc`. It accepts the same types of arguments, and processes them sequentially, 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 `ocamlopt` compiler produces a compiled interface in the file `x.cmi`. The interface produced is identical to that produced by the bytecode compiler `ocamlc`.

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

The implementation is checked against the interface file `x.mli` (if it exists) as described in the manual for `ocamlc` (chapter 13).
**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.

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

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

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

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

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

The compiler is able to emit some information on its internal stages:

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

* `.cmir-linear` files for the implementation of the compilation unit if the option `-save-ir-after scheduling` is passed to it. Each such file contains a low-level intermediate representation, produced by the instruction scheduling pass.

An external tool can perform low-level optimisations, such as code layout, by transforming a `.cmir-linear` file. To continue compilation, the compiler can be invoked with (a possibly modified) `.cmir-linear` file as an argument, instead of the corresponding source file.

## 16.2 Options

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

* `-a` Build a library (`.cmxa` and `.a/..lib` files) with the object files (`.cmx` and `.o/..obj` 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.
**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)

**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)
If `-cclib` or `-ccopt` options are passed on the command line, these options are stored in the resulting `.cmxalibrary`. Then, linking with this library automatically adds back the `-cclib` and `-ccopt` options as if they had been provided on the command line, unless the `-noautolink` option is given.

**-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 called to build the final executable 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 linker. This causes the given C library to be linked with the program.

**-ccopt option**

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

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

**-compact**

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

**-config**

Print the version number of `ocamlopt` 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 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.

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

**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.
-for-pack *module-path*

Generate an object file (`.cmx` and `.o`/.`obj` files) that can later be included as a sub-module (with the given access path) of a compilation unit constructed with `-pack`. For instance, `ocamlopt -for-pack P -c A.ml` will generate `a.cmx` and `a.o` files that can later be used with `ocamlopt -pack -o P.cmx a.cmx`. 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 produce stack backtraces when the program terminates on an uncaught exception (see section 15.2).

-no-g

Do not record debugging information (default).

-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 (`.cmx`), and libraries (`.cmxa`). By default, the current directory is searched first, then the standard library directory. Directories added with `-I` are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. 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`.

-inline *n*

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

**Options for the 64-bit x86 architecture** The 64-bit code generator for Intel/AMD x86 processors (`amd64` architecture) supports the following additional options:

**-fPIC**

Generate position-independent machine code. This is the default.
- `-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
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.

- `-linscan`

Use linear scan register allocation. Compiling with this allocator is faster than with the usual
graph coloring allocator, sometimes quite drastically so for long functions and modules. On
the other hand, the generated code can be a bit slower.

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

- `-no-float-const-prop`

Deactivates the constant propagation for floating-point operations. This option should be
given if the program changes the float rounding mode during its execution.
**-fno-PIC**

Generate position-dependent machine code.

**Options for the PowerPC architecture** The PowerPC code generator supports the following additional options:

**-flarge-toc**

Enables the PowerPC large model allowing the TOC (table of contents) to be arbitrarily large. This is the default since 4.11.

**-fsmall-toc**

Enables the PowerPC small model allowing the TOC to be up to 64 kbytes per compilation unit. Prior to 4.11 this was the default behaviour.

**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 : | ; ,.

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

## 16.3 Common errors

The error messages are almost identical to those of ocamlc. See section 13.4.

## 16.4 Running executables produced by ocamlopt

Executables generated by ocamlopt are native, stand-alone executable files that can be invoked directly. They do not depend on the ocamlrun bytecode runtime system nor on dynamically-loaded C/OCaml stub libraries.

During execution of an ocamlopt-generated executable, the following environment variables are also consulted:
-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 `.cmx` libraries, ignore `-cclib` and `-ccopt` options potentially contained in the libraries (if these options were given when building the libraries). This can be useful if a library contains incorrect specifications of C libraries or C options; in this case, during linking, set `-noautolink` and pass the correct C libraries and options on the command line.

-nodynlink

Allow the compiler to use some optimizations that are valid only for code that is statically linked to produce a non-relocatable executable. The generated code cannot be linked to produce a shared library nor a position-independent executable (PIE). Many operating systems produce PIEs by default, causing errors when linking code compiled with `-nodynlink`. Either do not use `-nodynlink` or pass the option `-ccopt -no-pie` at link-time.

-nolabels

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

-nostdlib

Do not automatically add the standard library directory to the list of directories searched for compiled interface files (`.cmi`), compiled object code files (`.cmx`), and libraries (`.cmxa`). 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 `-shared` option is given, specify the name of plugin file produced.

-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.
### OCAMLRUNPARAM

Same usage as in `ocamlrun` (see section 15.2), except that option `l` is ignored (the operating system's stack size limit is used instead).

### CAMLRUNPARAM

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

## 16.5 Compatibility with the bytecode compiler

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

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

* On ARM and PowerPC processors (32 and 64 bits), fused multiply-add (FMA) instructions can be generated for a floating-point multiplication followed by a floating-point addition or subtraction, as in `x *. y +. z`. The FMA instruction avoids rounding the intermediate result `x *. y`, which is generally beneficial, but produces floating-point results that differ slightly from those produced by the bytecode interpreter.

* The native-code compiler performs a number of optimizations that the bytecode compiler does not perform, especially when the `Lambda` optimizer is active. In particular, the native-code compiler identifies and eliminates “dead code”, i.e. computations that do not contribute to the results of the program. For example,

```
let _ = ignore M.f
```

contains a reference to compilation unit `M` when compiled to bytecode. This reference forces `M` to be linked and its initialization code to be executed. The native-code compiler eliminates the reference to `M`, hence the compilation unit `M` may not be linked and executed. A workaround is to compile `M` with the `-linkall` flag so that it will always be linked and executed, even if not referenced. See also the `Sys.opaque_identity` function from the `Sys` standard library module.

* Before 4.10, stack overflows, typically caused by excessively deep recursion, are not always turned into a `Stack_overflow` exception like with the bytecode compiler. The runtime system makes a best effort to trap stack overflows and raise the `Stack_overflow` exception, but sometimes it fails and a “segmentation fault” or another system fault occurs instead.
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 an 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 compiled shared/dynamic library (`.so` extension, `.dll` under Windows).

**-output-complete-obj**

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

**-pack**

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

`ocamopt -pack -o P.cmx A.cmx B.cmx C.cmx`

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

The `.cmx` object files being combined must have been compiled with the appropriate `-for-pack` option. In the example above, `A.cmx`, `B.cmx` and `C.cmx` must have been compiled with `ocamopt -for-pack P`.

Multiple levels of packing can be achieved by combining `-pack` with `-for-pack`. Consider the following example:

`ocamopt -for-pack P.Q -c A.ml ocamopt -pack -o Q.cmx -for-pack P A.cmx ocamopt -for-pack P -c B.ml ocamopt -pack -o P.cmx Q.cmx B.cmx`

The resulting `P.cmx` object file has sub-modules `P.Q`, `P.Q.A` and `P.B`.
# Chapter 17

## Parser and parser generators (ocamllex, ocamlyacc)

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

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

### 17.1 Overview of ocamllex

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

```
ocamllex lexer.mll
```

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

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

When used in conjunction with a parser generated by `ocamlyacc`, the semantic actions compute a value belonging to the type `token` defined by the generated parsing module. (See the description of `ocamlyacc` below.)
-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.

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

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

-save-ir-after *pass*

Save intermediate representation after the given compilation pass to a file. The currently supported passes and the corresponding file extensions are: `scheduling` (`.cmir-linear`).

This experimental feature enables external tools to inspect and manipulate compiler's intermediate representation of the program using `compiler-libs` library (see section 30).

-shared

Build a plugin (usually `.cmxs`) that can be dynamically loaded with the `Dynlink` module. The
### 17.1.1 Options

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

- **-ml** Output code that does not use OCaml's built-in automata interpreter. Instead, the automaton is encoded by OCaml functions. This option improves performance when using the native compiler, but decreases it when using the bytecode compiler.

- **-o output-file**
Specify the name of the output file produced by `ocamllex`. The default is the input file name with its extension replaced by `.ml`.

- **-q** Quiet mode. `ocamllex` normally outputs informational messages to standard output. They are suppressed if option `-q` is used.

- **-v** or **-version**
Print version string and exit.

- **-vnum**
Print short version number and exit.

- **-help** or **--help**
Display a short usage summary and exit.

## 17.2 Syntax of lexer definitions

The format of lexer definitions is as follows:

```
{
    header
}

let ident = regexp ...

[refill { refill-block }]

rule entrypoint [arg₁... argₙ] =
    parse regexp { action }
  | ...
  | regexp { action }

and entrypoint [arg₁... argₙ] =
    parse ...

and ...

{ trailer }
```

Comments are delimited by `(*` and `*`)`, as in OCaml. The `parse` keyword, can be replaced by the `shortest` keyword, with the semantic consequences explained below.

Refill handlers are a recent (optional) feature introduced in 4.02, documented below in subsection 17.2.7.
name of the plugin must be set with the `-o` option. A plugin can include a number of OCaml modules and libraries, and extra native objects (`.o`, `.obj`, `.a`, `.lib` files). Building native plugins is only supported for some operating system. Under some systems (currently, only Linux AMD 64), all the OCaml code linked in a plugin must have been compiled without the `-nodynlink` flag. Some constraints might also apply to the way the extra native objects have been compiled (under Linux AMD 64, they must contain only position-independent code).

**-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`, `scheduling`, `emit`.

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

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

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

### 17.2.2 Naming regular expressions

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

### 17.2.3 Entry points

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

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

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

### 17.2.4 Regular expressions

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

`regexp ::= ...`

`' regular-char | escape-sequence '`

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

`_` (underscore) Match any character.

`eof` Match the end of the lexer input.

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

`" {string-character} "`

A string constant, with the same syntax as OCaml string constants. Match the corresponding sequence of characters.
**-verbose**

Print all external commands before they are executed, in particular invocations of the assembler, C compiler, and linker. 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*.

**-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:
[ character-set ]

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

[ ~ character-set ]

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

regexp1 # regexp2

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

regexp *

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

regexp +

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

regexp ?

(option) Match the empty string, or a string matching `regexp`.

regexp1 | regexp2

(alternative) Match any string that matches `regexp1` or `regexp2`. If both `regexp1` and `regexp2` are character sets, this construction produces another character set, obtained by taking the union of `regexp1` and `regexp2`.

regexp1 regexp2

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

( regexp )

Match the same strings as `regexp`.

ident

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

regexp as ident

Bind the substring matched by `regexp` to identifier `ident`.

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

### 17.2.5 Actions

The actions are arbitrary OCaml expressions. They are evaluated in a context where the identifiers defined by using the `as` construct are bound to subparts of the matched string. Additionally, `lexbuf` is bound to the current lexer buffer. Some typical uses for `lexbuf`, in conjunction with the operations on lexer buffers provided by the `Lexing` standard library module, are listed below.
**+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.
**Lexing.lexeme lebuf**

Return the matched string.

**Lexing.lexeme_char lebuf n**

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

**Lexing.lexeme_start lebuf**

Return the absolute position in the input text of the beginning of the matched string (i.e. the offset of the first character of the matched string). The first character read from the input text has offset 0.

**Lexing.lexeme_end lebuf**

Return the absolute position in the input text of the end of the matched string (i.e. the offset of the first character after the matched string). The first character read from the input text has offset 0.

**entrypoint [exp₁... expₙ] lebuf**

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

### 17.2.6 Variables in regular expressions

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

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

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

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

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

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

In some cases, a successful match may not yield a unique set of bindings. For instance the matching of `aba` by the regular expression `(( 'a' | "ab" ) as x) (( "ba" | 'a') as y)` may result in binding either `x` to `"ab"` and `y` to `"a"`, or `x` to `"a"` and `y` to `"ba"`. The automata produced by `ocamllex` on such ambiguous regular expressions will select one of the possible resulting sets of bindings. The selected set of bindings is purposely left unspecified.
**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)
### 17.2.7 Refill handlers

By default, when `ocamllex` reaches the end of its lexing buffer, it will silently call the `refill_buff` function of `lexbuf` structure and continue lexing. It is sometimes useful to be able to take control of refilling action; typically, if you use a library for asynchronous computation, you may want to wrap the refilling action in a delaying function to avoid blocking synchronous operations.

Since OCaml 4.02, it is possible to specify a *refill handler*, a function that will be called when refill happens. It is passed the continuation of the lexing, on which it has total control. The OCaml expression used as refill action should have a type that is an instance of

`(Lexing.lexbuf -> 'a) -> Lexing.lexbuf -> 'a`

where the first argument is the continuation which captures the processing `ocamllex` would usually perform (refilling the buffer, then calling the lexing function again), and the result type that instantiates `['a]` should unify with the result type of all lexing rules.

As an example, consider the following lexer that is parametrized over an arbitrary monad:

```ocaml
{
  type token = EOL | INT of int | PLUS

  module Make (M : sig
    type 'a t
    val return: 'a -> 'a t
    val bind: 'a t -> ('a -> 'b t) -> 'b t
    val fail : string -> 'a t

    (* Set up lexbuf *)
    val on_refill : Lexing.lexbuf -> unit t
  end)

  = struct

  let refill_handler k lexbuf =
    M.bind (M.on_refill lexbuf) (fun () -> k lexbuf)
}

refill {refill_handler}

rule token = parse
  | [' ' '\t']
  | { token lexbuf }
  | '\n'
  | { M.return EOL }
  | ['0'-'9']+ as i
  | { M.return (INT (int_of_string i)) }
  | '+'
  | { M.return PLUS }
```
**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)
```
|
{ M fail "unexpected character" }
{
end
}
```

### 17.2.8 Reserved identifiers

All identifiers starting with `__ocaml_lex` are reserved for use by `ocamllex`; do not use any such identifier in your programs.

## 17.3 Overview of ocamlyacc

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

`ocamlyacc options grammar.mly`

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

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

## 17.4 Syntax of grammar definitions

Grammar definitions have the following format:

```
%{
    header
}%
%{
    declarations
}%
%{
    rules
}%
%{
    trailer
```

Comments are delimited by (`*` and `*`), as in OCaml. Additionally, comments can be delimited by `/*` and `*/`, as in C, in the "declarations" and "rules" sections. C-style comments do not nest, but OCaml-style comments do.
**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)
### 17.4.1 Header and trailer

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

### 17.4.2 Declarations

Declarations are given one per line. They all start with a `%` sign.

**`%token constr... constr`**

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

**`%token < typexpr > constr... constr`**

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

**`%start symbol...symbol`**

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

**`%type < typexpr > symbol...symbol`**

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

**`%left symbol...symbol`**

**`%right symbol...symbol`**

**`%nonassoc symbol...symbol`**

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

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

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

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

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

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

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

### 17.4.3 Rules

The syntax for rules is as usual:

```
nonterminal :
    symbol ... symbol { semantic-action }
  | ...
  | symbol ... symbol { semantic-action }
;
```

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

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

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

Actions occurring in the middle of rules are not supported.

Nonterminal symbols are like regular OCaml symbols, except that they cannot end with ' (single quote).
**-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.

**Options for the 64-bit x86 architecture** The 64-bit code generator for Intel/AMD x86 processors (`amd64` architecture) supports the following additional options:

**-fPIC**

Generate position-independent machine code. This is the default.

**-fno-PIC**

Generate position-dependent machine code.

**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 `:|;,.`.
### 17.4.4 Error handling

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

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

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

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

## 17.5 Options

The ocamlyacc command recognizes the following options:

**-bprefix**

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

**-q** This option has no effect.

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

**-version**

Print version string and exit.

**-vnum**

Print short version number and exit.

**-** Read the grammar specification from standard input. The default output file names are `stdin.m1` and `stdin.mli`.

**--file**

Process *file* as the grammar specification, even if its name starts with a dash (-) character. This option must be the last on the command line.

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

## 16.3 Common errors

The error messages are almost identical to those of `ocamlc`. See section 13.4.

## 16.4 Running executables produced by ocamlopt

Executables generated by `ocamlopt` are native, stand-alone executable files that can be invoked directly. They do not depend on the `ocamlrun` bytecode runtime system nor on dynamically-loaded C/OCaml stub libraries.

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

**OCAMLRUNPARAM**

Same usage as in `ocamlrun` (see section 15.2), except that option `l` is ignored (the operating system's stack size limit is used instead).

**CAMLRUNPARAM**

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

## 16.5 Compatibility with the bytecode compiler

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

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

* On ARM and PowerPC processors (32 and 64 bits), fused multiply-add (FMA) instructions can be generated for a floating-point multiplication followed by a floating-point addition or subtraction, as in `x *. y +. z`. The FMA instruction avoids rounding the intermediate result `x *. y`, which is generally beneficial, but produces floating-point results that differ slightly from those produced by the bytecode interpreter.

* The native-code compiler performs a number of optimizations that the bytecode compiler does not perform, especially when the `Lambda` optimizer is active. In particular, the native-code compiler identifies and eliminates “dead code”, i.e. computations that do not contribute to the results of the program. For example,

`let _ = ignore M.f`
## 17.6 A complete example

The all-time favorite: a desk calculator. This program reads arithmetic expressions on standard input, one per line, and prints their values. Here is the grammar definition:

```c
/* File parser.mly */
%token <int> INT
%token PLUS MINUS TIMES DIV
%token LPAREN RPAREN
%token EOL
%left PLUS MINUS      /* lowest precedence */
%left TIMES DIV       /* medium precedence */
%nonassoc UMINUS      /* highest precedence */
%start main          /* the entry point */
%type <int> main
%%
main:
    expr EOL          { $1 }
;
expr:
    INT              { $1 }
  | LPAREN expr RPAREN { $2 }
  | expr PLUS expr    { $1 + $3 }
  | expr MINUS expr   { $1 - $3 }
  | expr TIMES expr   { $1 * $3 }
  | expr DIV expr     { $1 / $3 }
  | MINUS expr %prec UMINUS { - $2 }
;
```

Here is the definition for the corresponding lexer:

```c
(* File lexer.mll *)
{
    open Parser      (* The type token is defined in parser.mli *)
    exception Eof
}
rule token = parse
    [' ' '\t']   { token lexbuf } (* skip blanks *)
  | ['\n']      { EOL }
  | ['0'-'9']+ as lxm { INT(int_of_string lxm) }
  | '+'          { PLUS }
  | '-'          { MINUS }
  | '*'          { TIMES }
  | '/'          { DIV }
  | '('          { LPAREN }
  | ')'          { RPAREN }
  | eof           { raise Eof }
```
contains a reference to compilation unit *M* when compiled to bytecode. This reference forces *M* to be linked and its initialization code to be executed. The native-code compiler eliminates the reference to *M*, hence the compilation unit *M* may not be linked and executed. A workaround is to compile *M* with the `-linkall` flag so that it will always be linked and executed, even if not referenced. See also the `Sys.opaque_identity` function from the `Sys` standard library module.

* Before 4.10, stack overflows, typically caused by excessively deep recursion, are not always turned into a `Stack_overflow` exception like with the bytecode compiler. The runtime system makes a best effort to trap stack overflows and raise the `Stack_overflow` exception, but sometimes it fails and a "segmentation fault" or another system fault occurs instead.
Here is the main program, that combines the parser with the lexer:

```
(* File calc.ml *)
let _ =
  try
    let lexbuf = Lexing.from_channel stdin in
    while true do
      let result = Parser.main lexer token lexbuf in
      print_int result; print_newline(); flush stdout
    done
  with Parser.Eof ->
    exit 0
```

To compile everything, execute:

```
ocamllex lexer.mll          # generates lexer.ml
ocamlyacc parser.mly        # generates parser.ml and parser.mli
ocamlc -c parser.mli
ocamlc -c lexer.ml
ocamlc -c parser.ml
ocamlc -c calc.ml
ocamlc -o calc lexer.cmo parser.cmo calc.cmo
```

## 17.7 Common errors

ocamllex: transition table overflow, automaton is too big

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

```
rule token = parse
  "keyword1"   { KWD1 }
  "keyword2"   { KWD2 }
  ...
  "keyword100" { KWD100 }
  ['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
    { IDENT id }
```

To keep the generated automata small, rewrite those definitions with only one general "identifier" rule, followed by a hashtable lookup to separate keywords from identifiers:

```
{ let keyword_table = Hashtbl.create 53
let _ =
  List.iter (fun (kwd, tok) -> Hashtbl.add keyword_table kwd tok)
```
```c
    [ "keyword1", KWD1;
    "keyword2", KWD2; ...
    "keyword100", KWD100 ]
}

rule token = parse
    ['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
    { try
        Hashtbl.find keyword_table id
        with Not_found ->
        IDENT id }
```

**ocamllex: Position memory overflow, too many bindings**

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

**ocamlyacc: concurrency safety**

Parsers generated by **ocamlyacc** are not thread-safe. Those parsers rely on an internal work state which is shared by all **ocamlyacc** generated parsers. The **menhir** parser generator is a better option if you want thread-safe parsers.
# Chapter 17

## Parser and parser generators (ocamllex, ocamlyacc)

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

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

### 17.1 Overview of ocamllex

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

```
ocamllex lexer.mll
```

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

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

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

The following command-line options are recognized by ocamllex.

- **-ml** Output code that does not use OCaml's built-in automata interpreter. Instead, the automaton is encoded by OCaml functions. This option improves performance when using the native compiler, but decreases it when using the bytecode compiler.

- **-o output-file**
Specify the name of the output file produced by ocamllex. The default is the input file name with its extension replaced by **.ml**.

- **-q** Quiet mode. ocamllex normally outputs informational messages to standard output. They are suppressed if option **-q** is used.

- **-v** or **-version**
Print version string and exit.

- **-vnum**
Print short version number and exit.

- **-help** or **--help**
Display a short usage summary and exit.

## 17.2 Syntax of lexer definitions

The format of lexer definitions is as follows:

```
{
    header
}

let ident = regexp ...

[refill { refill-block }]

rule entrypoint [arg₁... argₙ] =
    parse regexp { action }
  | ...
  | regexp { action }

and entrypoint [arg₁... argₙ] =
    parse ...

and ...

{
    trailer
}
```

Comments are delimited by (`*` and `*`), as in OCaml. The `parse` keyword, can be replaced by the `shortest` keyword, with the semantic consequences explained below.

Refill handlers are a recent (optional) feature introduced in 4.02, documented below in subsection 17.2.7.
# Chapter 18

## Dependency generator (ocamldep)

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

The typical usage is:

```
ocamldep options *.mli *.ml > .depend
```

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

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

### 18.1 Options

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

**-absname**

Show absolute filenames in error messages.

**-all**

Generate dependencies on all required files, rather than assuming implicit dependencies.

**-allow-approx**

Allow falling back on a lexer-based approximation when parsing fails.

**-args filename**

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

**-args0 filename**

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

**-as-map**

For the following files, do not include delayed dependencies for module aliases. This option
### 17.2.1 Header and trailer

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

### 17.2.2 Naming regular expressions

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

### 17.2.3 Entry points

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

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

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

### 17.2.4 Regular expressions

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

`regexp ::= ...`

`' regular-char | escape-sequence '`

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

`_` (underscore) Match any character.

`eof` Match the end of the lexer input.

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

`" {string-character} "`

A string constant, with the same syntax as OCaml string constants. Match the corresponding sequence of characters.
assumes that they are compiled using options `-no-alias-deps -w -49`, and that those files or their interface are passed with the `-map` option when computing dependencies for other files. Note also that for dependencies to be correct in the implementation of a map file, its interface should not coerce any of the aliases it contains.

**-debug-map**

Dump the delayed dependency map for each map file.

**-I *directory***

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

**-nocwd**

Do not add current working directory to the list of include directories.

**-impl *file***

Process *file* as a `.ml` file.

**-intf *file***

Process *file* as a `.mli` file.

**-map *file***

Read and propagate the delayed dependencies for module aliases in *file*, so that the following files will depend on the exported aliased modules if they use them. See the example below.

**-ml-synonym *.ext**

Consider the given extension (with leading dot) to be a synonym for `.ml`.

**-mli-synonym *.ext**

Consider the given extension (with leading dot) to be a synonym for `.mli`.

**-modules**

Output raw dependencies of the form

`filename: Module1 Module2 ... ModuleN`

where `Module1`, ..., `ModuleN` are the names of the compilation units referenced within the file `filename`, but these names are not resolved to source file names. Such raw dependencies cannot be used by `make`, but can be post-processed by other tools such as `Omake`.

**-native**

Generate dependencies for a pure native-code program (no bytecode version). When an implementation file (`.ml` file) has no explicit interface file (`.mli` file), `ocamldep` generates dependencies on the bytecode compiled file (`.cmo` file) to reflect interface changes. This can cause unnecessary bytecode recompilations for programs that are compiled to native-code only.
[ character-set ]

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

[ ~ character-set ]

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

regexp₁ # regexp₂

(difference of character sets) Regular expressions `regexp₁` and `regexp₂` must be character sets defined with `[...]` (or a single character expression or underscore _). Match the difference of the two specified character sets.

regexp *

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

regexp +

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

regexp ?

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

regexp₁ | regexp₂

(alternative) Match any string that matches `regexp₁` or `regexp₂`. If both `regexp₁` and `regexp₂` are character sets, this construction produces another character set, obtained by taking the union of `regexp₁` and `regexp₂`.

regexp₁ regexp₂

(concatenation) Match the concatenation of two strings, the first matching `regexp₁`, the second matching `regexp₂`.

( regexp )

Match the same strings as regexp.

ident

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

regexp as ident

Bind the substring matched by `regexp` to identifier `ident`.

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

### 17.2.5 Actions

The actions are arbitrary OCaml expressions. They are evaluated in a context where the identifiers defined by using the `as` construct are bound to subparts of the matched string. Additionally, `lexbuf` is bound to the current lexer buffer. Some typical uses for `lexbuf`, in conjunction with the operations on lexer buffers provided by the `Lexing` standard library module, are listed below.
The flag `-native` causes dependencies on native compiled files (`.cmx`) to be generated instead of on `.cmo` files. (This flag makes no difference if all source files have explicit `.mli` interface files.)

**-one-line**

Output one line per file, regardless of the length.

**-open module**

Assume that module *module* is opened before parsing each of the following files.

**-pp command**

Cause `ocamldep` to call the given *command* as a preprocessor for each source file.

**-ppx command**

Pipe abstract syntax trees through preprocessor *command*.

**-shared**

Generate dependencies for native plugin files (`.cmxs`) in addition to native compiled files (`.cmx`).

**-slash**

Under Windows, use a forward slash (`/`) as the path separator instead of the usual backward slash (`\`). Under Unix, this option does nothing.

**-sort**

Sort files according to their dependencies.

**-version**

Print version string and exit.

**-vnum**

Print short version number and exit.

**-help or --help**

Display a short usage summary and exit.

## 18.2 A typical Makefile

Here is a template `Makefile` for a OCaml program.

```
OCAMLC=ocamlc
OCAMLOPT=ocamlopt
OCAMLDEP=ocamldep
INCLUDES=                 # all relevant -I options here
OCAMLFLAGS=$ (INCLUDES)   # add other options for ocamlc here
OCAMLOPTFLAGS=$ (INCLUDES) # add other options for ocamlopt here
```

# prog1 should be compiled to bytecode, and is composed of three
**Lexing.lexeme lexbuf**

Return the matched string.

**Lexing.lexeme_char lexbuf n**

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

**Lexing.lexeme_start lexbuf**

Return the absolute position in the input text of the beginning of the matched string (i.e. the offset of the first character of the matched string). The first character read from the input text has offset 0.

**Lexing.lexeme_end lexbuf**

Return the absolute position in the input text of the end of the matched string (i.e. the offset of the first character after the matched string). The first character read from the input text has offset 0.

**entrypoint [exp₁... expₙ] lexbuf**

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

### 17.2.6 Variables in regular expressions

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

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

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

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

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

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

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

# The list of object files for prog1
PROG1 ObJS=mod1.cmo mod2.cmo mod3.cmo

prog1: $(PROG1 ObJS)
$(OCAMLC) -o prog1 $(OCAMLFLAGS) $(PROG1 ObJS)

# prog2 should be compiled to native-code, and is composed of two
# units: mod4 and mod5.

# The list of object files for prog2
PROG2 ObJS=mod4.cmx mod5.cmx

prog2: $(PROG2 ObJS)
$(OCAMLOPT) -o prog2 $(OCAMLFLAGS) $(PROG2 ObJS)

# Common rules

%.cmo: %.ml
$(OCAMLC) $(OCAMLFLAGS) -c $<

%.cmi: %.mli
$(OCAMLC) $(OCAMLFLAGS) -c $<

%.cmx: %.ml
$(OCAMLOPT) $(OCAMLOPTFLAGS) -c $<

# Clean up

clean:
rm -f prog1 prog2
rm -f *.cm[iox]

# Dependencies

depend:
$(OCAMLDEP) $(INCLUDES) *.mli *.ml > .depend

include .depend

If you use module aliases to give shorter names to modules, you need to change the above definitions. Assuming that your map file is called mylib.mli, here are minimal modifications.

OCAMLFLAGS=$(INCLUDES) -open Mylib

mylib.cmi: mylib.mli
$(OCAMLC) $(INCLUDES) -no-alias-deps -w -49 -c $<
### 17.2.7 Refill handlers

By default, when ocamllex reaches the end of its lexing buffer, it will silently call the `refill_buff` function of `lexbuf` structure and continue lexing. It is sometimes useful to be able to take control of refilling action; typically, if you use a library for asynchronous computation, you may want to wrap the refilling action in a delaying function to avoid blocking synchronous operations.

Since OCaml 4.02, it is possible to specify a *refill handler*, a function that will be called when refill happens. It is passed the continuation of the lexing, on which it has total control. The OCaml expression used as refill action should have a type that is an instance of

```
(Lexing.lexbuf -> 'a) -> Lexing.lexbuf -> 'a
```

where the first argument is the continuation which captures the processing ocamllex would usually perform (refilling the buffer, then calling the lexing function again), and the result type that instantiates `['a]` should unify with the result type of all lexing rules.

As an example, consider the following lexer that is parametrized over an arbitrary monad:

```ocaml
{
  type token = EOL | INT of int | PLUS

  module Make (M : sig
    type 'a t
    val return: 'a -> 'a t
    val bind: 'a t -> ('a -> 'b t) -> 'b t
    val fail : string -> 'a t

    (* Set up lexbuf *)
    val on_refill : Lexing.lexbuf -> unit t
  end)

= struct

  let refill_handler k lexbuf =
    M.bind (M.on_refill lexbuf) (fun () -> k lexbuf)
}

refill {refill_handler}

rule token = parse
  | [' ' '\t']
  | { token lexbuf }
  | '\n'
  | { M.return EOL }
  | ['0'-'9']+ as i
  | { M.return (INT (int_of_string i)) }
  | '+'
  | { M.return PLUS }
```
depend:

$(OCAMLDEP) $(INCLUDES) -map mylib.mli $(PROG1 ObJS:.cmo=.ml) > .depend

Note that in this case you should not compute dependencies for mylib.mli together with the
other files, hence the need to pass explicitly the list of files to process. If mylib.mli itself has
dependencies, you should compute them using -as-map.
```
|
{ M fail "unexpected character" }
{
end
}
```

### 17.2.8 Reserved identifiers

All identifiers starting with `__ocaml_lex` are reserved for use by `ocamllex`; do not use any such identifier in your programs.

## 17.3 Overview of ocamlyacc

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

`ocamlyacc options grammar.mly`

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

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

## 17.4 Syntax of grammar definitions

Grammar definitions have the following format:

```
%{
    header
}%
%{
    declarations
}%
%{
    rules
}%
%{
    trailer
```

Comments are delimited by (`*` and `*`), as in OCaml. Additionally, comments can be delimited by `/*` and `*/`, as in C, in the "declarations" and "rules" sections. C-style comments do not nest, but OCaml-style comments do.
### 17.4.1 Header and trailer

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

### 17.4.2 Declarations

Declarations are given one per line. They all start with a `%` sign.

**`%token constr... constr`**

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

**`%token < typexpr > constr... constr`**

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

**`%start symbol...symbol`**

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

**`%type < typexpr > symbol...symbol`**

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

**`%left symbol...symbol`**

**`%right symbol...symbol`**

**`%nonassoc symbol...symbol`**

Associate precedences and associativities to the given symbols. All symbols on the same line are given the same precedence. They have higher precedence than symbols declared before in a `%left`, `%right` or `%nonassoc` line. They have lower precedence than symbols declared
Chapter 19

The documentation generator
(ocamldoc)

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

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

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

19.1 Usage

19.1.1 Invocation

OCamldoc is invoked via the command *ocamldoc*, as follows:

`ocamldoc options sourcefiles`

Options for choosing the output format

The following options determine the format for the generated documentation.

-html

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

-latex

Generate documentation in LATEX default format. The generated LATEX document is saved in
after in a `%left`, `%right` or `%nonassoc` line. The symbols are declared to associate to the
left (`%left`), to the right (`%right`), or to be non-associative (`%nonassoc`). The symbols are
usually tokens. They can also be dummy nonterminals, for use with the `%prec` directive inside
the rules.

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

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

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

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

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

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

### 17.4.3 Rules

The syntax for rules is as usual:

```
nonterminal :
symbol ... symbol { semantic-action }
| ...
| symbol ... symbol { semantic-action }
;
```

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

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

The rules may contain the special symbol `error` to indicate resynchronization points, as in `yacc`.
Actions occurring in the middle of rules are not supported.

Nonterminal symbols are like regular OCaml symbols, except that they cannot end with ' (single quote).
file ocamldoc.out, or in the file specified with the -o option. The document uses the style file ocamldoc.sty. This file is generated when using the -latex option, if it does not already exist. You can change this file to customize the style of your LATEX documentation.

-texi

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

-man

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

-dot

Generate a dependency graph for the toplevel modules, in a format suitable for displaying and processing by dot. The dot tool is available from https://graphviz.org/. The textual representation of the graph is written to the file ocamldoc.out, or to the file specified with the -o option. Use dot ocamldoc.out to display it.

-g file.cm[o,a,xs]

Dynamically load the given file, which defines a custom documentation generator. See section 19.4.1. This option is supported by the ocamldoc command (to load .cmo and .cma files) and by its native-code version ocamldoc.opt (to load .cmxs files). If the given file is a simple one and does not exist in the current directory, then ocamldoc looks for it in the custom generators default directory, and in the directories specified with optional -i options.

-customdir

Display the custom generators default directory.

-i directory

Add the given directory to the path where to look for custom generators.

## General options

-d dir

Generate files in directory dir, rather than the current directory.

-dump file

Dump collected information into file. This information can be read with the -load option in a subsequent invocation of ocamldoc.

-hide modules

Hide the given complete module names in the generated documentation. modules is a list of complete module names separated by ',' without blanks. For instance: Stdlib,M2.M3.

-inv-merge-ml-mli

Reverse the precedence of implementations and interfaces when merging. All elements in implementation files are kept, and the -m option indicates which parts of the comments in interface files are merged with the comments in implementation files.
### 17.4.4 Error handling

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

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

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

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

## 17.5 Options

The ocamlyacc command recognizes the following options:

**-bprefix**

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

**-q** This option has no effect.

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

**-version**

Print version string and exit.

**-vnum**

Print short version number and exit.

**-** Read the grammar specification from standard input. The default output file names are `stdin.ml` and `stdin.mli`.

**--file**

Process *file* as the grammar specification, even if its name starts with a dash (-) character. This option must be the last on the command line.

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

Always keep the source code for values, methods and instance variables, when available.

-load file

Load information from *file*, which has been produced by `ocamldoc -dump`. Several `-load` options can be given.

-m *flags*

Specify merge options between interfaces and implementations. (see section 19.1.2 for details).

*flags* can be one or several of the following characters:

d merge description

a merge @author

v merge @version

l merge @see

s merge @since

b merge @before

o merge @deprecated

p merge @param

e merge @raise

r merge @return

A merge everything

-no-custom-tags

Do not allow custom @-tags (see section 19.2.12).

-no-stop

Keep elements placed after/between the (\*\*/\*\*) special comment(s) (see section 19.2).

-o *file*

Output the generated documentation to *file* instead of `ocamldoc.out`. This option is meaningful only in conjunction with the `-latex`, `-texi`, or `-dot` options.

-pp *command*

Pipe sources through preprocessor *command*.

-impl *filename*

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

-intf *filename*

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

-text *filename*

Process the file *filename* as a text file, even if its extension is not `.txt`.

-sort

Sort the list of top-level modules before generating the documentation.
17.6 A complete example

The all-time favorite: a desk calculator. This program reads arithmetic expressions on standard input, one per line, and prints their values. Here is the grammar definition:

/* File parser.mly */
%token <int> INT
%token PLUS MINUS TIMES DIV
%token LPAREN RPAREN
%token EOL
%left PLUS MINUS         /* lowest precedence */
%left TIMES DIV          /* medium precedence */
%nonassoc UMINUS         /* highest precedence */
%start main             /* the entry point */
%type <int> main
%%
main:
    expr EOL                 { $1 }
;
expr:
    INT                     { $1 }
  | LPAREN expr RPAREN       { $2 }
  | expr PLUS expr          { $1 + $3 }
  | expr MINUS expr         { $1 - $3 }
  | expr TIMES expr         { $1 * $3 }
  | expr DIV expr           { $1 / $3 }
  | MINUS expr %prec UMINUS { - $2 }
;

Here is the definition for the corresponding lexer:

(* File lexer.mll *)
{
    open Parser (* The type token is defined in parser.mli *)
    exception Eof
}
rule token = parse
    [ ' ' '\t'] { token lexbuf } (* skip blanks *)
  | [ ' \n' ] { EOL }
  | ['0'-'9']+ as lxm { INT(int_of_string lxm) }
  | '+' { PLUS }
  | '-' { MINUS }
  | '*' { TIMES }
  | '/' { DIV }
  | '(' { LPAREN }
  | ')' { RPAREN }
  | eof { raise Eof }
}
**-stars**

Remove blank characters until the first asterisk (`*`) in each line of comments.

**-t title**

Use *title* as the title for the generated documentation.

**-intro file**

Use content of *file* as ocamldoc text to use as introduction (HTML, LATEX and TeXinfo only).
For HTML, the file is used to create the whole *index.html* file.

**-v** Verbose mode. Display progress information.

**-version**

Print version string and exit.

**-vnum**

Print short version number and exit.

**-warn-error**

Treat Ocamldoc warnings as errors.

**-hide-warnings**

Do not print OCamldoc warnings.

**-help or --help**

Display a short usage summary and exit.

## Type-checking options

OCamldoc calls the OCaml type-checker to obtain type information. The following options impact the type-checking phase. They have the same meaning as for the *ocamlc* and *ocamlopt* commands.

**-I directory**

Add *directory* to the list of directories search for compiled interface files (`.cmi` files).

**-nlabels**

Ignore non-optional labels in types.

**-rectypes**

Allow arbitrary recursive types. (See the `-rectypes` option to *ocamlc*.)

## Options for generating HTML pages

The following options apply in conjunction with the `-html` option:

**-all-params**

Display the complete list of parameters for functions and methods.

**-charset charset**

Add information about character encoding being *charset* (default is `iso-8859-1`).
Here is the main program, that combines the parser with the lexer:

```c
(* File calc.ml *)
let _ =
  try
    let lexbuf = Lexing.from_channel stdin in
    while true do
      let result = Parser.main Parser token lexbuf in
      print_int result; print_newline(); flush stdout
    done
  with Parser.Eof ->
    exit 0
```

To compile everything, execute:

```bash
ocamllex lexer.mll          # generates lexer.ml
ocamlyacc parser.mly        # generates parser.ml and parser.mli
ocamlc -c parser.mli
ocamlc -c lexer.ml
ocamlc -c parser.ml
ocamlc -c calc.ml
ocamlc -o calc lexer.cmo parser.cmo calc.cmo
```

## 17.7 Common errors

**ocamllex: transition table overflow, automaton is too big**

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

```c
rule token = parse
  "keyword1"   { KWD1 }
  "keyword2"   { KWD2 }
  ...
  "keyword100" { KWD100 }
  [ 'A'-'Z' 'a'-'z' ] [ 'A'-'Z' 'a'-'z' '0'-'9' '._' ] * as id
    { IDENT id }
```

To keep the generated automata small, rewrite those definitions with only one general "identifier" rule, followed by a hashtable lookup to separate keywords from identifiers:

```c
{ let keyword_table = Hashtbl.create 53
let _ =
  List.iter (fun (kwd, tok) -> Hashtbl.add keyword_table kwd tok)
```
-colorize-code

Colorize the OCaml code enclosed in `[]` and `{{}}`, using colors to emphasize keywords, etc.
If the code fragments are not syntactically correct, no color is added.

-css-style filename

Use *filename* as the Cascading Style Sheet file.

-index-only

Generate only index files.

-short-functors

Use a short form to display functors:

module M : functor (A:Module) -> functor (B:Module2) -> sig .. end

is displayed as:

module M (A:Module) (B:Module2) : sig .. end

## Options for generating LATEX files

The following options apply in conjunction with the -latex option:

-latex-value-prefix *prefix*

Give a prefix to use for the labels of the values in the generated LATEX document. The default prefix is the empty string. You can also use the options -latex-type-prefix, -latex-exception-prefix, -latex-module-prefix, -latex-module-type-prefix, -latex-class-prefix, -latex-class-type-prefix, -latex-attribute-prefix and -latex-method-prefix.

These options are useful when you have, for example, a type and a value with the same name.
If you do not specify prefixes, LATEX will complain about multiply defined labels.

-latextitle *n*,*style*

Associate style number *n* to the given LATEX sectioning command *style*, e.g. *section* or *subsection*. (LATEX only.) This is useful when including the generated document in another LATEX document, at a given sectioning level. The default association is 1 for *section*, 2 for *subsection*, 3 for *subsubsection*, 4 for *paragraph* and 5 for *subparagraph*.

-noheader

Suppress header in generated documentation.

-notoc

Do not generate a table of contents.

-notrailers

Suppress trailer in generated documentation.

-sepfiles

Generate one .tex file per toplevel module, instead of the global ocamldoc.out file.
```c
    [ "keyword1", KWD1;
    "keyword2", KWD2; ...
    "keyword100", KWD100 ]
}

rule token = parse
    ['A'-'Z' 'a'-'z'] ['A'-'Z' 'a'-'z' '0'-'9' '_'] * as id
    { try
        Hashtbl.find keyword_table id
        with Not_found ->
            IDENT id }
```

**ocamllex: Position memory overflow, too many bindings**

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

**ocamlyacc: concurrency safety**

Parsers generated by `ocamlyacc` are not thread-safe. Those parsers rely on an internal work state which is shared by all `ocamlyacc` generated parsers. The `menhir` parser generator is a better option if you want thread-safe parsers.
## Options for generating TeXinfo files

The following options apply in conjunction with the `-texi` option:

**-esc8**

Escape accented characters in Info files.

**-info-entry**

Specify Info directory entry.

**-info-section**

Specify section of Info directory.

**-noheader**

Suppress header in generated documentation.

**-noindex**

Do not build index for Info files.

**-notrailер**

Suppress trailer in generated documentation.

## Options for generating dot graphs

The following options apply in conjunction with the `-dot` option:

**-dot-colors colors**

Specify the colors to use in the generated `dot` code. When generating module dependencies, `ocamldoc` uses different colors for modules, depending on the directories in which they reside. When generating types dependencies, `ocamldoc` uses different colors for types, depending on the modules in which they are defined. `colors` is a list of color names separated by ',' , as in `Red,Blue,Green`. The available colors are the ones supported by the `dot` tool.

**-dot-include-all**

Include all modules in the `dot` output, not only modules given on the command line or loaded with the `-load` option.

**-dot-reduce**

Perform a transitive reduction of the dependency graph before outputting the `dot` code. This can be useful if there are a lot of transitive dependencies that clutter the graph.

**-dot-types**

Output `dot` code describing the type dependency graph instead of the module dependency graph.
## Options for generating man files

The following options apply in conjunction with the `-man` option:

**-man-mini**

Generate man pages only for modules, module types, classes and class types, instead of pages for all elements.

**-man-suffix suffix**

Set the suffix used for generated man filenames. Default is '3o', as in `List.3o`.

**-man-section section**

Set the section number used for generated man filenames. Default is '3'.

### 19.1.2 Merging of module information

Information on a module can be extracted either from the `.mli` or `.ml` file, or both, depending on the files given on the command line. When both `.mli` and `.ml` files are given for the same module, information extracted from these files is merged according to the following rules:

* Only elements (values, types, classes, ...) declared in the `.mli` file are kept. In other terms, definitions from the `.ml` file that are not exported in the `.mli` file are not documented.

* Descriptions of elements and descriptions in `@-tags` are handled as follows. If a description for the same element or in the same `@-tag` of the same element is present in both files, then the description of the `.ml` file is concatenated to the one in the `.mli` file, if the corresponding `-m` flag is given on the command line. If a description is present in the `.ml` file and not in the `.mli` file, the `.ml` description is kept. In either case, all the information given in the `.mli` file is kept.

### 19.1.3 Coding rules

The following rules must be respected in order to avoid name clashes resulting in cross-reference errors:

* In a module, there must not be two modules, two module types or a module and a module type with the same name. In the default HTML generator, modules `ab` and `AB` will be printed to the same file on case insensitive file systems.

* In a module, there must not be two classes, two class types or a class and a class type with the same name.

* In a module, there must not be two values, two types, or two exceptions with the same name.

* Values defined in tuple, as in `let (x,y,z) = (1,2,3)` are not kept by OCamldoc.

* Avoid the following construction:
Chapter 18

Dependency generator (ocamldep)

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

The typical usage is:

`ocamldep options *.mli *.ml > .depend`

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

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

18.1 Options

The following command-line options are recognized by ocamldep.

-absname

Show absolute filenames in error messages.

-all

Generate dependencies on all required files, rather than assuming implicit dependencies.

-allow-approx

Allow falling back on a lexer-based approximation when parsing fails.

-args filename

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

-args0 filename

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

-as-map

For the following files, do not include delayed dependencies for module aliases. This option
```python
open Foo (* which has a module Bar with a value x *)
module Foo =
    struct
        module Bar =
            struct
                let x = 1
            end
    end
    let dummy = Bar.x
```

In this case, OCamldoc will associate `Bar.x` to the `x` of module `Foo` defined just above, instead of to the `Bar.x` defined in the opened module `Foo`.

## 19.2 Syntax of documentation comments

Comments containing documentation material are called *special comments* and are written between (\*\* and \*). Special comments must start exactly with (\*\*. Comments beginning with ( and more than two \* are ignored.

### 19.2.1 Placement of documentation comments

OCamldoc can associate comments to some elements of the language encountered in the source files. The association is made according to the locations of comments with respect to the language elements. The locations of comments in `.mli` and `.ml` files are different.

### 19.2.2 Comments in `.mli` files

A special comment is associated to an element if it is placed before or after the element.
A special comment before an element is associated to this element if:

* There is no blank line or another special comment between the special comment and the element. However, a regular comment can occur between the special comment and the element.

* The special comment is not already associated to the previous element.

* The special comment is not the first one of a toplevel module.

A special comment after an element is associated to this element if there is no blank line or comment between the special comment and the element.

There are two exceptions: for constructors and record fields in type definitions, the associated comment can only be placed after the constructor or field definition, without blank lines or other comments between them. The special comment for a constructor with another constructor following must be placed before the `|` character separating the two constructors.

The following sample interface file `foo.mli` illustrates the placement rules for comments in `.mli` files.

<footnote>(\*\* The first special comment of the file is the comment associated with the whole module.\*)</footnote>
assumes that they are compiled using options `-no-alias-deps -w -49`, and that those files or their interface are passed with the `-map` option when computing dependencies for other files. Note also that for dependencies to be correct in the implementation of a map file, its interface should not coerce any of the aliases it contains.

**-debug-map**

Dump the delayed dependency map for each map file.

**-I directory**

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

**-H directory**

Behaves identically to `-I`, except that the `-H` directories are searched last. This flag is included to make it easier to invoke `ocamldep` with the same options as the compiler, where `-H` is used for transitive dependencies that the program should not directly mention.

**-nocwd**

Do not add current working directory to the list of include directories.

**-impl file**

Process *file* as a `.ml` file.

**-intf file**

Process *file* as a `.mli` file.

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

**-map file**

Read and propagate the delayed dependencies for module aliases in *file*, so that the following files will depend on the exported aliased modules if they use them. See the example below.

**-ml-synonym .ext**

Consider the given extension (with leading dot) to be a synonym for `.ml`.

**-mli-synonym .ext**

Consider the given extension (with leading dot) to be a synonym for `.mli`.
(** Special comments can be placed between elements and are kept by the OCamldoc tool, but are not associated to any element. @—tags in these comments are ignored.*)

(*****************************************************************)

(** Comments like the one above, with more than two asterisks, are ignored. *)

(** The comment for function f. *)

val f : int -> int -> int

(** The continuation of the comment for function f. *)

(** Comment for exception My_exception, even with a simple comment between the special comment and the exception.*)

(* Hello, I'm a simple comment :-) *)

exception My_exception of (int -> int) * int

(** Comment for type weather *)

type weather =

| Rain of int (** The comment for constructor Rain *)

| Sun (** The comment for constructor Sun *)

(** Comment for type weather2 *)

type weather2 =

| Rain of int (** The comment for constructor Rain *)

| Sun (** The comment for constructor Sun *)

(** I can continue the comment for type weather2 here because there is already a comment associated to the last constructor.*)

(** The comment for type my_record *)

type my_record = {

foo : int ; (** Comment for field foo *)
bar : string ; (** Comment for field bar *)
}

(** Continuation of comment for type my_record *)

(** Comment for foo *)

val foo : string

(** This comment is associated to foo and not to bar. *)

val bar : string

(** This comment is associated to bar. *)

(** The comment for class my_class *)
-modules

Output raw dependencies of the form

filename: Module1 Module2 ... ModuleN

where *Module1*, ..., *ModuleN* are the names of the compilation units referenced within the file *filename*, but these names are not resolved to source file names. Such raw dependencies cannot be used by *make*, but can be post-processed by other tools such as *Omake*.

-native

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

-one-line

Output one line per file, regardless of the length.

-open *module*

Assume that module *module* is opened before parsing each of the following files.

-pp *command*

Cause *ocamldep* to call the given *command* as a preprocessor for each source file.

-ppx *command*

Pipe abstract syntax trees through preprocessor *command*.

-shared

Generate dependencies for native plugin files (`.cmxs`) in addition to native compiled files (`.cmx`).

-slash

Under Windows, use a forward slash (`/`) as the path separator instead of the usual backward slash (`\`). Under Unix, this option does nothing.

-sort

Sort files according to their dependencies.

-version

Print version string and exit.

-vnum

Print short version number and exit.

-help or --help

Display a short usage summary and exit.
class my_class :

object

(** A comment to describe inheritance from cl *)

inherit cl

(** The comment for attribute tutu *)

val mutable tutu : string

(** The comment for attribute toto. *)

val toto : int

(** This comment is not attached to titi since
there is a blank line before titi, but is kept
as a comment in the class. *)

val titi : string

(** Comment for method toto *)

method toto : string

(** Comment for method m *)

method m : float -> int

end

(** The comment for the class type my_class_type *)

class type my_class_type =

object

(** The comment for variable x. *)

val mutable x : int

(** The comment for method m. *)

method m : int -> int

end

(** The comment for module Foo *)

module Foo :

sig

(** The comment for x *)

val x : int

(** A special comment that is kept but not associated to any element *)

end

(** The comment for module type my_module_type. *)

module type my_module_type =
## 18.2 A typical Makefile

Here is a template Makefile for a OCaml program.

OCAMLC=ocamlc
OCAMLOPT=ocamlopt
OCAMLDEP=ocamldep

INCLUDES= # all relevant -I options here
OCAMLFLAGS=$(INCLUDES) # add other options for ocamlc here
OCAMLOPTFLAGS=$(INCLUDES) # add other options for ocamlopt here

# prog1 should be compiled to bytecode, and is composed of three
# units: mod1, mod2 and mod3.

# The list of object files for prog1
PROG1 ObJS=mod1.cmo mod2.cmo mod3.cmo

prog1: $(PROG1 ObJS)
$(OCAMLC) -o prog1 $(OCAMLFLAGS) $(PROG1 ObJS)

# prog2 should be compiled to native-code, and is composed of two
# units: mod4 and mod5.

# The list of object files for prog2
PROG2 ObJS=mod4.cmx mod5.cmx

prog2: $(PROG2 ObJS)
$(OCAMLOPT) -o prog2 $(OCAMLFLAGS) $(PROG2 ObJS)

# Common rules

%.cmo: %.ml
$(OCAMLC) $(OCAMLFLAGS) -c $<

%.cmi: %.mli
$(OCAMLC) $(OCAMLFLAGS) -c $<

%.cmx: %.ml
$(OCAMLOPT) $(OCAMLOPTFLAGS) -c $<

# Clean up

clean:
rm -f prog1 prog2
rm -f *.cm[iox]

# Dependencies
sig

(** The comment for value x. *)

val x : int

(** The comment for module M. *)

module M :

sig

(** The comment for value y. *)

val y : int

(* ... *)

end

end

### 19.2.3 Comments in .ml files

A special comment is associated to an element if it is placed before the element and there is no blank line between the comment and the element. Meanwhile, there can be a simple comment between the special comment and the element. There are two exceptions, for constructors and record fields in type definitions, whose associated comment must be placed after the constructor or field definition, without blank line between them. The special comment for a constructor with another constructor following must be placed before the ' | ' character separating the two constructors.

The following example of file toto.ml shows where to place comments in a .ml file.

(** The first special comment of the file is the comment associated to the whole module. *)

(** The comment for function f *)

let f x y = x + y

(** This comment is not attached to any element since there is another special comment just before the next element. *)

(** Comment for exception My_exception, even with a simple comment between the special comment and the exception.*)

(* A simple comment. *)

exception My_exception of (int -> int) * int

(** Comment for type weather *)

type weather =

| Rain of int (** The comment for constructor Rain *)

| Sun (** The comment for constructor Sun *)

(** The comment for type my_record *)

type my_record = {
```
depend:
    $(OCAMLDEP) $(INCLUDES) *.mli *.ml > .depend
```

```
include .depend
```

If you use module aliases to give shorter names to modules, you need to change the above definitions. Assuming that your map file is called `mylib.mli`, here are minimal modifications.

```
OCAMLFLAGS=$(INCLUDES) -open Mylib
```

```
mylib.cmi: mylib.mli
    $(OCAMLC) $(INCLUDES) -no-alias-deps -w -49 -c $<
```

```
depend:
    $(OCAMLDEP) $(INCLUDES) -map mylib.mli $(PROG1 ObJS:.cmo=.ml) > .depend
```

Note that in this case you should not compute dependencies for `mylib.mli` together with the other files, hence the need to pass explicitly the list of files to process. If `mylib.mli` itself has dependencies, you should compute them using `-as-map`.
```fortran
foo : int ;      (** Comment for field foo *)
bar : string ;   (** Comment for field bar *)
}
```

*(** The comment for class my_class *)*

```fortran
class my_class =
    object
        (** A comment to describe inheritance from cl *)
        inherit cl
```

*(** The comment for the instance variable tutu *)*

```fortran
val mutable tutu = "tutu"
```

*(** The comment for toto *)*

```fortran
val toto = 1
val titi = "titi"
```

*(** Comment for method toto *)*

```fortran
method toto = tutu ^ "!"
```

*(** Comment for method m *)*

```fortran
method m (f : float) = 1
end
```

*(** The comment for class type my_class_type *)*

```fortran
class type my_class_type =
    object
        (** The comment for the instance variable x. *)
        val mutable x : int
        (** The comment for method m. *)
        method m : int -> int
end
```

*(** The comment for module Foo *)*

```python
module Foo =
    struct
        (** The comment for x *)
        let x = 0
        (** A special comment in the class, but not associated to any element. *)
        end
```

*(** The comment for module type my_module_type. *)*

```python
module type my_module_type =
    sig
        (* Comment for value x. *)
        val x : int
        (* ... *)
    end
```
### 19.2.4 The Stop special comment

The special comment (`**/**`) tells OCamldoc to discard elements placed after this comment, up to the end of the current class, class type, module or module type, or up to the next stop comment. For instance:

```python
class type foo =
object
    (** comment for method m *)
    method m : string
```

(**/**)

(** This method won't appear in the documentation *)
    method bar : int

end

(** This value appears in the documentation, since the Stop special comment in the class does not affect the parent module of the class.*)

val foo : string

(**/**)

(** The value bar does not appear in the documentation.*)

val bar : string

(**/**)

(** The type t appears since in the documentation since the previous stop comment toggled off the "no documentation mode". *)

type t = string

The `-no-stop` option to `ocamldoc` causes the Stop special comments to be ignored.

### 19.2.5 Syntax of documentation comments

The inside of documentation comments (`**...`) consists of free-form text with optional formatting annotations, followed by optional *tags* giving more specific information about parameters, version, authors, ... The tags are distinguished by a leading @ character. Thus, a documentation comment has the following shape:

(** The comment begins with a description, which is text formatted according to the rules described in the next section.
The description continues until the first non-escaped '@' character.
@author Mr Smith
@param x description for parameter x
*)

Some elements support only a subset of all @-tags. Tags that are not relevant to the documented element are simply ignored. For instance, all tags are ignored when documenting type constructors,
Chapter 19

The documentation generator
(ocamldoc)

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

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

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

19.1 Usage

19.1.1 Invocation

OCamldoc is invoked via the command ocamldoc , as follows:

ocamldoc options sourcefiles

Options for choosing the output format

The following options determine the format for the generated documentation.

-html

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

-latex

Generate documentation in LATEX default format. The generated LATEX document is saved in
record fields, and class inheritance clauses. Similarly, a `@param` tag on a class instance variable is ignored.

At last, (**) is the empty documentation comment.

### 19.2.6 Text formatting

Here is the BNF grammar for the simple markup language used to format text descriptions.
file ocamldoc.out, or in the file specified with the -o option. The document uses the style file ocamldoc.sty. This file is generated when using the -latex option, if it does not already exist. You can change this file to customize the style of your LATEX documentation.

-texi

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

-man

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

-dot

Generate a dependency graph for the toplevel modules, in a format suitable for displaying and processing by dot. The dot tool is available from https://graphviz.org/. The textual representation of the graph is written to the file ocamldoc.out, or to the file specified with the -o option. Use dot ocamldoc.out to display it.

-g file.cm[o,a,xs]

Dynamically load the given file, which defines a custom documentation generator. See section 19.4.1. This option is supported by the ocamldoc command (to load .cmo and .cma files) and by its native-code version ocamldoc.opt (to load .cmxs files). If the given file is a simple one and does not exist in the current directory, then ocamldoc looks for it in the custom generators default directory, and in the directories specified with optional -i options.

-customdir

Display the custom generators default directory.

-i directory

Add the given directory to the path where to look for custom generators.

## General options

-d dir

Generate files in directory *dir*, rather than the current directory.

-dump file

Dump collected information into *file*. This information can be read with the -load option in a subsequent invocation of ocamldoc.

-hide *modules*

Hide the given complete module names in the generated documentation. *modules* is a list of complete module names separated by ',' without blanks. For instance: Stdlib,M2.M3.

-inv-merge-ml-mli

Reverse the precedence of implementations and interfaces when merging. All elements in implementation files are kept, and the -m option indicates which parts of the comments in interface files are merged with the comments in implementation files.
text ::= {text-element}⁺

inline-text ::= {inline-text-element}⁺

text-element ::=

| inline-text-element

| blank-line force a new line.

inline-text-element ::=

| { {0...9}⁺ inline-text } format text as a section header; the integer following { indicates the sectioning level.

| { {0...9}⁺ : label inline-text } same, but also associate the name *label* to the current point. This point can be referenced by its fully-qualified label in a `{!` command, just like any other element.

| {b inline-text } set text in bold.

| {i inline-text } set text in italic.

| {e inline-text } emphasize text.

| {C inline-text } center text.

| {L inline-text } left align text.

| {R inline-text } right align text.

| {ul list } build a list.

| {ol list } build an enumerated list.

| {{: string } inline-text } put a link to the given address (given as *string*) on the given text.

| [ string ] set the given *string* in source code style.

| {[ string ]} set the given *string* in preformatted source code style.

| {v string v} set the given *string* in verbatim style.

| `% string %` target-specific content (LaTeX code by default, see details in 19.2.10)

| `{! string }` insert a cross-reference to an element (see section 19.2.8 for the syntax of cross-references).

| {{! string } inline-text } insert a cross-reference with the given text.

| `{!modules: string string... }` insert an index table for the given module names. Used in HTML only.

| `{!indexlist}` insert a table of links to the various indexes (types, values, modules, ...). Used in HTML only.

| {^ inline-text } set text in superscript.

| {- inline-text } set text in subscript.

| escaped-string typeset the given string as is; special characters (`{'`, `}'`, `['`, `]`, and `@`) must be escaped by a `\`
-keep-code

Always keep the source code for values, methods and instance variables, when available.

-load file

Load information from *file*, which has been produced by `ocamldoc -dump`. Several `-load` options can be given.

-m *flags*

Specify merge options between interfaces and implementations. (see section 19.1.2 for details).
*flags* can be one or several of the following characters:

d merge description

a merge @author

v merge @version

l merge @see

s merge @since

b merge @before

o merge @deprecated

p merge @param

e merge @raise

r merge @return

A merge everything

-no-custom-tags

Do not allow custom @-tags (see section 19.2.12).

-no-stop

Keep elements placed after/between the (\*\*/\*\*) special comment(s) (see section 19.2).

-o *file*

Output the generated documentation to *file* instead of `ocamldoc.out`. This option is meaningful only in conjunction with the `-latex`, `-texi`, or `-dot` options.

-pp *command*

Pipe sources through preprocessor *command*.

-impl *filename*

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

-intf *filename*

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

-text *filename*

Process the file *filename* as a text file, even if its extension is not `.txt`.

-sort

Sort the list of top-level modules before generating the documentation.
### 19.2.7 List formatting

$$ \texttt{list ::=} \\ \quad | \{\{- inline-text \}\}^{+} \\ \quad | \{\{li inline-text \}\}^{+} $$

A shortcut syntax exists for lists and enumerated lists:

(** Here is a {b list}

- item 1

- item 2

- item 3

The list is ended by the blank line.*)

is equivalent to:

(** Here is a {b list}

- {ul {- item 1}

- {- item 2}

- {- item 3}}

The list is ended by the blank line.*)

The same shortcut is available for enumerated lists, using '+' instead of '-'. Note that only one list can be defined by this shortcut in nested lists.

### 19.2.8 Cross-reference formatting

Cross-references are fully qualified element names, as in the example `{!Foo.Bar.t}`. This is an ambiguous reference as it may designate a type name, a value name, a class name, etc. It is possible to make explicit the intended syntactic class, using `{!type:Foo.Bar.t}` to designate a type, and `{!val:Foo.Bar.t}` a value of the same name.

The list of possible syntactic class is as follows:

<table><thead><tr><th>tag</th><th>syntactic class</th></tr></thead><tbody><tr><td>module:</td><td>module</td></tr><tr><td>modtype:</td><td>module type</td></tr><tr><td>class:</td><td>class</td></tr><tr><td>classtype:</td><td>class type</td></tr><tr><td>val:</td><td>value</td></tr><tr><td>type:</td><td>type</td></tr><tr><td>exception:</td><td>exception</td></tr><tr><td>attribute:</td><td>attribute</td></tr><tr><td>method:</td><td>class method</td></tr><tr><td>section:</td><td>ocamldoc section</td></tr><tr><td>const:</td><td>variant constructor</td></tr><tr><td>recfield:</td><td>record field</td></tr></tbody></table>