text
stringlengths
10
16.2k
# Chapter 10 Memory model: The hard bits This chapter describes the details of OCaml relaxed memory model. The relaxed memory model describes what values an OCaml program is allowed to witness when reading a memory location. If you are interested in high-level parallel programming in OCaml, please have a look at the parallel programming chapter [9](parallelism.html#c%3Aparallelism). This chapter is aimed at experts who would like to understand the details of the OCaml memory model from a practitioner’s perspective. For a formal definition of the OCaml memory model, its guarantees and the compilation to hardware memory models, please have a look at the PLDI 2018 paper on [Bounding Data Races in Space and Time](https://doi.org/10.1145/3192366.3192421). The memory model presented in this chapter is an extension of the one presented in the PLDI 2018 paper. This chapter also covers some pragmatic aspects of the memory model that are not covered in the paper.
## 1 Why weakly consistent memory? The simplest memory model that we could give to our programs is sequential consistency. Under sequential consistency, the values observed by the program can be explained through some interleaving of the operations from different domains in the program. For example, consider the following program with two domains d1 and d2 executing in parallel: let d1 a b = let r1 = !a \* 2 in let r2 = !b in let r3 = !a \* 2 in (r1, r2, r3) let d2 b = b := 0 let main () = let a = ref 1 in let b = ref 1 in let h = Domain.spawn (fun \_ -> let r1, r2, r3 = d1 a b in Printf.printf "r1 = %d, r2 = %d, r3 = %d\\n" r1 r2 r3) in d2 b; Domain.join h The reference cells a and b are initially 1. The user may observe r1 = 2, r2 = 0, r3 = 2 if the write to b in d2 occurred before the read of b in d1. Here, the observed behaviour can be explained in terms of interleaving of the operations from different domains. Let us now assume that a and b are aliases of each other. let d1 a b = let r1 = !a \* 2 in let r2 = !b in let r3 = !a \* 2 in (r1, r2, r3) let d2 b = b := 0 let main () = let ab = ref 1 in let h = Domain.spawn (fun \_ -> let r1, r2, r3 = d1 ab ab in assert (not (r1 = 2 && r2 = 0 && r3 = 2))) in d2 ab; Domain.join h In the above program, the variables ab, a and b refer to the same reference cell. One would expect that the assertion in the main function will never fail. The reasoning is that if r2 is 0, then the write in d2 occurred before the read of b in d1. Given that a and b are aliases, the second read of a in d1 should also return 0.
### 1.1 Compiler optimisations Surprisingly, this assertion may fail in OCaml due to compiler optimisations. The OCaml compiler observes the common sub-expression !a \* 2 in d1 and optimises the program to: let d1 a b = let r1 = !a \* 2 in let r2 = !b in let r3 = r1 in (\* CSE: !a \* 2 ==> r1 \*) (r1, r2, r3) let d2 b = b := 0 let main () = let ab = ref 1 in let h = Domain.spawn (fun \_ -> let r1, r2, r3 = d1 ab ab in assert (not (r1 = 2 && r2 = 0 && r3 = 2))) in d2 ab; Domain.join h This optimisation is known as the common sub-expression elimination (CSE). Such optimisations are valid and necessary for good performance, and do not change the sequential meaning of the program. However, CSE breaks sequential reasoning. In the optimized program above, even if the write to b in d2 occurs between the first and the second reads in d1, the program will observe the value 2 for r3, causing the assertion to fail. The observed behaviour cannot be explained by interleaving of operations from different domains in the source program. Thus, CSE optimization is said to be invalid under sequential consistency. One way to explain the observed behaviour is as if the operations performed on a domain were reordered. For example, if the second and the third reads from d1 were reordered, let d1 a b = let r1 = !a \* 2 in let r3 = !a \* 2 in let r2 = !b in (r1, r2, r3) then we can explain the observed behaviour (2,0,2) returned by d1.
### 1.2 Hardware optimisations The other source of reordering is by the hardware. Modern hardware architectures have complex cache hierarchies with multiple levels of cache. While cache coherence ensures that reads and writes to a single memory location respect sequential consistency, the guarantees on programs that operate on different memory locations are much weaker. Consider the following program: let a = ref 0 and b = ref 0 let d1 () = a := 1; !b let d2 () = b := 1; !a let main () = let h = Domain.spawn d2 in let r1 = d1 () in let r2 = Domain.join h in assert (not (r1 = 0 && r2 = 0)) Under sequential consistency, we would never expect the assertion to fail. However, even on x86, which offers much stronger guarantees than ARM, the writes performed at a CPU core are not immediately published to all of the other cores. Since a and b are different memory locations, the reads of a and b may both witness the initial values, leading to the assertion failure. This behaviour can be explained if a load is allowed to be reordered before a preceding store to a different memory location. This reordering can happen due to the presence of in-core store-buffers on modern processors. Each core effectively has a FIFO buffer of pending writes to avoid the need to block while a write completes. The writes to a and b may be in the store-buffers of cores c1 and c2 running the domains d1 and d2, respectively. The reads of b and a running on the cores c1 and c2, respectively, will not see the writes if the writes have not propagated from the buffers to the main memory.
## 2 Data race freedom implies sequential consistency The aim of the OCaml relaxed memory model is to precisely describe which orders are preserved by the OCaml program. The compiler and the hardware are free to optimize the program as long as they respect the ordering guarantees of the memory model. While programming directly under the relaxed memory model is difficult, the memory model also describes the conditions under which a program will only exhibit sequentially consistent behaviours. This guarantee is known as *data race freedom implies sequential consistency* (DRF-SC). In this section, we shall describe this guarantee. In order to do this, we first need a number of definitions.
### 2.1 Memory locations OCaml classifies memory locations into *atomic* and *non-atomic* locations. Reference cells, array fields and mutable record fields are non-atomic memory locations. Immutable objects are non-atomic locations with an initialising write but no further updates. Atomic memory locations are those that are created using the [Atomic](../5.2/api/Atomic.html) module.
### 2.2 Happens-before relation Let us imagine that the OCaml programs are executed by an abstract machine that executes one action at a time, arbitrarily picking one of the available domains at each step. We classify actions into two: *inter-domain* and *intra-domain*. An inter-domain action is one which can be observed and be influenced by actions on other domains. There are several inter-domain actions: - Reads and writes of atomic and non-atomic locations. - Spawn and join of domains. - Operations on mutexes. On the other hand, intra-domain actions can neither be observed nor influence the execution of other domains. Examples include evaluating an arithmetic expression, calling a function, etc. The memory model specification ignores such intra-domain actions. In the sequel, we use the term action to indicate inter-domain actions. A totally ordered list of actions executed by the abstract machine is called an *execution trace*. There might be several possible execution traces for a given program due to non-determinism. For a given execution trace, we define an irreflexive, transitive *happens-before relation* that captures the causality between actions in the OCaml program. The happens-before relation is defined as the smallest transitive relation satisfying the following properties: - We define the order in which a domain executes its actions as the *program order*. If an action x precedes another action y in program order, then x precedes y in happens-before order.
### 2.2 Happens-before relation - If x is a write to an atomic location and y is a subsequent read or write to that memory location in the execution trace, then x precedes y in happens-before order. For atomic locations, compare_and_set, fetch_and_add, exchange, incr and decr are considered to perform both a read and a write. - If x is Domain.spawn f and y is the first action in the newly spawned domain executing f, then x precedes y in happens-before order. - If x is the last action in a domain d and y is Domain.join d, then x precedes y in happens-before order. - If x is an unlock operation on a mutex, and y is any subsequent operation on the mutex in the execution trace, then x precedes y in happens-before order.
### 2.3 Data race In a given trace, two actions are said to be *conflicting* if they access the same non-atomic location, at least one is a write and neither is an initialising write to that location. We say that a program has a *data race* if there exists some execution trace of the program with two conflicting actions and there does not exist a happens-before relationship between the conflicting accesses. A program without data races is said to be *correctly synchronised*.
### 2.4 DRF-SC DRF-SC guarantee: A program without data races will only exhibit sequentially consistent behaviours. DRF-SC is a strong guarantee for the programmers. Programmers can use *sequential reasoning* i.e., reasoning by executing one inter-domain action after the other, to identify whether their program has a data race. In particular, they do not need to reason about reorderings described in section ‍[10.1](#s%3Awhy_relaxed_memory) in order to determine whether their program has a data race. Once the determination that a particular program is data race free is made, they do not need to worry about reorderings in their code.
## 3 Reasoning with DRF-SC In this section, we will look at examples of using DRF-SC for program reasoning. In this section, we will use the functions with names dN to represent domains executing in parallel with other domains. That is, we assume that there is a main function that runs the dN functions in parallel as follows: let main () = let h1 = Domain.spawn d1 in let h2 = Domain.spawn d2 in ... ignore @@ Domain.join h1; ignore @@ Domain.join h2 Here is a simple example with a data race: (\* Has data race \*) let r = ref 0 let d1 () = r := 1 let d2 () = !r r is a non-atomic reference. The two domains race to access the reference, and d1 is a write. Since there is no happens-before relationship between the conflicting accesses, there is a data race. Both of the programs that we had seen in the section ‍[10.1](#s%3Awhy_relaxed_memory) have data races. It is no surprise that they exhibit non sequentially consistent behaviours. Accessing disjoint array indices and fields of a record in parallel is not a data race. For example, (\* No data race \*) let a = \[\| 0; 1 \|\] let d1 () = a.(0) \<- 42 let d2 () = a.(1) \<- 42 (\* No data race \*) type t = { mutable a : int; mutable b : int } let r = {a = 0; b = 1} let d1 () = r.a \<- 42 let d2 () = r.b \<- 42 do not have data races. Races on atomic locations do not lead to a data race. (\* No data race \*) let r = Atomic.make 0 let d1 () = Atomic.set r 1 let d2 () = Atomic.get r
#### Message-passing Atomic variables may be used for implementing non-blocking communication between domains. (\* No data race \*) let msg = ref 0 let flag = Atomic.make false let d1 () = msg := 42; (\* a \*) Atomic.set flag true (\* b \*) let d2 () = if Atomic.get flag (\* c \*) then !msg (\* d \*) else 0 Observe that the actions a and d write and read from the same non-atomic location msg, respectively, and hence are conflicting. We need to establish that a and d have a happens-before relationship in order to show that this program does not have a data race. The action a precedes b in program order, and hence, a happens-before b. Similarly, c happens-before d. If d2 observes the atomic variable flag to be true, then b precedes c in happens-before order. Since happens-before is transitive, the conflicting actions a and d are in happens-before order. If d2 observes the flag to be false, then the read of msg is not done. Hence, there is no conflicting access in this execution trace. Hence, the program does not have a data race. The following modified version of the message passing program does have a data race. (\* Has data race \*) let msg = ref 0 let flag = Atomic.make false let d1 () = msg := 42; (\* a \*) Atomic.set flag true (\* b \*) let d2 () = ignore (Atomic.get flag); (\* c \*) !msg (\* d \*) The domain d2 now unconditionally reads the non-atomic reference msg. Consider the execution trace: Atomic.get flag; (* c *) !msg; (* d *) msg := 42; (* a *) Atomic.set flag true (* b *)
## 3 Reasoning with DRF-SC In this trace, d and a are conflicting operations. But there is no happens-before relationship between them. Hence, this program has a data race.
## 4 Local data race freedom The OCaml memory model offers strong guarantees even for programs with data races. It offers what is known as *local data race freedom sequential consistency (LDRF-SC)* guarantee. A formal definition of this property is beyond the scope of this manual chapter. Interested readers are encouraged to read the PLDI 2018 paper on [Bounding Data Races in Space and Time](https://doi.org/10.1145/3192366.3192421). Informally, LDRF-SC says that the data race free parts of the program remain sequentially consistent. That is, even if the program has data races, those parts of the program that are disjoint from the parts with data races are amenable to sequential reasoning. Consider the following snippet: let snippet () = let c = ref 0 in c := 42; let a = !c in (a, c) Observe that c is a newly allocated reference. Can the read of c return a value which is not 42? That is, can a ever be not 42? Surprisingly, in the C++ and Java memory models, the answer is yes. With the C++ memory model, if the program has a data race, even in unrelated parts, then the semantics is undefined. If this snippet were linked with a library that had a data race, then, under the C++ memory model, the read may return any value. Since data races on unrelated locations can affect program behaviour, we say that C++ memory model is not bounded in space.
## 4 Local data race freedom Unlike C++, Java memory model is bounded in space. But Java memory model is not bounded in time; data races in the future will affect the past behaviour. For example, consider the translation of this example to Java. We assume a prior definition of Class c {int x;} and a shared *non-volatile* variable C g. Now the snippet may be part of a larger program with parallel threads: (* Thread 1 *) C c = new C(); c.x = 42; a = c.x; g = c; (* Thread 2 *) g.x = 7; The read of c.x and the write of g in the first thread are done on separate memory locations. Hence, the Java memory model allows them to be reordered. As a result, the write in the second thread may occur before the read of c.x, and hence, c.x returns 7. The OCaml equivalent of the Java code above is: let g = ref None let snippet () = let c = ref 0 in c := 42; let a = !c in (a, c) let d1 () = let (a,c) = snippet () in g := Some c; a let d2 () = match !g with \| None -> () \| Some c -> c := 7 Observe that there is a data race on both g and c. Consider only the first three instructions in snippet: let c = ref 0 in c := 42; let a = !c in ... The OCaml memory model is bounded both in space and time. The only memory location here is c. Reasoning only about this snippet, there is neither the data race in space (the race on g) nor in time (the future race on c). Hence, the snippet will have sequentially consistent behaviour, and the value returned by !c will be 42.
## 4 Local data race freedom The OCaml memory model guarantees that even for programs with data races, memory safety is preserved. While programs with data races may observe non-sequentially consistent behaviours, they will not crash.
## 5 An operational view of the memory model In this section, we describe the semantics of the OCaml memory model. A formal definition of the operational view of the memory model is presented in section 3 of the PLDI 2018 paper on [Bounding Data Races in Space and Time](https://doi.org/10.1145/3192366.3192421). This section presents an informal description of the memory model with the help of an example. Given an OCaml program, which may possibly contain data races, the operational semantics tells you the values that may be observed by the read of a memory location. For simplicity, we restrict the intra-thread actions to just the accesses to atomic and non-atomic locations, ignoring domain spawn and join operations, and the operations on mutexes. We describe the semantics of the OCaml memory model in a straightforward small-step operational manner. That is, the semantics is described by an abstract machine that executes one action at a time, arbitrarily picking one of the available domains at each step. This is similar to the abstract machine that we had used to describe the happens-before relationship in section ‍[10.2.2](#s%3Ahappens_before).
### 5.1 Non-atomic locations In the semantics, we model non-atomic locations as finite maps from timestamps t to values v. We take timestamps to be rational numbers. The timestamps are totally ordered but dense; there is a timestamp between any two others. For example, a: [t1 -> 1; t2 -> 2] b: [t3 -> 3; t4 -> 4; t5 -> 5] c: [t6 -> 5; t7 -> 6; t8 -> 7] represents three non-atomic locations a, b and c and their histories. The location a has two writes at timestamps t1 and t2 with values 1 and 2, respectively. When we write a: \[t1 -> 1; t2 -> 2\], we assume that t1 \< t2. We assume that the locations are initialised with a history that has a single entry at timestamp 0 that maps to the initial value.
### 5.2 Domains Each domain is equipped with a *frontier*, which is a map from non-atomic locations to timestamps. Intuitively, each domain’s frontier records, for each non-atomic location, the latest write known to the thread. More recent writes may have occurred, but are not guaranteed to be visible. For example, d1: [a -> t1; b -> t3; c -> t7] d2: [a -> t1; b -> t4; c -> t7] represents two domains d1 and d2 and their frontiers.
### 5.3 Non-atomic accesses Let us now define the semantics of non-atomic reads and writes. Suppose domain d1 performs the read of b. For non-atomic reads, the domains may read an arbitrary element of the history for that location, as long as it is not older than the timestamp in the domains’s frontier. In this case, since d1 frontier at b is at t3, the read may return the value 3, 4 or 5. A non-atomic read does not change the frontier of the current domain. Suppose domain d2 writes the value 10 to c (c := 10). We pick a new timestamp t9 for this write such that it is later than d2’s frontier at c. Note a subtlety here: this new timestamp might not be later than everything else in the history, but merely later than any other write known to the writing domain. Hence, t9 may be inserted in c’s history either (a) between t7 and t8 or (b) after t8. Let us pick the former option for our discussion. Since the new write appears after all the writes known by the domain d2 to the location c, d2’s frontier at c is also updated. The new state of the abstract machine is: (* Non-atomic locations *) a: [t1 -> 1; t2 -> 2] b: [t3 -> 3; t4 -> 4; t5 -> 5] c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7] (* new write at t9 *) (* Domains *) d1: [a -> t1; b -> t3; c -> t7] d2: [a -> t1; b -> t4; c -> t9] (* frontier updated at c *)
### 5.4 Atomic accesses Atomic locations carry not only values but also synchronization information. We model atomic locations as a pair of the value held by that location and a frontier. The frontier models the synchronization information, which is merged with the frontiers of threads that operate on the location. In this way, non-atomic writes made by one thread can become known to another by communicating via an atomic location. For example, (* Atomic locations *) A: 10, [a -> t1; b -> t5; c -> t7] B: 5, [a -> t2; b -> t4; c -> t6] shows two atomic variables A and B with values 10 and 5, respectively, and frontiers of their own. We use upper-case variable names to indicate atomic locations. During atomic reads, the frontier of the location is merged into that of the domain performing the read. For example, suppose d1 reads B. The read returns 5, and d1’s frontier updated by merging it with B’s frontier, choosing the later timestamp for each location. The abstract machine state before the atomic read is: (* Non-atomic locations *) a: [t1 -> 1; t2 -> 2] b: [t3 -> 3; t4 -> 4; t5 -> 5] c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7] (* Domains *) d1: [a -> t1; b -> t3; c -> t7] d2: [a -> t1; b -> t4; c -> t9] (* Atomic locations *) A: 10, [a -> t1; b -> t5; c -> t7] B: 5, [a -> t2; b -> t4; c -> t6] As a result of the atomic read, the abstract machine state is updated to: (* Non-atomic locations *) a: [t1 -> 1; t2 -> 2] b: [t3 -> 3; t4 -> 4; t5 -> 5] c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7]
### 5.4 Atomic accesses (* Domains *) d1: [a -> t2; b -> t4; c -> t7] (* frontier updated at a and b *) d2: [a -> t1; b -> t4; c -> t9] (* Atomic locations *) A: 10, [a -> t1; b -> t5; c -> t7] B: 5, [a -> t2; b -> t4; c -> t6] During atomic writes, the value held by the atomic location is updated. The frontiers of both the writing domain and that of the location being written to are updated to the merge of the two frontiers. For example, if d2 writes 20 to A in the current machine state, the machine state is updated to: (* Non-atomic locations *) a: [t1 -> 1; t2 -> 2] b: [t3 -> 3; t4 -> 4; t5 -> 5] c: [t6 -> 5; t7 -> 6; t9 -> 10; t8 -> 7] (* Domains *) d1: [a -> t2; b -> t4; c -> t7] d2: [a -> t1; b -> t5; c -> t9] (* frontier updated at b *) (* Atomic locations *) A: 20, [a -> t1; b -> t5; c -> t9] (* value updated. frontier updated at c. *) B: 5, [a -> t2; b -> t4; c -> t6]
### 5.5 Reasoning with the semantics Let us revisit an example from earlier (section [10.1](#s%3Awhy_relaxed_memory)). let a = ref 0 and b = ref 0 let d1 () = a := 1; !b let d2 () = b := 1; !a let main () = let h = Domain.spawn d2 in let r1 = d1 () in let r2 = Domain.join h in assert (not (r1 = 0 && r2 = 0)) This program has a data race on a and b, and hence, the program may exhibit non sequentially consistent behaviour. Let us use the semantics to show that the program may exhibit r1 = 0 && r2 = 0. The initial state of the abstract machine is: (* Non-atomic locations *) a: [t0 -> 0] b: [t1 -> 0] (* Domains *) d1: [a -> t0; b -> t1] d2: [a -> t0; b -> t1] There are several possible schedules for executing this program. Let us consider the following schedule: 1: a := 1 @ d1 2: b := 1 @ d2 3: !b @ d1 4: !a @ d2 After the first action a:=1 by d1, the machine state is: (* Non-atomic locations *) a: [t0 -> 0; t2 -> 1] (* new write at t2 *) b: [t1 -> 0] (* Domains *) d1: [a -> t2; b -> t1] (* frontier updated at a *) d2: [a -> t0; b -> t1] After the second action b:=1 by d2, the machine state is: (* Non-atomic locations *) a: [t0 -> 0; t2 -> 1] b: [t1 -> 0; t3 -> 1] (* new write at t3 *) (* Domains *) d1: [a -> t2; b -> t1] d2: [a -> t0; b -> t3] (* frontier updated at b *) Now, for the third action !b by d1, observe that d1’s frontier at b is at t1. Hence, the read may return either 0 or 1. Let us assume that it returns 0. The machine state is not updated by the non-atomic read.
### 5.5 Reasoning with the semantics Similarly, for the fourth action !a by d2, d2’s frontier at a is at t0. Hence, this read may also return either 0 or 1. Let us assume that it returns 0. Hence, the assertion in the original program, assert (not (r1 = 0 && r2 = 0)), will fail for this particular execution.
## 6 Non-compliant operations There are certain operations which are not memory model compliant. - Array.blit function on float arrays may cause *tearing*. When an unsynchronized blit operation runs concurrently with some overlapping write to the fields of the same float array, the field may end up with bits from either of the writes. - With flat-float arrays or records with only float fields on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing. - The Bytes module ‍[Bytes](../5.2/api/Bytes.html) permits mixed-mode accesses where reads and writes may be of different sizes. Unsynchronized mixed-mode accesses lead to tearing. ------------------------------------------------------------------------ [« Parallel programming](parallelism.html)[The OCaml language »](language.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The OCaml language Source: https://ocaml.org/manual/5.2/language.html ☰ - [The OCaml language](language.html) - [Language extensions](extn.html)
# Chapter 11 The OCaml language
### Foreword This document is intended as a reference manual for the OCaml language. It lists the language constructs, and gives their precise syntax and informal semantics. It is by no means a tutorial introduction to the language. A good working knowledge of OCaml is assumed. No attempt has been made at mathematical rigor: words are employed with their intuitive meaning, without further definition. As a consequence, the typing rules have been left out, by lack of the mathematical framework required to express them, while they are definitely part of a full formal definition of the language.
### Notations The syntax of the language is given in BNF-like notation. Terminal symbols are set in typewriter font (like this). Non-terminal symbols are set in italic font (like that). Square brackets \[…\] denote optional components. Curly brackets {…} denotes zero, one or several repetitions of the enclosed components. Curly brackets with a trailing plus sign {…}<sup>+</sup> denote one or several repetitions of the enclosed components. Parentheses (…) denote grouping. - [1 Lexical conventions](lex.html) - [2 Values](values.html) - [3 Names](names.html) - [4 Type expressions](types.html) - [5 Constants](const.html) - [6 Patterns](patterns.html) - [7 Expressions](expr.html) - [8 Type and exception definitions](typedecl.html) - [9 Classes](classes.html) - [10 Module types (module specifications)](modtypes.html) - [11 Module expressions (module implementations)](modules.html) - [12 Compilation units](compunit.html) ------------------------------------------------------------------------ [« Memory model: The hard bits](memorymodel.html)[Language extensions »](extn.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Language extensions Source: https://ocaml.org/manual/5.2/extn.html ☰ - [The OCaml language](language.html) - [Language extensions](extn.html)
# Chapter 12 Language extensions This chapter describes language extensions and convenience features that are implemented in OCaml, but not described in chapter [11](language.html#c%3Arefman). - [1 Recursive definitions of values](letrecvalues.html) - [2 Recursive modules](recursivemodules.html) - [3 Private types](privatetypes.html) - [4 Locally abstract types](locallyabstract.html) - [5 First-class modules](firstclassmodules.html) - [6 Recovering the type of a module](moduletypeof.html) - [7 Substituting inside a signature](signaturesubstitution.html) - [8 Type-level module aliases](modulealias.html) - [9 Overriding in open statements](overridingopen.html) - [10 Generalized algebraic datatypes](gadts.html) - [11 Syntax for Bigarray access](bigarray.html) - [12 Attributes](attributes.html) - [13 Extension nodes](extensionnodes.html) - [14 Extensible variant types](extensiblevariants.html) - [15 Generative functors](generativefunctors.html) - [16 Extension-only syntax](extensionsyntax.html) - [17 Inline records](inlinerecords.html) - [18 Documentation comments](doccomments.html) - [19 Extended indexing operators](indexops.html) - [20 Empty variant types](emptyvariants.html) - [21 Alerts](alerts.html) - [22 Generalized open statements](generalizedopens.html) - [23 Binding operators](bindingops.html) - [24 Effect handlers](effects.html) ------------------------------------------------------------------------ [« The OCaml language](language.html)[Batch compilation (ocamlc) »](comp.html)
# Chapter 12 Language extensions Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - Batch compilation (ocamlc) Source: https://ocaml.org/manual/5.2/comp.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 13 Batch compilation (ocamlc) This chapter describes the OCaml batch compiler ocamlc, which compiles OCaml source files to bytecode object files and links these object files to produce standalone bytecode executable files. These executable files are then run by the bytecode interpreter ocamlrun.
## 1 Overview of the compiler The ocamlc command has a command-line interface similar to the one of most C compilers. It accepts several types of arguments and processes them sequentially, after all options have been processed: - Arguments ending in .mli are taken to be source files for compilation unit interfaces. Interfaces specify the names exported by compilation units: they declare value names with their types, define public data types, declare abstract data types, and so on. From the file x.mli, the ocamlc compiler produces a compiled interface in the file x.cmi. - Arguments ending in .ml are taken to be source files for compilation unit implementations. Implementations provide definitions for the names exported by the unit, and also contain expressions to be evaluated for their side-effects. From the file x.ml, the ocamlc compiler produces compiled object bytecode in the file x.cmo. If the interface file x.mli exists, the implementation x.ml is checked against the corresponding compiled interface x.cmi, which is assumed to exist. If no interface x.mli is provided, the compilation of x.ml produces a compiled interface file x.cmi in addition to the compiled object code file x.cmo. The file x.cmi produced corresponds to an interface that exports everything that is defined in the implementation x.ml.
## 1 Overview of the compiler - Arguments ending in .cmo are taken to be compiled object bytecode. These files are linked together, along with the object files obtained by compiling .ml arguments (if any), and the OCaml standard library, to produce a standalone executable program. The order in which .cmo and .ml arguments are presented on the command line is relevant: compilation units are initialized in that order at run-time, and it is a link-time error to use a component of a unit before having initialized it. Hence, a given x.cmo file must come before all .cmo files that refer to the unit x. - Arguments ending in .cma are taken to be libraries of object bytecode. A library of object bytecode packs in a single file a set of object bytecode files (.cmo files). Libraries are built with ocamlc -a (see the description of the -a option below). The object files contained in the library are linked as regular .cmo files (see above), in the order specified when the .cma file was built. The only difference is that if an object file contained in a library is not referenced anywhere in the program, then it is not linked in. - Arguments ending in .c are passed to the C compiler, which generates a .o object file (.obj under Windows). This object file is linked with the program if the -custom flag is set (see the description of -custom below). - Arguments ending in .o or .a (.obj or .lib under Windows) are assumed to be C object files and libraries. They are passed to the C linker when linking in -custom mode (see the description of -custom below).
## 1 Overview of the compiler - Arguments ending in .so (.dll under Windows) are assumed to be C shared libraries (DLLs). During linking, they are searched for external C functions referenced from the OCaml code, and their names are written in the generated bytecode executable. The run-time system ocamlrun then loads them dynamically at program start-up time. The output of the linking phase is a file containing compiled bytecode that can be executed by the OCaml bytecode interpreter: the command named ocamlrun. If a.out is the name of the file produced by the linking phase, the command ocamlrun a.out arg1 arg2 … argn executes the compiled code contained in a.out, passing it as arguments the character strings arg<sub>1</sub> to arg<sub>n</sub>. (See chapter ‍[15](runtime.html#c%3Aruntime) for more details.) On most systems, the file produced by the linking phase can be run directly, as in: ./a.out arg1 arg2 … argn The produced file has the executable bit set, and it manages to launch the bytecode interpreter by itself. The compiler is able to emit some information on its internal stages. It can output .cmt files for the implementation of the compilation unit and .cmti for signatures if the option -bin-annot is passed to it (see the description of -bin-annot below). Each such file contains a typed abstract syntax tree (AST), that is produced during the type checking procedure. This tree contains all available information about the location and the specific type of each term in the source file. The AST is partial if type checking was unsuccessful.
## 1 Overview of the compiler These .cmt and .cmti files are typically useful for code inspection tools.
## 2 Options The following command-line options are recognized by ocamlc. The options -pack, -a, -c, -output-obj and -output-complete-obj are mutually exclusive. -a Build a library(.cma file) with the object files ( .cmo files) given on the command line, instead of linking them into an executable file. The name of the library must be set with the -o option. If -custom, -cclib or -ccopt options are passed on the command line, these options are stored in the resulting .cmalibrary. Then, linking with this library automatically adds back the -custom, -cclib and -ccopt options as if they had been provided on the command line, unless the -noautolink option is given. -absname Force error messages to show absolute paths for file names. -no-absname Do not try to show absolute filenames in error messages. -annot Deprecated since OCaml 4.11. Please use -bin-annot instead. -args filename Read additional newline-terminated command line arguments from filename. -args0 filename Read additional null character terminated command line arguments from filename. -bin-annot Dump detailed information about the compilation (types, bindings, tail-calls, etc) in binary format. The information for file src.ml (resp. src.mli) is put into file src.cmt (resp. src.cmti). In case of a type error, dump all the information inferred by the type-checker before the error. The \*.cmt and \*.cmti files produced by -bin-annot contain more information and are much more compact than the files produced by -annot.
## 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 when linking in “custom runtime” mode (see the -custom option) and as the C compiler for compiling .c source files. When linking object files produced by a C++ compiler (such as g++ or clang++), it is recommended to use -cc c++. -cclib -llibname Pass the -llibname option to the C linker when linking in “custom runtime” mode (see the -custom option). This causes the given C library to be linked with the program. -ccopt option Pass the given option to the C compiler and linker. When linking in “custom runtime” mode, for instance -ccopt -Ldir causes the C linker to search for C libraries in directory dir. (See the -custom option.) -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.
## 2 Options The environment variable OCAML_COLOR is considered if -color is not provided. Its values are auto/always/never as above. If -color is not provided, OCAML_COLOR is not set and the environment variable NO_COLOR is set, then color output is disabled. Otherwise, the default setting is ’auto’, and the current heuristic checks that the TERM environment variable exists and is not empty or dumb, and that ’isatty(stderr)’ holds. -error-style mode Control the way error messages and warnings are printed. The following modes are supported: short only print the error and its location; contextual like short, but also display the source code snippet corresponding to the location of the error. The default setting is contextual. The environment variable OCAML_ERROR_STYLE is considered if -error-style is not provided. Its values are short/contextual as above. -compat-32 Check that the generated bytecode executable can run on 32-bit platforms and signal an error if it cannot. This is useful when compiling bytecode on a 64-bit machine. -config Print the version number of ocamlc and a detailed summary of its configuration, then exit. -config-var var Print the value of a specific configuration variable from the -config output, then exit. If the 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.
## 2 Options -custom Link in “custom runtime” mode. In the default linking mode, the linker produces bytecode that is intended to be executed with the shared runtime system, ocamlrun. In the custom runtime mode, the linker produces an output file that contains both the runtime system and the bytecode for the program. The resulting file is larger, but it can be executed directly, even if the ocamlrun command is not installed. Moreover, the “custom runtime” mode enables static linking of OCaml code with user-defined C functions, as described in chapter ‍[22](intfc.html#c%3Aintf-c). > Unix:  Never use the strip command on executables produced by ocamlc -custom, this would remove the bytecode part of the executable. > Unix:  Security warning: never set the “setuid” or “setgid” bits on executables produced by ocamlc -custom, this would make them vulnerable to attacks. -depend ocamldep-args Compute dependencies, as the ocamldep command would do. The remaining arguments are interpreted as if they were given to the ocamldep command. -dllib -llibname Arrange for the C shared library dlllibname.so (dlllibname.dll under Windows) to be loaded dynamically by the run-time system ocamlrun at program start-up time. -dllpath dir Adds the directory dir to the run-time search path for shared C libraries. At link-time, shared libraries are searched in the standard search path (the one corresponding to the -I option). The -dllpath option simply stores dir in the produced executable file, where ocamlrun can find it and use it as described in section ‍[15.3](runtime.html#s%3Aocamlrun-dllpath).
## 2 Options -for-pack module-path Generate an object file (.cmo) that can later be included as a sub-module (with the given access path) of a compilation unit constructed with -pack. For instance, ocamlc -for-pack P -c A.ml will generate a..cmo that can later be used with ocamlc -pack -o P.cmo a.cmo. Note: you can still pack a module that was compiled without -for-pack but in this case exceptions will be printed with the wrong names. -g Add debugging information while compiling and linking. This option is required in order to be able to debug the program with ocamldebug (see chapter ‍[20](debugger.html#c%3Adebugger)), and 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 .cmo, libraries (.cma) and C libraries specified with -cclib -lxxx. By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. See also option -nostdlib. If the given directory starts with +, it is taken relative to the standard library directory. For instance, -I +unix adds the subdirectory unix of the standard library to the search path. -H directory Behaves identically to -I, except that (a) programs may not directly refer to modules added to the search path this way, and (b) these directories are searched after any -I directories. This makes it possible to provide the compiler with compiled interface and object code files for the current program’s transitive dependencies (the dependencies of its dependencies) without allowing them to silently become direct dependencies. -impl filename Compile the file filename as an implementation file, even if its extension is not .ml. -intf filename Compile the file filename as an interface file, even if its extension is not .mli. -intf-suffix string Recognize file names ending with string as interface files (instead of the default .mli). -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.
## 2 Options -linkall Force all modules contained in libraries to be linked in. If this flag is not given, unreferenced modules are not linked in. When building a library (option -a), setting the -linkall option forces all subsequent links of programs involving that library to link all the modules contained in the library. When compiling a module (option -c), setting the -linkall option ensures that this module will always be linked if it is put in a library and this library is linked. -make-runtime Build a custom runtime system (in the file specified by option -o) incorporating the C object files and libraries given on the command line. This custom runtime system can be used later to execute bytecode executables produced with the ocamlc -use-runtime runtime-name option. See section ‍[22.1.6](intfc.html#ss%3Acustom-runtime) for more information. -match-context-rows Set the number of rows of context used for optimization during pattern matching compilation. The default value is 32. Lower values cause faster compilation, but less optimized code. This advanced option is meant for use in the event that a pattern-match-heavy program leads to significant increases in compilation time. -no-alias-deps Do not record dependencies for module aliases. See section ‍[12.8](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.
## 2 Options -noassert Do not compile assertion checks. Note that the special form assert false is always compiled because it is typed specially. This flag has no effect when linking already-compiled files. -noautolink When linking .cmalibraries, ignore -custom, -cclib and -ccopt options potentially contained in the libraries (if these options were given when building the libraries). This can be useful if a library contains incorrect specifications of C libraries or C options; in this case, during linking, set -noautolink and pass the correct C libraries and options on the command line. -nolabels Ignore non-optional labels in types. Labels cannot be used in applications, and parameter order becomes strict. -nostdlib Do not include the standard library directory in the list of directories searched for compiled interface files (.cmi), compiled object code files (.cmo), libraries (.cma), and C libraries specified with -cclib -lxxx. See also option -I. -o output-file Specify the name of the output file to produce. For executable files, the default output name is a.out under Unix and camlprog.exe under Windows. If the -a option is given, specify the name of the library produced. If the -pack option is given, specify the name of the packed object file produced. If the -output-obj or -output-complete-obj options are given, specify the name of the produced object file. If the -c option is given, specify the name of the object file produced for the *next* source file that appears on the command line.
## 2 Options -opaque When the native compiler compiles an implementation, by default it produces a .cmx file containing information for cross-module optimization. It also expects .cmx files to be present for the dependencies of the currently compiled source, and uses them for optimization. Since OCaml 4.03, the compiler will emit a warning if it is unable to locate the .cmx file of one of those dependencies. The -opaque option, available since 4.04, disables cross-module optimization information for the currently compiled unit. When compiling .mli interface, using -opaque marks the compiled .cmi interface so that subsequent compilations of modules that depend on it will not rely on the corresponding .cmx file, nor warn if it is absent. When the native compiler compiles a .ml implementation, using -opaque generates a .cmx that does not contain any cross-module optimization information. Using this option may degrade the quality of generated code, but it reduces compilation time, both on clean and incremental builds. Indeed, with the native compiler, when the implementation of a compilation unit changes, all the units that depend on it may need to be recompiled – because the cross-module information may have changed. If the compilation unit whose implementation changed was compiled with -opaque, no such recompilation needs to occur. This option can thus be used, for example, to get faster edit-compile-test feedback loops.
## 2 Options -open Module Opens the given module before processing the interface or implementation files. If several -open options are given, they are processed in order, just as if the statements open! Module1;; ... open! ModuleN;; were added at the top of each file. -output-obj Cause the linker to produce a C object file instead of a bytecode executable file. This is useful to wrap OCaml code as a C library, callable from any C program. See chapter ‍[22](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 C source file (.c extension) or a compiled shared/dynamic library (.so extension, .dll under Windows). -output-complete-exe Build a self-contained executable by linking a C object file containing the bytecode program, the OCaml runtime system and any other static C code given to ocamlc. The resulting effect is similar to -custom, except that the bytecode is embedded in the C code so it is no longer accessible to tools such as ocamldebug. On the other hand, the resulting binary is resistant to strip. -output-complete-obj Same as -output-obj options except the object file produced includes the runtime and autolink libraries. -pack Build a bytecode object file (.cmo file) and its associated compiled interface (.cmi) that combines the object files given on the command line, making them appear as sub-modules of the output .cmo file. The name of the output .cmo file must be given with the -o option. For instance,
## 2 Options ocamlc -pack -o p.cmo a.cmo b.cmo c.cmo generates compiled files p.cmo and p.cmi describing a compilation unit having three sub-modules A, B and C, corresponding to the contents of the object files a.cmo, b.cmo and c.cmo. These contents can be referenced as P.A, P.B and P.C in the remainder of the program. -pp command Cause the compiler to call the given command as a preprocessor for each source file. The output of command is redirected to an intermediate file, which is compiled. If there are no compilation errors, the intermediate file is deleted afterwards. -ppx command After parsing, pipe the abstract syntax tree through the preprocessor command. The module Ast_mapper, described in 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.
## 2 Options -rectypes Allow arbitrary recursive types during type-checking. By default, only recursive types where the recursion goes through an object type are supported. Note that once you have created an interface using this flag, you must use it again for all dependencies. -runtime-variant suffix Add the suffix string to the name of the runtime library used by the program. Currently, only one such suffix is supported: d, and only if the OCaml compiler was configured with option -with-debug-runtime. This suffix gives the debug version of the runtime, which is useful for debugging pointer problems in low-level code such as C stubs. -safe-string Enforce the separation between types string and bytes, thereby making strings read-only. This is the default, and enforced since OCaml 5.0. -safer-matching Do not use type information to optimize pattern-matching. This allows to detect match failures even if a pattern-matching was wrongly assumed to be exhaustive. This only impacts GADT and polymorphic variant compilation. -short-paths When a type is visible under several module-paths, use the shortest one when printing the type’s name in inferred interfaces and error and warning messages. Identifier names starting with an underscore \_ or containing double underscores \_\_ incur a penalty of +10 when computing their length. -stop-after pass Stop compilation after the given compilation pass. The currently supported passes are: parsing, typing. -strict-sequence Force the left-hand part of each sequence to have type unit.
## 2 Options -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\]. -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 slightly faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. Additionally, turn off the check for zero divisor in integer division and modulus operations. With -unsafe, an integer division (or modulus) by zero can halt the program or continue with an unspecified result instead of raising a Division_by_zero exception. -unsafe-string Identify the types string and bytes, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0. -use-runtime runtime-name Generate a bytecode executable file that can be executed on the custom runtime system runtime-name, built earlier with ocamlc -make-runtime runtime-name. See section ‍[22.1.6](intfc.html#ss%3Acustom-runtime) for more information.
## 2 Options -v Print the version number of the compiler and the location of the standard library directory, then exit. -verbose Print all external commands before they are executed, in particular invocations of the C compiler and linker in -custom mode. Useful to debug C library problems. -version or -vnum Print the version number of the compiler in short form (e.g. 3.11.0), then exit. -w warning-list Enable, disable, or mark as fatal the warnings specified by the argument warning-list. Each warning can be *enabled* or *disabled*, and each warning can be *fatal* or *non-fatal*. If a warning is disabled, it isn’t displayed and doesn’t affect compilation in any way (even if it is fatal). If a warning is enabled, it is displayed normally by the compiler whenever the source code triggers it. If it is enabled and fatal, the compiler will also stop with an error after displaying it. The warning-list argument is a sequence of warning specifiers, with no separators between them. A warning specifier is one of the following: +num Enable warning number num. -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.
## 2 Options @letter Enable and mark as fatal the set of warnings corresponding to letter. The letter may be uppercase or lowercase. uppercase-letter Enable the set of warnings corresponding to uppercase-letter. lowercase-letter Disable the set of warnings corresponding to lowercase-letter. Alternatively, warning-list can specify a single warning using its mnemonic name (see below), as follows: +name Enable warning name. -name Disable warning name. @name Enable and mark as fatal warning name. Warning numbers, letters and names which are not currently defined are ignored. The warnings are as follows (the name following each number specifies the mnemonic for that warning). 1 comment-start Suspicious-looking start-of-comment mark. 2 comment-not-end Suspicious-looking end-of-comment mark. 3 Deprecated synonym for the ’deprecated’ alert. 4 fragile-match Fragile pattern matching: matching that will remain complete even if additional constructors are added to one of the variant types matched. 5 ignored-partial-application Partially applied function: expression whose result has function type and is ignored. 6 labels-omitted Label omitted in function application. 7 method-override Method overridden. 8 partial-match Partial match: missing cases in pattern-matching. 9 missing-record-field-pattern Missing fields in a record pattern. 10 non-unit-statement Expression on the left-hand side of a sequence that doesn’t have type unit (and that is not a function, see warning number 5). 11 redundant-case Redundant case in a pattern matching (unused match case).
## 2 Options 12 redundant-subpat Redundant sub-pattern in a pattern-matching. 13 instance-variable-override Instance variable overridden. 14 illegal-backslash Illegal backslash escape in a string constant. 15 implicit-public-methods Private method made public implicitly. 16 unerasable-optional-argument Unerasable optional argument. 17 undeclared-virtual-method Undeclared virtual method. 18 not-principal Non-principal type. 19 non-principal-labels Type without principality. 20 ignored-extra-argument Unused function argument. 21 nonreturning-statement Non-returning statement. 22 preprocessor Preprocessor warning. 23 useless-record-with Useless record with clause. 24 bad-module-name Bad module name: the source file name is not a valid OCaml module name. 25 Ignored: now part of warning 8. 26 unused-var Suspicious unused variable: unused variable that is bound with let or as, and doesn’t start with an underscore (\_) character. 27 unused-var-strict Innocuous unused variable: unused variable that is not bound with let nor as, and doesn’t start with an underscore (\_) character. 28 wildcard-arg-to-constant-constr Wildcard pattern given as argument to a constant constructor. 29 eol-in-string Unescaped end-of-line in a string constant (non-portable code). 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)
## 2 Options 33 unused-open Unused open statement. (since 4.00) 34 unused-type-declaration Unused type declaration. (since 4.00) 35 unused-for-index Unused for-loop index. (since 4.00) 36 unused-ancestor Unused ancestor variable. (since 4.00) 37 unused-constructor Unused constructor. (since 4.00) 38 unused-extension Unused extension constructor. (since 4.00) 39 unused-rec-flag Unused rec flag. (since 4.00) 40 name-out-of-scope Constructor or label name used out of scope. (since 4.01) 41 ambiguous-name Ambiguous constructor or label name. (since 4.01) 42 disambiguated-name Disambiguated constructor or label name (compatibility warning). (since 4.01) 43 nonoptional-label Nonoptional label applied as optional. (since 4.01) 44 open-shadow-identifier Open statement shadows an already defined identifier. (since 4.01) 45 open-shadow-label-constructor Open statement shadows an already defined label or constructor. (since 4.01) 46 bad-env-variable Error in environment variable. (since 4.01) 47 attribute-payload Illegal attribute payload. (since 4.02) 48 eliminated-optional-arguments Implicit elimination of optional arguments. (since 4.02) 49 no-cmi-file Absent cmi file when looking up module alias. (since 4.02) 50 unexpected-docstring Unexpected documentation comment. (since 4.03) 51 wrong-tailcall-expectation Function call annotated with an incorrect @tailcall attribute. (since 4.03) 52 fragile-literal-pattern (see [13.5.3](#ss%3Awarn52)) Fragile constant pattern. (since 4.03) 53 misplaced-attribute Attribute cannot appear in this context. (since 4.03)
## 2 Options 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](#ss%3Awarn57)) Ambiguous or-pattern variables under guard. (since 4.03) 58 no-cmx-file Missing cmx file. (since 4.03) 59 flambda-assignment-to-non-mutable-value Assignment to non-mutable value. (since 4.03) 60 unused-module Unused module declaration. (since 4.04) 61 unboxable-type-in-prim-decl Unboxable type in primitive declaration. (since 4.04) 62 constraint-on-gadt Type constraint on GADT type declaration. (since 4.06) 63 erroneous-printed-signature Erroneous printed signature. (since 4.08) 64 unsafe-array-syntax-without-parsing -unsafe used with a preprocessor returning a syntax tree. (since 4.08) 65 redefining-unit Type declaration defining a new ’()’ constructor. (since 4.08) 66 unused-open-bang Unused open! statement. (since 4.08) 67 unused-functor-parameter Unused functor parameter. (since 4.10) 68 match-on-mutable-state-prevent-uncurry Pattern-matching depending on mutable state prevents the remaining arguments from being uncurried. (since 4.12) 69 unused-field Unused record field. (since 4.13) 70 missing-mli Missing interface file. (since 4.13) 71 unused-tmc-attribute Unused @tail_mod_cons attribute. (since 4.14) 72 tmc-breaks-tailcall A tail call is turned into a non-tail call by the @tail_mod_cons transformation. (since 4.14)
## 2 Options 73 generative-application-expects-unit A generative functor is applied to an empty structure (struct end) rather than to (). (since 5.1) A all warnings C warnings 1, 2. D Alias for warning 3. E Alias for warning 4. F Alias for warning 5. K warnings 32, 33, 34, 35, 36, 37, 38, 39. L Alias for warning 6. M Alias for warning 7. P Alias for warning 8. R Alias for warning 9. S Alias for warning 10. U warnings 11, 12. V Alias for warning 13. X warnings 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 30. Y Alias for warning 26. Z Alias for warning 27. The default setting is -w +a-4-6-7-9-27-29-32..42-44-45-48-50-60. It is displayed by ocamlc -help. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker. -warn-error warning-list Mark as fatal the warnings specified in the argument warning-list. The compiler will stop with an error when one of these warnings is emitted. The warning-list has the same meaning as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign both enables and marks as fatal the corresponding warnings. Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error in production code, because this can break your build when future versions of OCaml add some new warnings. The default setting is -warn-error -a (no warning is fatal). -warn-help Show the description of all available warning numbers. -where Print the location of the standard library, then exit.
## 2 Options -with-runtime Include the runtime system in the generated program. This is the default. -without-runtime The compiler does not include the runtime system (nor a reference to it) in the generated program; it must be supplied separately. - file Process file as a file name, even if it starts with a dash (-) character. -help or --help Display a short usage summary and exit.
##### contextual-cli-control Contextual control of command-line options The compiler command line can be modified “from the outside” with the following mechanisms. These are experimental and subject to change. They should be used only for experimental and development work, not in released packages. OCAMLPARAM (environment variable) A set of arguments that will be inserted before or after the arguments from the command 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 Modules and the file system This short section is intended to clarify the relationship between the names of the modules corresponding to compilation units and the names of the files that contain their compiled interface and compiled implementation. The compiler always derives the module name by taking the capitalized base name of the source file (.ml or .mli file). That is, it strips the leading directory name, if any, as well as the .ml or .mli suffix; then, it set the first letter to uppercase, in order to comply with the requirement that module names must be capitalized. For instance, compiling the file mylib/misc.ml provides an implementation for the module named Misc. Other compilation units may refer to components defined in mylib/misc.ml under the names Misc.name; they can also do open Misc, then use unqualified names name. The .cmi and .cmo files produced by the compiler have the same base name as the source file. Hence, the compiled files always have their base name equal (modulo capitalization of the first letter) to the name of the module they describe (for .cmi files) or implement (for .cmo files).
## 3 Modules and the file system When the compiler encounters a reference to a free module identifier Mod, it looks in the search path for a file named Mod.cmi or mod.cmi and loads the compiled interface contained in that file. As a consequence, renaming .cmi files is not advised: the name of a .cmi file must always correspond to the name of the compilation unit it implements. It is admissible to move them to another directory, if their base name is preserved, and the correct -I options are given to the compiler. The compiler will flag an error if it loads a .cmi file that has been renamed. Compiled bytecode files (.cmo files), on the other hand, can be freely renamed once created. That’s because the linker never attempts to find by itself the .cmo file that implements a module with a given name: it relies instead on the user providing the list of .cmo files by hand.
## 4 Common errors This section describes and explains the most frequently encountered error messages. Cannot find file filename The named file could not be found in the current directory, nor in the directories of the search path. The filename is either a compiled interface file (.cmi file), or a compiled bytecode file (.cmo file). If filename has the format mod.cmi, this means you are trying to compile a file that references identifiers from module mod, but you have not yet compiled an interface for module mod. Fix: compile mod.mli or mod.ml first, to create the compiled interface mod.cmi. If filename has the format mod.cmo, this means you are trying to link a bytecode object file that does not exist yet. Fix: compile mod.ml first. If your program spans several directories, this error can also appear because you haven’t specified the directories to look into. Fix: add the correct -I options to the command line. Corrupted compiled interface filename The compiler produces this error when it tries to read a compiled interface file (.cmi file) that has the wrong structure. This means something went wrong when this .cmi file was written: the disk was full, the compiler was interrupted in the middle of the file creation, and so on. This error can also appear if a .cmi file is modified after its creation by the compiler. Fix: remove the corrupted .cmi file, and rebuild it.
## 4 Common errors This expression has type t<sub>1</sub>, but is used with type t<sub>2</sub> This is by far the most common type error in programs. Type t<sub>1</sub> is the type inferred for the expression (the part of the program that is displayed in the error message), by looking at the expression itself. Type t<sub>2</sub> is the type expected by the context of the expression; it is deduced by looking at how the value of this expression is used in the rest of the program. If the two types t<sub>1</sub> and t<sub>2</sub> are not compatible, then the error above is produced. In some cases, it is hard to understand why the two types t<sub>1</sub> and t<sub>2</sub> are incompatible. For instance, the compiler can report that “expression of type foo cannot be used with type foo”, and it really seems that the two types foo are compatible. This is not always true. Two type constructors can have the same name, but actually represent different types. This can happen if a type constructor is redefined. Example: type foo = A | B let f = function A -> 0 | B -> 1 type foo = C | D f C This result in the error message “expression C of type foo cannot be used with type foo”.
## 4 Common errors The type of this expression, t, contains type variables that cannot be generalized Type variables ('a, 'b, …) in a type t can be in either of two states: generalized (which means that the type t is valid for all possible instantiations of the variables) and not generalized (which means that the type t is valid only for one instantiation of the variables). In a let binding let name = expr, the type-checker normally generalizes as many type variables as possible in the type of expr. However, this leads to unsoundness (a well-typed program can crash) in conjunction with polymorphic mutable data structures. To avoid this, generalization is performed at let bindings only if the bound expression expr belongs to the class of “syntactic values”, which includes constants, identifiers, functions, tuples of syntactic values, etc. In all other cases (for instance, expr is a function application), a polymorphic mutable could have been created and generalization is therefore turned off for all variables occurring in contravariant or non-variant branches of the type. For instance, if the type of a non-value is 'a list the variable is generalizable (list is a covariant type constructor), but not in 'a list -> 'a list (the left branch of -> is contravariant) or 'a ref (ref is non-variant).
## 4 Common errors Non-generalized type variables in a type cause no difficulties inside a given structure or compilation unit (the contents of a .ml file, or an interactive session), but they cannot be allowed inside signatures nor in compiled interfaces (.cmi file), because they could be used inconsistently later. Therefore, the compiler flags an error when a structure or compilation unit defines a value name whose type contains non-generalized type variables. There are two ways to fix this error: - Add a type constraint or a .mli file to give a monomorphic type (without type variables) to name. For instance, instead of writing let sort_int_list = List.sort Stdlib.compare (* inferred type 'a list -> 'a list, with 'a not generalized *) write let sort_int_list = (List.sort Stdlib.compare : int list -> int list);; - If you really need name to have a polymorphic type, turn its defining expression into a function by adding an extra parameter. For instance, instead of writing let map_length = List.map Array.length (* inferred type 'a array list -> int list, with 'a not generalized *) write let map_length lv = List.map Array.length lv
## 4 Common errors Reference to undefined global mod This error appears when trying to link an incomplete or incorrectly ordered set of files. Either you have forgotten to provide an implementation for the compilation unit named mod on the command line (typically, the file named mod.cmo, or a library containing that file). Fix: add the missing .ml or .cmo file to the command line. Or, you have provided an implementation for the module named mod, but it comes too late on the command line: the implementation of mod must come before all bytecode object files that reference mod. Fix: change the order of .ml and .cmo files on the command line. Of course, you will always encounter this error if you have mutually recursive functions across modules. That is, function Mod1.f calls function Mod2.g, and function Mod2.g calls function Mod1.f. In this case, no matter what permutations you perform on the command line, the program will be rejected at link-time. Fixes: - Put f and g in the same module. - Parameterize one function by the other. That is, instead of having mod1.ml: let f x = ... Mod2.g ... mod2.ml: let g y = ... Mod1.f ... define mod1.ml: let f g x = ... g ... mod2.ml: let rec g y = ... Mod1.f g ... and link mod1.cmo before mod2.cmo. - Use a reference to hold one of the two functions, as in :
## 4 Common errors mod1.ml: let forward_g = ref((fun x -> failwith "forward_g") : <type>) let f x = ... !forward_g ... mod2.ml: let g y = ... Mod1.f ... let _ = Mod1.forward_g := g The external function f is not available This error appears when trying to link code that calls external functions written in C. As explained in chapter ‍[22](intfc.html#c%3Aintf-c), such code must be linked with C libraries that implement the required f C function. If the C libraries in question are not shared libraries (DLLs), the code must be linked in “custom runtime” mode. Fix: add the required C libraries to the command line, and possibly the -custom option.
## 5 Warning reference This section describes and explains in detail some warnings:
### 5.1 Warning 6: Label omitted in function application OCaml supports labels-omitted full applications: if the function has a known arity, all the arguments are unlabeled, and their number matches the number of non-optional parameters, then labels are ignored and non-optional parameters are matched in their definition order. Optional arguments are defaulted. let f ~x ~y = x + y let test = f 2 3 > let test = f 2 3 > ^ > Warning 6 [labels-omitted]: labels x, y were omitted in the application of this function. This support for labels-omitted application was introduced when labels were added to OCaml, to ease the progressive introduction of labels in a codebase. However, it has the downside of weakening the labeling discipline: if you use labels to prevent callers from mistakenly reordering two parameters of the same type, labels-omitted make this mistake possible again. Warning 6 warns when labels-omitted applications are used, to discourage their use. When labels were introduced, this warning was not enabled by default, so users would use labels-omitted applications, often without noticing. Over time, it has become idiomatic to enable this warning to avoid argument-order mistakes. The warning is now on by default, since OCaml 4.13. Labels-omitted applications are not recommended anymore, but users wishing to preserve this transitory style can disable the warning explicitly.
### 5.2 Warning 9: missing fields in a record pattern When pattern matching on records, it can be useful to match only few fields of a record. Eliding fields can be done either implicitly or explicitly by ending the record pattern with ; \_. However, implicit field elision is at odd with pattern matching exhaustiveness checks. Enabling warning 9 prioritizes exhaustiveness checks over the convenience of implicit field elision and will warn on implicit field elision in record patterns. In particular, this warning can help to spot exhaustive record pattern that may need to be updated after the addition of new fields to a record type. type 'a point = {x : 'a; y : 'a} let dx { x } = x (* implicit field elision: trigger warning 9 *) let dy { y; _ } = y (* explicit field elision: do not trigger warning 9 *)
### 5.3 Warning 52: fragile constant pattern Some constructors, such as the exception constructors Failure and Invalid_argument, take as parameter a string value holding a text message intended for the user. These text messages are usually not stable over time: call sites building these constructors may refine the message in a future version to make it more explicit, etc. Therefore, it is dangerous to match over the precise value of the message. For example, until OCaml 4.02, Array.iter2 would raise the exception Invalid_argument "arrays must have the same length" Since 4.03 it raises the more helpful message Invalid_argument "Array.iter2: arrays must have the same length" but this means that any code of the form try ... with Invalid_argument "arrays must have the same length" -> ... is now broken and may suffer from uncaught exceptions. Warning 52 is there to prevent users from writing such fragile code in the first place. It does not occur on every matching on a literal string, but only in the case in which library authors expressed their intent to possibly change the constructor parameter value in the future, by using the attribute ocaml.warn_on_literal_pattern (see the manual section on builtin attributes in [12.12.1](attributes.html#ss%3Abuiltin-attributes)): type t = \| Foo of string \[@ocaml.warn_on_literal_pattern\] \| Bar of string let no_warning = function \| Bar "specific value" -> 0 \| \_ -> 1 let warning = function \| Foo "specific value" -> 0 \| \_ -> 1
### 5.3 Warning 52: fragile constant pattern Warning 52 \[fragile-literal-pattern\]: Code should not depend on the actual values of this constructor's arguments. They are only for information and may change in future versions. (see manual section 13.5.3) In particular, all built-in exceptions with a string argument have this attribute set: Invalid_argument, Failure, Sys_error will all raise this warning if you match for a specific string argument. Additionally, built-in exceptions with a structured argument that includes a string also have the attribute set: Assert_failure and Match_failure will raise the warning for a pattern that uses a literal string to match the first element of their tuple argument. If your code raises this warning, you should *not* change the way you test for the specific string to avoid the warning (for example using a string equality inside the right-hand-side instead of a literal pattern), as your code would remain fragile. You should instead enlarge the scope of the pattern by matching on all possible values. let warning = function | Foo _ -> 0 | _ -> 1 This may require some care: if the scrutinee may return several different cases of the same pattern, or raise distinct instances of the same exception, you may need to modify your code to separate those several cases. For example, try (int_of_string count_str, bool_of_string choice_str) with | Failure "int_of_string" -> (0, true) | Failure "bool_of_string" -> (-1, false)
### 5.3 Warning 52: fragile constant pattern should be rewritten into more atomic tests. For example, using the exception patterns documented in Section ‍[11.6](patterns.html#sss%3Aexception-match), one can write: match int_of_string count_str with | exception (Failure _) -> (0, true) | count -> begin match bool_of_string choice_str with | exception (Failure _) -> (-1, false) | choice -> (count, choice) end The only case where that transformation is not possible is if a given function call may raise distinct exceptions with the same constructor but different string values. In this case, you will have to check for specific string values. This is dangerous API design and it should be discouraged: it’s better to define more precise exception constructors than store useful information in strings.
### 5.4 Warning 57: Ambiguous or-pattern variables under guard The semantics of or-patterns in OCaml is specified with a left-to-right bias: a value v matches the pattern p \| q if it matches p or q, but if it matches both, the environment captured by the match is the environment captured by p, never the one captured by q. While this property is generally intuitive, there is at least one specific case where a different semantics might be expected. Consider a pattern followed by a when-guard: \| ‍p ‍when ‍g ‍-> ‍e, for example: | ((Const x, _) | (_, Const x)) when is_neutral x -> branch The semantics is clear: match the scrutinee against the pattern, if it matches, test the guard, and if the guard passes, take the branch. In particular, consider the input (Const ‍a, Const ‍b), where a fails the test is_neutral ‍a, while b passes the test is_neutral ‍b. With the left-to-right semantics, the clause above is *not* taken by its input: matching (Const ‍a, Const ‍b) against the or-pattern succeeds in the left branch, it returns the environment x ‍-> ‍a, and then the guard is_neutral ‍a is tested and fails, the branch is not taken. However, another semantics may be considered more natural here: any pair that has one side passing the test will take the branch. With this semantics the previous code fragment would be equivalent to | (Const x, _) when is_neutral x -> branch | (_, Const x) when is_neutral x -> branch This is *not* the semantics adopted by OCaml.
### 5.4 Warning 57: Ambiguous or-pattern variables under guard Warning 57 is dedicated to these confusing cases where the specified left-to-right semantics is not equivalent to a non-deterministic semantics (any branch can be taken) relatively to a specific guard. More precisely, it warns when guard uses “ambiguous” variables, that are bound to different parts of the scrutinees by different sides of a or-pattern. ------------------------------------------------------------------------ [« Language extensions](extn.html)[The toplevel system or REPL (ocaml) »](toplevel.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------
# OCaml - The toplevel system or REPL (ocaml) Source: https://ocaml.org/manual/5.2/toplevel.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 14 The toplevel system or REPL (ocaml) This chapter describes ocaml, the toplevel system for OCaml, that permits interactive use of the OCaml system through a read-eval-print loop (REPL). In this mode, the system repeatedly reads OCaml phrases from the input, then typechecks, compile and evaluate them, then prints the inferred type and result value, if any. End-of-file on standard input terminates ocaml. Input to the toplevel can span several lines. It begins after the # (sharp) prompt printed by the system and is terminated by ;; (a double-semicolon) followed by optional white space and comments and an end of line. The toplevel input consists in one or several toplevel phrases, with the following syntax:
# Chapter 14 The toplevel system or REPL (ocaml) <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">toplevel-input</td><td class="c005">::=</td><td class="c007">{ [definition](modules.html#definition) } ;;</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> [expr](expr.html#expr) ;;</td></tr><tr class="odd"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> # [ident](lex.html#ident) [ [directive-argument](#directive-argument) ] ;;</td></tr><tr class="even"><td class="c008"> </td><td></td><td></td></tr><tr class="odd"><td class="c008">directive-argument</td><td class="c005">::=</td><td class="c007">[string-literal](lex.html#string-literal)</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> [integer-literal](lex.html#integer-literal)</td></tr><tr class="odd"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> [value-path](names.html#value-path)</td></tr><tr class="even"><td class="c008"> </td><td class="c005">∣</td><td class="c007"> true ∣ false</td></tr></tbody></table></td></tr></tbody></table>
# Chapter 14 The toplevel system or REPL (ocaml) A phrase can consist of a sequence of definitions, like those found in implementations of compilation units or in struct … end module expressions. The definitions can bind value names, type names, exceptions, module names, or module type names. The toplevel system performs the bindings, then prints the types and values (if any) for the names thus defined. A phrase may also consist in a value expression (section ‍[11.7](expr.html#s%3Avalue-expr)). It is simply evaluated without performing any bindings, and its value is printed. Finally, a phrase can also consist in a toplevel directive, starting with # (the sharp sign). These directives control the behavior of the toplevel; they are listed below in section ‍[14.2](#s%3Atoplevel-directives).
# Chapter 14 The toplevel system or REPL (ocaml) > Unix:  The toplevel system is started by the command ocaml, as follows: > > ocaml options objects # interactive mode > ocaml options objects scriptfile # script mode > > options are described below. objects are filenames ending in .cmo or .cma; they are loaded into the interpreter immediately after options are set. scriptfile is any file name not ending in .cmo or .cma. > > If no scriptfile is given on the command line, the toplevel system enters interactive mode: phrases are read on standard input, results are printed on standard output, errors on standard error. End-of-file on standard input terminates ocaml (see also the #quit directive in section ‍[14.2](#s%3Atoplevel-directives)). > > On start-up (before the first phrase is read), the contents of initialization file are read as a sequence of OCaml phrases and executed as per the #use directive described in section ‍[14.2](#s%3Atoplevel-directives). The evaluation outcode for each phrase are not displayed. > > The initialization file is the first found of: > > 1. .ocamlinit in the current directory; > 2. XDG_CONFIG_HOME/ocaml/init.ml, if XDG_CONFIG_HOME is an absolute path; > 3. otherwise, on Unix, HOME/ocaml/init.ml or, on Windows, ocaml\\init.ml under LocalAppData (e.g. C:\\Users\\Bactrian\\AppData\\Local\\ocaml\\init.ml); > 4. ocaml/init.ml under any of the absolute paths in XDG_CONFIG_DIRS. Paths in XDG_CONFIG_DIRS are colon-delimited on Unix, and semicolon-delimited on Windows; > 5. if XDG_CONFIG_DIRS contained no absolute paths, /usr/xdg/ocaml/init.ml on Unix or, ocaml\\init.ml under any of LocalAppData (e.g. C:\\Users\\Bactrian\\AppData\\Local), RoamingAppData (e.g. C:\\Users\\Bactrian\\AppData\\Roaming), or ProgramData (e.g. C:\\ProgramData) on Windows; > 6. HOME/.ocamlinit, if HOME is non-empty; > > The toplevel system does not perform line editing, but it can easily be used in conjunction with an external line editor such as ledit, or rlwrap. An improved toplevel, utop, is also available. Another option is to use ocaml under Gnu Emacs, which gives the full editing power of Emacs (command run-caml from library inf-caml). > > At any point, the parsing, compilation or evaluation of the current phrase can be interrupted by pressing ctrl-C (or, more precisely, by sending the INTR signal to the ocaml process). The toplevel then immediately returns to the # prompt. > > If scriptfile is given on the command-line to ocaml, the toplevel system enters script mode: the contents of the file are read as a sequence of OCaml phrases and executed, as per the #use directive (section ‍[14.2](#s%3Atoplevel-directives)). The outcome of the evaluation is not printed. On reaching the end of file, the ocaml command exits immediately. No commands are read from standard input. Sys.argv is transformed, ignoring all OCaml parameters, and starting with the script file name in Sys.argv.(0). > > In script mode, the first line of the script is ignored if it starts with #!. Thus, it should be possible to make the script itself executable and put as first line #!/usr/local/bin/ocaml, thus calling the toplevel system automatically when the script is run. However, ocaml itself is a #! script on most installations of OCaml, and Unix kernels usually do not handle nested #! scripts. A better solution is to put the following as the first line of the script: > > #!/usr/local/bin/ocamlrun /usr/local/bin/ocaml
## 1 Options The following command-line options are recognized by the ocaml command. -absname Force error messages to show absolute paths for file names. -no-absname Do not try to show absolute filenames in error messages. -args filename Read additional newline-terminated command line arguments from filename. It is not possible to pass a scriptfile via file to the toplevel. -args0 filename Read additional null character terminated command line arguments from filename. It is not possible to pass a scriptfile via file to the toplevel. -I directory Add the given directory to the list of directories searched for source and compiled files. By default, the current directory is searched first, then the standard library directory. Directories added with -I are searched after the current directory, in the order in which they were given on the command line, but before the standard library directory. See also option -nostdlib. If the given directory starts with +, it is taken relative to the standard library directory. For instance, -I +unix adds the subdirectory unix of the standard library to the search path. Directories can also be added to the list once the toplevel is running with the #directory directive (section ‍[14.2](#s%3Atoplevel-directives)). -init file Load the given file instead of the default initialization file. The default initialization file is the first found of: 1. .ocamlinit in the current directory; 2. XDG_CONFIG_HOME/ocaml/init.ml, if XDG_CONFIG_HOME is an absolute path;
## 1 Options 3. otherwise, on Unix, HOME/ocaml/init.ml or, on Windows, ocaml\\init.ml under LocalAppData (e.g. C:\\Users\\Bactrian\\AppData\\Local\\ocaml\\init.ml); 4. ocaml/init.ml under any of the absolute paths in XDG_CONFIG_DIRS. Paths in XDG_CONFIG_DIRS are colon-delimited on Unix, and semicolon-delimited on Windows; 5. if XDG_CONFIG_DIRS contained no absolute paths, /usr/xdg/ocaml/init.ml on Unix or, ocaml\\init.ml under any of LocalAppData (e.g. C:\\Users\\Bactrian\\AppData\\Local), RoamingAppData (e.g. C:\\Users\\Bactrian\\AppData\\Roaming), or ProgramData (e.g. C:\\ProgramData) on Windows; 6. HOME/.ocamlinit, if HOME is non-empty; -labels Labels are not ignored in types, labels may be used in applications, and labelled parameters can be given in any order. This is the default. -no-app-funct Deactivates the applicative behaviour of functors. With this option, each functor application generates new types in its result and applying the same functor twice to the same argument yields two incompatible structures. -noassert Do not compile assertion checks. Note that the special form assert false is always compiled because it is typed specially. -nolabels Ignore non-optional labels in types. Labels cannot be used in applications, and parameter order becomes strict. -noprompt Do not display any prompt when waiting for input. -nopromptcont Do not display the secondary prompt when waiting for continuation lines in multi-line inputs. This should be used e.g. when running ocaml in an emacs window.
## 1 Options -nostdlib Do not include the standard library directory in the list of directories searched for source and compiled files. -ppx command After parsing, pipe the abstract syntax tree through the preprocessor command. The module Ast_mapper, described in 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. -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.
## 1 Options -short-paths When a type is visible under several module-paths, use the shortest one when printing the type’s name in inferred interfaces and error and warning messages. Identifier names starting with an underscore \_ or containing double underscores \_\_ incur a penalty of +10 when computing their length. -stdin Read the standard input as a script file rather than starting an interactive session. -strict-sequence Force the left-hand part of each sequence to have type unit. -strict-formats Reject invalid formats that were accepted in legacy format implementations. You should use this flag to detect and fix such invalid formats, as they will be rejected by future OCaml versions. -unsafe Turn bound checking off for array and string accesses (the v.(i) and s.\[i\] constructs). Programs compiled with -unsafe are therefore faster, but unsafe: anything can happen if the program accesses an array or string outside of its bounds. -unsafe-string Identify the types string and bytes, thereby making strings writable. This is intended for compatibility with old source code and should not be used with new software. This option raises an error unconditionally since OCaml 5.0. -v Print the version number of the compiler and the location of the standard library directory, then exit. -verbose Print all external commands before they are executed, Useful to debug C library problems. -version Print version string and exit. -vnum Print short version number and exit. -no-version Do not print the version banner at startup.
## 1 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.
## 1 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.
## 1 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)
## 1 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)
## 1 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.
## 1 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 -help. Note that warnings 5 and 10 are not always triggered, depending on the internals of the type checker. -warn-error warning-list Mark as fatal the warnings specified in the argument warning-list. The compiler will stop with an error when one of these warnings is emitted. The warning-list has the same meaning as for the -w option: a + sign (or an uppercase letter) marks the corresponding warnings as fatal, a - sign (or a lowercase letter) turns them back into non-fatal warnings, and a @ sign both enables and marks as fatal the corresponding warnings. Note: it is not recommended to use warning sets (i.e. letters) as arguments to -warn-error in production code, because this can break your build when future versions of OCaml add some new warnings. The default setting is -warn-error -a (no warning is fatal). -warn-help Show the description of all available warning numbers. - file Use file as a script file name, even when it starts with a hyphen (-). -help or --help Display a short usage summary and exit.
## 1 Options > Unix:  The following environment variables are also consulted: > > OCAMLTOP_INCLUDE_PATH > Additional directories to search for compiled object code files (.cmi, .cmo and .cma). The specified directories are considered from left to right, after the include directories specified on the command line via -I have been searched. Available since OCaml 4.08. > > OCAMLTOP_UTF_8 > When printing string values, non-ascii bytes ( \> \\0x7E ) are printed as decimal escape sequence if OCAMLTOP_UTF_8 is set to false. Otherwise, they are printed unescaped. > > TERM > When printing error messages, the toplevel system attempts to underline visually the location of the error. It consults the TERM variable to determines the type of output terminal and look up its capabilities in the terminal database. > > XDG_CONFIG_HOME, HOME, XDG_CONFIG_DIRS > Initialization file lookup procedure (see above).
## 2 Toplevel directives The following directives control the toplevel behavior, load files in memory, and trace program execution. Note: all directives start with a # (sharp) symbol. This # must be typed before the directive, and must not be confused with the # prompt displayed by the interactive loop. For instance, typing #quit;; will exit the toplevel loop, but typing quit;; will result in an “unbound value quit” error. General #help;; Prints a list of all available directives, with corresponding argument type if appropriate. #quit;; Exit the toplevel loop and terminate the ocaml command. Loading codes #cd "dir-name";; Change the current working directory. #directory "dir-name";; Add the given directory to the list of directories searched for source and compiled files. #remove_directory "dir-name";; Remove the given directory from the list of directories searched for source and compiled files. Do nothing if the list does not contain the given directory. #load "file-name";; Load in memory a bytecode object file (.cmo file) or library file (.cma file) produced by the batch compiler ocamlc. #load_rec "file-name";; Load in memory a bytecode object file (.cmo file) or library file (.cma file) produced by the batch compiler ocamlc. When loading an object file that depends on other modules which have not been loaded yet, the .cmo files for these modules are searched and loaded as well, recursively. The loading order is not specified.
## 2 Toplevel directives #use "file-name";; Read, compile and execute source phrases from the given file. This is textual inclusion: phrases are processed just as if they were typed on standard input. The reading of the file stops at the first error encountered. #use_output "command";; Execute a command and evaluate its output as if it had been captured to a file and passed to #use. #mod_use "file-name";; Similar to #use but also wrap the code into a top-level module of the same name as capitalized file name without extensions, following semantics of the compiler. For directives that take file names as arguments, if the given file name specifies no directory, the file is searched in the following directories: 1. In script mode, the directory containing the script currently executing; in interactive mode, the current working directory. 2. Directories added with the #directory directive. 3. Directories given on the command line with -I options. 4. The standard library directory. Environment queries #show_class class-path;; #show_class_type class-path;; #show_exception ident;; #show_module module-path;; #show_module_type modtype-path;; #show_type typeconstr;; #show_val value-path;; Print the signature of the corresponding component. #show ident;; Print the signatures of components with name ident in all the above categories.
## 2 Toplevel directives Pretty-printing #install_printer printer-name;; This directive registers the function named printer-name (a value path) as a printer for values whose types match the argument type of the function. That is, the toplevel loop will call printer-name when it has such a value to print. The printing function printer-name should have type Format.formatter -> t -> unit, where t is the type for the values to be printed, and should output its textual representation for the value of type t on the given formatter, using the functions provided by the Format library. For backward compatibility, printer-name can also have type t -> unit and should then output on the standard formatter, but this usage is deprecated. #print_depth n;; Limit the printing of values to a maximal depth of n. The parts of values whose depth exceeds n are printed as ... (ellipsis). #print_length n;; Limit the number of value nodes printed to at most n. Remaining parts of values are printed as ... (ellipsis). #remove_printer printer-name;; Remove the named function from the table of toplevel printers. Tracing #trace function-name;; After executing this directive, all calls to the function named function-name will be “traced”. That is, the argument and the result are displayed for each call, as well as the exceptions escaping out of the function, raised either by the function itself or by another function it calls. If the function is curried, each argument is printed as it is passed to the function. #untrace function-name;; Stop tracing the given function.
## 2 Toplevel directives #untrace_all;; Stop tracing all functions traced so far. Compiler options #debug bool;; Turn on/off the insertion of debugging events. Default is true. #labels bool;; Ignore labels in function types if argument is false, or switch back to default behaviour (commuting style) if argument is true. #ppx "file-name";; After parsing, pipe the abstract syntax tree through the preprocessor command. #principal bool;; If the argument is true, check information paths during type-checking, to make sure that all types are derived in a principal way. If the argument is false, do not check information paths. #rectypes;; Allow arbitrary recursive types during type-checking. Note: once enabled, this option cannot be disabled because that would lead to unsoundness of the type system. #warn_error "warning-list";; Treat as errors the warnings enabled by the argument and as normal warnings the warnings disabled by the argument. #warnings "warning-list";; Enable or disable warnings according to the argument.
## 3 The toplevel and the module system Toplevel phrases can refer to identifiers defined in compilation units with the same mechanisms as for separately compiled units: either by using qualified names (Modulename.localname), or by using the open construct and unqualified names (see section ‍[11.3](names.html#s%3Anames)). However, before referencing another compilation unit, an implementation of that unit must be present in memory. At start-up, the toplevel system contains implementations for all the modules in the the standard library. Implementations for user modules can be entered with the #load directive described above. Referencing a unit for which no implementation has been provided results in the error Reference to undefined global \`...'. Note that entering open Mod merely accesses the compiled interface (.cmi file) for Mod, but does not load the implementation of Mod, and does not cause any error if no implementation of Mod has been loaded. The error “reference to undefined global Mod” will occur only when executing a value or module definition that refers to Mod.
## 4 Common errors This section describes and explains the most frequently encountered error messages. Cannot find file filename The named file could not be found in the current directory, nor in the directories of the search path. If filename has the format mod.cmi, this means you have referenced the compilation unit mod, but its compiled interface could not be found. Fix: compile mod.mli or mod.ml first, to create the compiled interface mod.cmi. If filename has the format mod.cmo, this means you are trying to load with #load a bytecode object file that does not exist yet. Fix: compile mod.ml first. If your program spans several directories, this error can also appear because you haven’t specified the directories to look into. Fix: use the #directory directive to add the correct directories to the search path. This expression has type t<sub>1</sub>, but is used with type t<sub>2</sub> See section ‍[13.4](comp.html#s%3Acomp-errors). Reference to undefined global mod You have neglected to load in memory an implementation for a module with #load. See section ‍[14.3](#s%3Atoplevel-modules) above.
## 5 Building custom toplevel systems: ocamlmktop The ocamlmktop command builds OCaml toplevels that contain user code preloaded at start-up. The ocamlmktop command takes as argument a set of .cmo and .cma files, and links them with the object files that implement the OCaml toplevel. The typical use is: ocamlmktop -o mytoplevel foo.cmo bar.cmo gee.cmo This creates the bytecode file mytoplevel, containing the OCaml toplevel system, plus the code from the three .cmo files. This toplevel is directly executable and is started by: ./mytoplevel This enters a regular toplevel loop, except that the code from foo.cmo, bar.cmo and gee.cmo is already loaded in memory, just as if you had typed: #load "foo.cmo";; #load "bar.cmo";; #load "gee.cmo";; on entrance to the toplevel. The modules Foo, Bar and Gee are not opened, though; you still have to do open Foo;; yourself, if this is what you wish.
### 5.1 Options The following command-line options are recognized by ocamlmktop. -cclib libname Pass the -llibname option to the C linker when linking in “custom runtime” mode. See the corresponding option for ocamlc, in chapter ‍[13](comp.html#c%3Acamlc). -ccopt option Pass the given option to the C compiler and linker, when linking in “custom runtime” mode. See the corresponding option for ocamlc, in chapter ‍[13](comp.html#c%3Acamlc). -custom Link in “custom runtime” mode. See the corresponding option for ocamlc, in chapter ‍[13](comp.html#c%3Acamlc). -I directory Add the given directory to the list of directories searched for compiled object code files (.cmo and .cma). -o exec-file Specify the name of the toplevel file produced by the linker. The default is a.out.
## 6 The native toplevel: ocamlnat (experimental) This section describes a tool that is not yet officially supported but may be found useful. OCaml code executing in the traditional toplevel system uses the bytecode interpreter. When increased performance is required, or for testing programs that will only execute correctly when compiled to native code, the *native toplevel* may be used instead. For the majority of installations the native toplevel will not have been installed along with the rest of the OCaml toolchain. In such circumstances it will be necessary to build the OCaml distribution from source. From the built source tree of the distribution you may use make natruntop to build and execute a native toplevel. (Alternatively make ocamlnat can be used, which just performs the build step.) If the make install command is run after having built the native toplevel then the ocamlnat program (either from the source or the installation directory) may be invoked directly rather than using make natruntop. ------------------------------------------------------------------------ [« Batch compilation (ocamlc)](comp.html)[The runtime system (ocamlrun) »](runtime.html) Copyright © 2024 Institut National de Recherche en Informatique et en Automatique ------------------------------------------------------------------------