text
stringlengths 10
16.2k
|
|---|
# OCaml - The runtime system (ocamlrun)
Source: https://ocaml.org/manual/5.2/runtime.html
☰
- [Batch compilation (ocamlc)](comp.html)
- [The toplevel system or REPL (ocaml)](toplevel.html)
- [The runtime system (ocamlrun)](runtime.html)
- [Native-code compilation (ocamlopt)](native.html)
- [Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc.html)
- [Dependency generator (ocamldep)](depend.html)
- [The documentation generator (ocamldoc)](ocamldoc.html)
- [The debugger (ocamldebug)](debugger.html)
- [Profiling (ocamlprof)](profil.html)
- [Interfacing C with OCaml](intfc.html)
- [Optimisation with Flambda](flambda.html)
- [Fuzzing with afl-fuzz](afl-fuzz.html)
- [Runtime tracing with runtime events](runtime-tracing.html)
- [The “Tail Modulo Constructor” program transformation](tail_mod_cons.html)
- [Runtime detection of data races with ThreadSanitizer](tsan.html)
|
# Chapter 15 The runtime system (ocamlrun)
The ocamlrun command executes bytecode files produced by the linking phase of the ocamlc command.
|
## 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 arg1 ... argn
The first non-option argument is taken to be the name of the file containing the executable bytecode. (That file is searched in the executable path as well as in the current directory.) The remaining arguments are passed to the OCaml program, in the string array Sys.argv. Element 0 of this array is the name of the bytecode executable file; elements 1 to n are the remaining arguments arg<sub>1</sub> to arg<sub>n</sub>.
As mentioned in chapter [13](comp.html#c%3Acamlc), the bytecode executable files produced by the ocamlc command are self-executable, and manage to launch the ocamlrun command on themselves automatically. That is, assuming a.out is a bytecode executable file,
a.out arg1 ... argn
works exactly as
ocamlrun a.out arg1 ... argn
Notice that it is not possible to pass options to ocamlrun when invoking a.out directly.
> Windows: Under several versions of Windows, bytecode executable files are self-executable only if their name ends in .exe. It is recommended to always give .exe names to bytecode executables, e.g. compile with ocamlc -o myprog.exe ... rather than ocamlc -o myprog ....
|
## 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](#s%3Aocamlrun-dllpath)).
-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](#s%3Aocamlrun-dllpath)).
|
## 2 Options
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](#s%3Aocamlrun-dllpath)). 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 specification is an option letter followed by an = sign, a decimal number (or an hexadecimal number prefixed by 0x), and an optional multiplier. The options are documented below; the options a, i, l, m, M, n, o, O, s, v, w correspond to the fields of the control record documented in [Module Gc](../5.2/api/Gc.html).
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.
|
## 2 Options
c
(cleanup_on_exit) Shut the runtime down gracefully on exit (see caml_shutdown in section [22.7.5](intfc.html#ss%3Ac-embedded-code)). The option also enables pooling (as in caml_startup_pooled). This mode can be used to detect leaks with a third-party memory debugger.
e
(runtime_events_log_wsize) Size of the per-domain runtime events ring buffers in log powers of two words. Defaults to 16, giving 64k word or 512kb buffers on 64-bit systems.
l
(stack_limit) The limit (in words) of the stack size. This is only relevant to the byte-code runtime, as the native code runtime uses the operating system’s stack.
m
(custom_minor_ratio) Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Default: 100. Note: this only applies to values allocated with caml_alloc_custom_mem.
M
(custom_major_ratio) Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values (e.g. bigarrays) located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. Default: 44. Note: this only applies to values allocated with caml_alloc_custom_mem.
|
## 2 Options
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<sup>10</sup>, 2<sup>20</sup>, and 2<sup>30</sup> respectively.
o
(space_overhead) The major GC speed setting. See the Gc module documentation for details.
p
(parser trace) Turn on debugging support for ocamlyacc-generated parsers. When this option is on, the pushdown automaton that executes the parsers prints a trace of its actions. This option takes no argument.
R
(randomize) Turn on randomization of all hash tables by default (see [Module Hashtbl](../5.2/api/Hashtbl.html)). 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
|
## 2 Options
256 (= 0x100)
Startup messages (loading the bytecode executable file, resolving shared libraries).
512 (= 0x200)
Computation of compaction-triggering condition.
1024 (= 0x400)
Output GC statistics at program exit.
2048 (= 0x800)
GC debugging messages.
4096 (= 0x1000)
Address space reservation changes.
V
(verify_heap) runs an integrity check on the heap just after the completion of a major GC cycle
W
Print runtime warnings to stderr (such as Channel opened on file dies without being closed, unflushed data, etc.)
If the option letter is not recognized, the whole parameter is ignored; if the equal sign or the number is missing, the value is taken as 1; if the multiplier is not recognized, it is ignored.
For example, on a 32-bit machine, under bash the command
export OCAMLRUNPARAM='b,s=256k,v=0x015'
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.
|
## 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](intfc.html#ss%3Adynlink-c-code)), 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.
|
## 3 Dynamic loading of shared libraries
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.
|
## 4 Common errors
This section describes and explains the most frequently encountered error messages.
filename: no such file or directory
If filename is the name of a self-executable bytecode file, this means that either that file does not exist, or that it failed to run the ocamlrun bytecode interpreter on itself. The second possibility indicates that OCaml has not been properly installed on your system.
Cannot exec ocamlrun
(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.
|
## 4 Common errors
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](debugger.html#c%3Adebugger)), 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, …
|
## 4 Common errors
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.
------------------------------------------------------------------------
[« The toplevel system or REPL (ocaml)](toplevel.html)[Native-code compilation (ocamlopt) »](native.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Native-code compilation (ocamlopt)
Source: https://ocaml.org/manual/5.2/native.html
☰
- [Batch compilation (ocamlc)](comp.html)
- [The toplevel system or REPL (ocaml)](toplevel.html)
- [The runtime system (ocamlrun)](runtime.html)
- [Native-code compilation (ocamlopt)](native.html)
- [Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc.html)
- [Dependency generator (ocamldep)](depend.html)
- [The documentation generator (ocamldoc)](ocamldoc.html)
- [The debugger (ocamldebug)](debugger.html)
- [Profiling (ocamlprof)](profil.html)
- [Interfacing C with OCaml](intfc.html)
- [Optimisation with Flambda](flambda.html)
- [Fuzzing with afl-fuzz](afl-fuzz.html)
- [Runtime tracing with runtime events](runtime-tracing.html)
- [The “Tail Modulo Constructor” program transformation](tail_mod_cons.html)
- [Runtime detection of data races with ThreadSanitizer](tsan.html)
|
# 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.
|
## 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](comp.html#c%3Acamlc)).
|
## 1 Overview of the compiler
- 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 build with ocamlopt -a (see the description of the -a option below). The object files contained in the library are linked as regular .cmx files (see above), in the order specified when the library was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in.
- Arguments ending in .c are passed to the C compiler, which generates a .o/.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.
|
## 1 Overview of the compiler
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.
|
## 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.
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.
|
## 2 Options
-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.
-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.
|
## 2 Options
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.
|
## 2 Options
-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](runtime.html#s%3Aocamlrun-options)).
-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.
|
## 2 Options
-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.
|
## 2 Options
-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).
-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.
|
## 2 Options
-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](modulealias.html#s%3Amodule-alias) 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.
|
## 2 Options
-noautolink
When linking .cmxalibraries, 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.
|
## 2 Options
-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.
|
## 2 Options
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](intfc.html#c%3Aintf-c), section [22.7.5](intfc.html#ss%3Ac-embedded-code). 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.
|
## 2 Options
-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.
|
## 2 Options
-ppx command
After parsing, pipe the abstract syntax tree through the preprocessor command. The module Ast_mapper, described in chapter [30](parsing.html#c%3Aparsinglib): [Ast_mapper](../5.2/api/compilerlibref/Ast_mapper.html) , 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.
|
## 2 Options
-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 chapter [30](parsing.html#c%3Aparsinglib) and [Compiler_libs](../5.2/api/compilerlibref/Compiler_libs.html) ).
|
## 2 Options
-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.
-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 unboxable (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\].
|
## 2 Options
-no-unboxed-types
When a type is unboxable 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.
|
## 2 Options
-w warning-list
Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it.
The warning-list argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following:
+num
Enable warning number num.
-num
Disable warning number num.
@num
Enable and mark as fatal warning number num.
+num1..num2
Enable warnings in the given range.
-num1..num2
Disable warnings in the given range.
@num1..num2
Enable and mark as fatal warnings in the given range.
+letter
Enable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
-letter
Disable the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
@letter
Enable and mark as fatal the set of warnings corresponding to letter. The letter may be uppercase or lowercase.
uppercase-letter
Enable the set of warnings corresponding to uppercase-letter.
lowercase-letter
Disable the set of warnings corresponding to lowercase-letter.
Alternatively, warning-list can specify a single warning using its mnemonic name (see below), as follows:
+name
Enable warning name.
-name
Disable warning name.
|
## 2 Options
@name
Enable and mark as fatal warning name.
Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning).
1 comment-start
Suspicious-looking start-of-comment mark.
2 comment-not-end
Suspicious-looking end-of-comment mark.
3
Deprecated synonym for the ’deprecated’ alert.
4 fragile-match
Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched.
5 ignored-partial-application
Partially applied function: expression whose result has function type and is ignored.
6 labels-omitted
Label omitted in function application.
7 method-override
Method overridden.
8 partial-match
Partial match: missing cases in pattern-matching.
9 missing-record-field-pattern
Missing fields in a record pattern.
10 non-unit-statement
Expression on the left-hand side of a sequence that doesn’t have type unit (and that is not a function, see warning number 5).
11 redundant-case
Redundant case in a pattern matching (unused match case).
12 redundant-subpat
Redundant sub-pattern in a pattern-matching.
13 instance-variable-override
Instance variable overridden.
14 illegal-backslash
Illegal backslash escape in a string constant.
15 implicit-public-methods
Private method made public implicitly.
16 unerasable-optional-argument
Unerasable optional argument.
17 undeclared-virtual-method
Undeclared virtual method.
18 not-principal
Non-principal type.
19 non-principal-labels
Type without principality.
|
## 2 Options
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
gnored: 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)
|
## 2 Options
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](comp.html#ss%3Awarn52))
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](comp.html#ss%3Awarn57))
Ambiguous or-pattern variables under guard. (since 4.03)
58 no-cmx-file
Missing cmx file. (since 4.03)
|
## 2 Options
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)
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.
|
## 2 Options
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.
-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 :\|; ,.
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.
|
## 3 Common errors
The error messages are almost identical to those of ocamlc. See section [13.4](comp.html#s%3Acomp-errors).
|
## 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](runtime.html#s%3Aocamlrun-options)), 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.
|
## 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 Flambda 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
|
## 5 Compatibility with the bytecode compiler
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.
------------------------------------------------------------------------
[« The runtime system (ocamlrun)](runtime.html)[Lexer and parser generators (ocamllex, ocamlyacc) »](lexyacc.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Lexer and parser generators (ocamllex, ocamlyacc)
Source: https://ocaml.org/manual/5.2/lexyacc.html
☰
- [Batch compilation (ocamlc)](comp.html)
- [The toplevel system or REPL (ocaml)](toplevel.html)
- [The runtime system (ocamlrun)](runtime.html)
- [Native-code compilation (ocamlopt)](native.html)
- [Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc.html)
- [Dependency generator (ocamldep)](depend.html)
- [The documentation generator (ocamldoc)](ocamldoc.html)
- [The debugger (ocamldebug)](debugger.html)
- [Profiling (ocamlprof)](profil.html)
- [Interfacing C with OCaml](intfc.html)
- [Optimisation with Flambda](flambda.html)
- [Fuzzing with afl-fuzz](afl-fuzz.html)
- [Runtime tracing with runtime events](runtime-tracing.html)
- [The “Tail Modulo Constructor” program transformation](tail_mod_cons.html)
- [Runtime detection of data races with ThreadSanitizer](tsan.html)
|
# Chapter 17 Lexer 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).
|
## 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.
Lexer buffers are an abstract data type implemented in the standard library module Lexing. The functions Lexing.from_channel, Lexing.from_string and Lexing.from_function create lexer buffers that read from an input channel, a character string, or any reading function, respectively. (See the description of module Lexing in chapter [29](stdlib.html#c%3Astdlib).)
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.)
|
### 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.
|
## 2 Syntax of lexer definitions
The format of lexer definitions is as follows:
{ header }
let ident = regexp …
[refill { refill-handler }]
rule entrypoint [arg1… argn] =
parse regexp { action }
| …
| regexp { action }
and entrypoint [arg1… argn] =
parse …
and …
{ trailer }
Comments are delimited by (\* and \*), as in OCaml. The parse keyword, can be replaced by the shortest keyword, with the semantic consequences explained below.
Refill handlers are a recent (optional) feature introduced in 4.02, documented below in subsection [17.2.7](#ss%3Arefill-handlers).
|
### 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.
|
### 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](lex.html#ident) = [regexp](#regexp). In regular expressions that follow this declaration, the identifier ident can be used as shorthand for regexp.
|
### 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 arg<sub>1</sub>… arg<sub>n</sub> 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.
|
### 2.4 Regular expressions
The regular expressions are in the style of lex, with a more OCaml-like syntax.
<table class="display dcenter"><colgroup><col style="width: 100%" /></colgroup><tbody><tr class="odd c009"><td class="dcell"><table class="c001 cellpading0"><tbody><tr class="odd"><td class="c008">regexp</td><td class="c005">::=</td><td class="c007">…</td></tr></tbody></table></td></tr></tbody></table>
' regular-char ∣ [escape-sequence](lex.html#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](lex.html#string-character) } "
A string constant, with the same syntax as OCaml string constants. Match the corresponding sequence of characters.
\[ character-set \]
Match any single character belonging to the given character set. Valid character sets are: single character constants ' c '; ranges of characters ' c<sub>1</sub> ' - ' c<sub>2</sub> ' (all characters between c<sub>1</sub> and c<sub>2</sub>, 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.
|
### 2.4 Regular expressions
[regexp](#regexp)<sub>1</sub> # [regexp](#regexp)<sub>2</sub>
(difference of character sets) Regular expressions [regexp](#regexp)<sub>1</sub> and [regexp](#regexp)<sub>2</sub> must be character sets defined with \[… \] (or a single character expression or underscore \_). Match the difference of the two specified character sets.
[regexp](#regexp) \*
(repetition) Match the concatenation of zero or more strings that match [regexp](#regexp).
[regexp](#regexp) +
(strict repetition) Match the concatenation of one or more strings that match [regexp](#regexp).
[regexp](#regexp) ?
(option) Match the empty string, or a string matching [regexp](#regexp).
[regexp](#regexp)<sub>1</sub> \| [regexp](#regexp)<sub>2</sub>
(alternative) Match any string that matches [regexp](#regexp)<sub>1</sub> or [regexp](#regexp)<sub>2</sub>. If both [regexp](#regexp)<sub>1</sub> and [regexp](#regexp)<sub>2</sub> are character sets, this constructions produces another character set, obtained by taking the union of [regexp](#regexp)<sub>1</sub> and [regexp](#regexp)<sub>2</sub>.
[regexp](#regexp)<sub>1</sub> [regexp](#regexp)<sub>2</sub>
(concatenation) Match the concatenation of two strings, the first matching [regexp](#regexp)<sub>1</sub>, the second matching [regexp](#regexp)<sub>2</sub>.
( [regexp](#regexp) )
Match the same strings as [regexp](#regexp).
[ident](lex.html#ident)
Reference the regular expression bound to [ident](lex.html#ident) by an earlier let [ident](lex.html#ident) = [regexp](#regexp) definition.
|
### 2.4 Regular expressions
[regexp](#regexp) as [ident](lex.html#ident)
Bind the substring matched by [regexp](#regexp) to identifier [ident](lex.html#ident).
Concerning the precedences of operators, # has the highest precedence, followed by \*, + and ?, then concatenation, then \| (alternation), then as.
|
### 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.
Lexing.lexeme lexbuf
Return the matched string.
Lexing.lexeme_char lexbuf n
Return the n<sup>th</sup> 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<sub>1</sub>… exp<sub>n</sub>\] 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.
|
### 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](#regexp) as [ident](lex.html#ident), the type of [ident](lex.html#ident) normally is string (or string option) except when [regexp](#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](lex.html#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](#regexp) as [ident](lex.html#ident) ) ? and of [regexp](#regexp)<sub>1</sub> \| ( [regexp](#regexp)<sub>2</sub> as [ident](lex.html#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.
|
### 2.6 Variables in regular expressions
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 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.
|
### 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:
{
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)
}
|
### 2.7 Refill handlers
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 }
| _
{ M.fail "unexpected character" }
{
end
}
|
### 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.
|
## 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. Lexer buffers are an abstract data type implemented in the standard library module Lexing. Tokens are values from the concrete type token, defined in the interface file grammar.mli produced by ocamlyacc.
|
## 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.
|
### 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.
|
### 4.2 Declarations
Declarations are given one per line. They all start with a `%` sign.
%token [constr](names.html#constr) … [constr](names.html#constr)
Declare the given symbols [constr](names.html#constr) … [constr](names.html#constr) as tokens (terminal symbols). These symbols are added as constant constructors for the token concrete type.
%token \< [typexpr](types.html#typexpr) \> [constr](names.html#constr) … [constr](names.html#constr)
Declare the given symbols [constr](names.html#constr) … [constr](names.html#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](types.html#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](types.html#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.
|
### 4.2 Declarations
%type \< [typexpr](types.html#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](types.html#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 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.
|
### 4.2 Declarations
- 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.
|
### 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).
|
### 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 Parsing.Parse_error exception.
In error recovery mode, the parser discards states from the stack until it reaches a place where the error token can be shifted. It then discards tokens from the input until it finds three successive tokens that can be accepted, and starts processing with the first of these. If no state can be uncovered where the error token can be shifted, then the parser aborts by raising the Parsing.Parse_error exception.
Refer to documentation on yacc for more details and guidance in how to use error recovery.
|
## 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](runtime.html#s%3Aocamlrun-options)). 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.
|
## 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 *)
|
## 6 A complete example
| ['\n' ] { EOL }
| ['0'-'9']+ as lxm { INT(int_of_string lxm) }
| '+' { PLUS }
| '-' { MINUS }
| '*' { TIMES }
| '/' { DIV }
| '(' { LPAREN }
| ')' { RPAREN }
| eof { raise Eof }
Here is the main program, that combines the parser with the lexer:
(* File calc.ml *)
let _ =
try
let lexbuf = Lexing.from_channel stdin in
while true do
let result = Parser.main Lexer.token lexbuf in
print_int result; print_newline(); flush stdout
done
with Lexer.Eof ->
exit 0
To compile everything, execute:
ocamllex lexer.mll # generates lexer.ml
ocamlyacc parser.mly # generates parser.ml and parser.mli
ocamlc -c parser.mli
ocamlc -c lexer.ml
ocamlc -c parser.ml
ocamlc -c calc.ml
ocamlc -o calc lexer.cmo parser.cmo calc.cmo
|
## 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)
[ "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.
|
## 7 Common errors
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](https://cambium.inria.fr/~fpottier/menhir/) parser generator is a better option if you want thread-safe parsers.
------------------------------------------------------------------------
[« Native-code compilation (ocamlopt)](native.html)[Dependency generator (ocamldep) »](depend.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - Dependency generator (ocamldep)
Source: https://ocaml.org/manual/5.2/depend.html
☰
- [Batch compilation (ocamlc)](comp.html)
- [The toplevel system or REPL (ocaml)](toplevel.html)
- [The runtime system (ocamlrun)](runtime.html)
- [Native-code compilation (ocamlopt)](native.html)
- [Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc.html)
- [Dependency generator (ocamldep)](depend.html)
- [The documentation generator (ocamldoc)](ocamldoc.html)
- [The debugger (ocamldebug)](debugger.html)
- [Profiling (ocamlprof)](profil.html)
- [Interfacing C with OCaml](intfc.html)
- [Optimisation with Flambda](flambda.html)
- [Fuzzing with afl-fuzz](afl-fuzz.html)
- [Runtime tracing with runtime events](runtime-tracing.html)
- [The “Tail Modulo Constructor” program transformation](tail_mod_cons.html)
- [Runtime detection of data races with ThreadSanitizer](tsan.html)
|
# 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.
|
## 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 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.
|
## 1 Options
-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.
-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.
|
## 1 Options
-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.
|
## 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
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 $<
|
## 2 A typical Makefile
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.
------------------------------------------------------------------------
[« Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc.html)[The documentation generator (ocamldoc) »](ocamldoc.html)
Copyright © 2024 Institut National de Recherche en Informatique et en Automatique
------------------------------------------------------------------------
|
# OCaml - The documentation generator (ocamldoc)
Source: https://ocaml.org/manual/5.2/ocamldoc.html
☰
- [Batch compilation (ocamlc)](comp.html)
- [The toplevel system or REPL (ocaml)](toplevel.html)
- [The runtime system (ocamlrun)](runtime.html)
- [Native-code compilation (ocamlopt)](native.html)
- [Lexer and parser generators (ocamllex, ocamlyacc)](lexyacc.html)
- [Dependency generator (ocamldep)](depend.html)
- [The documentation generator (ocamldoc)](ocamldoc.html)
- [The debugger (ocamldebug)](debugger.html)
- [Profiling (ocamlprof)](profil.html)
- [Interfacing C with OCaml](intfc.html)
- [Optimisation with Flambda](flambda.html)
- [Fuzzing with afl-fuzz](afl-fuzz.html)
- [Runtime tracing with runtime events](runtime-tracing.html)
- [The “Tail Modulo Constructor” program transformation](tail_mod_cons.html)
- [Runtime detection of data races with ThreadSanitizer](tsan.html)
|
# 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](#s%3Aocamldoc-comments).
OCamldoc can produce documentation in various formats: HTML, L<sup>A</sup>T<sub>E</sub>X, TeXinfo, Unix man pages, and dot dependency graphs. Moreover, users can add their own custom generators, as explained in section [19.3](#s%3Aocamldoc-custom-generators).
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.
|
## 1 Usage
|
### 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 L<sup>A</sup>T<sub>E</sub>X default format. The generated L<sup>A</sup>T<sub>E</sub>X document is saved in file ocamldoc.out, or in the file specified with the -o option. The document uses the style file ocamldoc.sty. This file is generated when using the -latex option, if it does not already exist. You can change this file to customize the style of your L<sup>A</sup>T<sub>E</sub>X documentation.
-texi
Generate documentation in TeXinfo default format. The generated L<sup>A</sup>T<sub>E</sub>X 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.
|
### 1.1 Invocation
-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/](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](#ss%3Aocamldoc-compilation-and-usage). 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.
-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](#ss%3Aocamldoc-merge) 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.5](#ss%3Aocamldoc-tags)).
-no-stop
Keep elements placed after/between the (\*\*/\*\*) special comment(s) (see section [19.2](#s%3Aocamldoc-comments)).
|
### 1.1 Invocation
-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.
-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, L<sup>A</sup>T<sub>E</sub>X 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).
-H directory
Like -I, but the -H directories are searched last and the program may not directly refer to the modules added to the search path this way.
-nolabels
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).
-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 L<sup>A</sup>T<sub>E</sub>X 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 L<sup>A</sup>T<sub>E</sub>X 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, L<sup>A</sup>T<sub>E</sub>X will complain about multiply defined labels.
-latextitle n,style
Associate style number n to the given L<sup>A</sup>T<sub>E</sub>X sectioning command style, e.g. section or subsection. (L<sup>A</sup>T<sub>E</sub>X only.) This is useful when including the generated document in another L<sup>A</sup>T<sub>E</sub>X document, at a given sectioning level. The default association is 1 for section, 2 for subsection, 3 for subsubsection, 4 for paragraph and 5 for subparagraph.
-noheader
Suppress header in generated documentation.
-notoc
Do not generate a table of contents.
-notrailer
Suppress trailer in generated documentation.
-sepfiles
Generate one .tex file per toplevel module, instead of the global ocamldoc.out file.
|
#### Options for generating TeXinfo files
The following options apply in conjunction with the -texi option:
-esc8
Escape accented characters in Info files.
-info-entry
Specify Info directory entry.
-info-section
Specify section of Info directory.
-noheader
Suppress header in generated documentation.
-noindex
Do not build index for Info files.
-notrailer
Suppress trailer in generated documentation.
|
#### Options for generating dot graphs
The following options apply in conjunction with the -dot option:
-dot-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’.
|
### 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.
|
### 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:
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.
|
## 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.
|
### 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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.