This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B.

**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like `Bytes.t[28.8]` mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable.

The labeled version of this module can be used as described in the `StdLabels`[28.52] module.

## Strings

### type t = string

The type for strings.

### val make : int -> char -> string

`make n c` is a string of length `n` with each index holding the character `c`.

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_string_length[28.55]`.

### val init : int -> (int -> char) -> string

`init n f` is a string of length `n` with index `i` holding the character `f` (called in increasing index order).

**Since:** 4.02

**Raises** `Invalid_argument` if `n < 0` or `n > Sys.max_string_length[28.55]`.

### val empty : string

The empty string.

**Since:** 4.13

### val length : string -> int

`length s` is the length (number of bytes/characters) of `s`.

### val get : string -> int -> char

`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`.

**Raises** `Invalid_argument` if `i` not an index of `s`.

### val of_bytes : bytes -> string

Return a new string that contains the same bytes as the given byte sequence.

**Since:** 4.13

### val to_bytes : string -> bytes

Return a new byte sequence that contains the same bytes as the given string.

**Since:** 4.13

### val blit : string -> int -> bytes -> int -> int -> unit

Same as `Bytes.blit_string[28.8]` which should be preferred.
val protect : t -> (unit -> 'a) -> 'a

protect mutex f runs f() in a critical section where mutex is locked (using
Mutex.lock[29.38]); it then takes care of releasing mutex, whether f() returned a value or
raised an exception.

The unlocking operation is guaranteed to always takes place, even in the event an
asynchronous exception (e.g. Sys.Break[29.60]) is raised in some signal handler.

Since: 5.1

29.39 Module Nativeint : Processor-native integers.

This module provides operations on the type *nativeint* of signed 32-bit integers (on 32-bit platforms) or signed 64-bit integers (on 64-bit platforms). This integer type has exactly the same width as that of a pointer type in the C compiler. All arithmetic operations over *nativeint* are taken modulo $2^{32}$ or $2^{64}$ depending on the word size of the architecture.

Performance notice: values of type *nativeint* occupy more memory space than values of type *int*, and arithmetic operations on *nativeint* are generally slower than those on *int*. Use *nativeint* only when the application requires the extra bit of precision over the *int* type.

Literals for native integers are suffixed by n:

let zero: nativeint = 0n
let one: nativeint = 1n
let m_one: nativeint = -1n

val zero : nativeint

The native integer 0.

val one : nativeint

The native integer 1.

val minus_one : nativeint

The native integer -1.

val neg : nativeint -> nativeint

Unary negation.

val add : nativeint -> nativeint -> nativeint

Addition.

val sub : nativeint -> nativeint -> nativeint

Subtraction.

val mul : nativeint -> nativeint -> nativeint
Multiplication.

val div : nativeint -> nativeint -> nativeint

Integer division. This division rounds the real quotient of its arguments towards zero, as specified for (`/`)[28.2].

**Raises** `Division_by_zero` if the second argument is zero.

val unsigned_div : nativeint -> nativeint -> nativeint

Same as `Nativeint.div`[29.39], except that arguments and result are interpreted as *unsigned* native integers.

**Since:** 4.08

val rem : nativeint -> nativeint -> nativeint

Integer remainder. If `y` is not zero, the result of `Nativeint.rem x y` satisfies the following properties: `Nativeint.zero <= Nativeint.rem x y < Nativeint abs y` and `x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y) (Nativeint.rem x y)`. If `y = 0`, `Nativeint.rem x y` raises `Division_by_zero`.

val unsigned/rem : nativeint -> nativeint -> nativeint

Same as `Nativeint.rem`[29.39], except that arguments and result are interpreted as *unsigned* native integers.

**Since:** 4.08

val succ : nativeint -> nativeint

Successor. `Nativeint.succ x` is `Nativeint.add x Nativeint.one`.

val pred : nativeint -> nativeint

Predecessor. `Nativeinteelrem` x is `Nativeint.sub x Nativeint.one`.

val abs : nativeint -> nativeint

`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative.

val size : int

The size in bits of a native integer. This is equal to 32 on a 32-bit platform and to 64 on a 64-bit platform.

val max_int : nativeint

The greatest representable native integer, either $2^{31} - 1$ on a 32-bit platform, or $2^{63} - 1$ on a 64-bit platform.

val min_int : nativeint

The smallest representable native integer, either $-2^{31}$ on a 32-bit platform, or $-2^{63}$ on a 64-bit platform.
## Extracting substrings

`val sub : string -> int -> int -> string`

`sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`.

**Raises** `Invalid_argument` if `pos` and `len` do not designate a valid substring of `s`.

`val split_on_char : char -> string -> string list`

`split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`.

The function's result is specified by the following invariants:

* The list is not empty.

* Concatenating its elements using `sep` as a separator returns a string equal to the input `(concat (make 1 sep) (split_on_char sep s) = s)`.

* No string in the result contains the `sep` character.

**Since:** 4.04 (4.05 in `StringLabels`)

## Transforming

`val map : (char -> char) -> string -> string`

`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order.

**Since:** 4.00

`val mapi : (int -> char -> char) -> string -> string`

`mapi f s` is like `String.map[28.53]` but the index of the character is also passed to `f`.

**Since:** 4.02

`val fold_left : ('acc -> char -> 'acc) -> 'acc -> string -> 'acc`

`fold_left f x s` computes `f (...) (f (f x s.[0]) s.[1]) ... s.[n-1]`, where `n` is the length of the string `s`.

**Since:** 4.13

`val fold_right : (char -> 'acc -> 'acc) -> string -> 'acc -> 'acc`

`fold_right f s x` computes `f s.[0] (f s.[1] (...) (f s.[n-1] x) ... )`, where `n` is the length of the string `s`.

**Since:** 4.13

`val for_all : (char -> bool) -> string -> bool`

`for_all p s` checks if all characters in `s` satisfy the predicate `p`.

**Since:** 4.13
val logand : nativeint -> nativeint -> nativeint
Bitwise logical and.

val logor : nativeint -> nativeint -> nativeint
Bitwise logical or.

val logxor : nativeint -> nativeint -> nativeint
Bitwise logical exclusive or.

val lognot : nativeint -> nativeint
Bitwise logical negation.

val shift_left : nativeint -> int -> nativeint
Nativeint.shift_left x y shifts x to the left by y bits. The result is unspecified if y < 0 or y >= bitsize, where bitsize is 32 on a 32-bit platform and 64 on a 64-bit platform.

val shift_right : nativeint -> int -> nativeint
Nativeint.shift_right x y shifts x to the right by y bits. This is an arithmetic shift: the sign bit of x is replicated and inserted in the vacated bits. The result is unspecified if y < 0 or y >= bitsize.

val shift_right_logical : nativeint -> int -> nativeint
Nativeint.shift_right_logical x y shifts x to the right by y bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of x. The result is unspecified if y < 0 or y >= bitsize.

val of_int : int -> nativeint
Convert the given integer (type *int*) to a native integer (type *nativeint*).

val to_int : nativeint -> int
Convert the given native integer (type *nativeint*) to an integer (type *int*). The high-order bit is lost during the conversion.

val unsigned_to_int : nativeint -> int option
Same as Nativeint.to_int[29.39], but interprets the argument as an *unsigned* integer.
Returns None if the unsigned value of the argument cannot fit into an *int*.

Since: 4.08

val of_float : float -> nativeint
Convert the given floating-point number to a native integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range [Nativeint.min_int[29.39], Nativeint.max_int[29.39]], no exception is raised, and an unspecified, platform-dependent integer is returned.
### `val to_float`: `nativeint` -> `float`

Convert the given native integer to a floating-point number.

### `val of_int32`: `int32` -> `nativeint`

Convert the given 32-bit integer (type `int32`) to a native integer.

### `val to_int32`: `nativeint` -> `int32`

Convert the given native integer to a 32-bit integer (type `int32`). On 64-bit platforms, the 64-bit native integer is taken modulo $2^{32}$, i.e. the top 32 bits are lost. On 32-bit platforms, the conversion is exact.

### `val of_string`: `string` -> `nativeint`

Convert the given string to a native integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively.

The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Nativeint.max_int+1]`. If the input exceeds `Nativeint.max_int` [29.39] it is converted to the signed integer `Int64.min_int + input - Nativeint.max_int - 1`.

**Raises** `Failure` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `nativeint`.

### `val of_string_opt`: `string` -> `nativeint` option

Same as `of_string`, but return `None` instead of raising.

**Since:** 4.05

### `val to_string`: `nativeint` -> `string`

Return the string representation of its argument, in decimal.

### `type t = nativeint`

An alias for the type of native integers.

### `val compare`: `t` -> `t` -> `int`

The comparison function for native integers, with the same specification as `compare` [28.2]. Along with the type `t`, this function `compare` allows the module `Nativeint` to be passed as argument to the functors `Set.Make` [29.54] and `Map.Make` [29.35].

### `val unsigned_compare`: `t` -> `t` -> `int`

Same as `Nativeint compares` [29.39], except that arguments are interpreted as unsigned native integers.

**Since:** 4.08

### `val equal`: `t` -> `t` -> `bool`
## Traversing

val iter : (char -> unit) -> string -> unit

iter f s applies function f in turn to all the characters of s. It is equivalent to f s.[0]; f s.[1]; ...; f s.[length s - 1]; ().

val iteri : (int -> char -> unit) -> string -> unit

iteri is like String.iter[28.53], but the function is also given the corresponding character index.

Since: 4.00

## Searching

val index_from : string -> int -> char -> int

index_from s i c is the index of the first occurrence of c in s after position i.

### Raises

* Not_found if c does not occur in s after position i.

* Invalid_argument if i is not a valid position in s.

val index_from_opt : string -> int -> char -> int option

index_from_opt s i c is the index of the first occurrence of c in s after position i (if any).

Since: 4.05

Raises Invalid_argument if i is not a valid position in s.

val rindex_from : string -> int -> char -> int

rindex_from s i c is the index of the last occurrence of c in s before position i+1.

### Raises

* Not_found if c does not occur in s before position i+1.

* Invalid_argument if i+1 is not a valid position in s.

val rindex_from_opt : string -> int -> char -> int option

rindex_from_opt s i c is the index of the last occurrence of c in s before position i+1 (if any).

Since: 4.05

Raises Invalid_argument if i+1 is not a valid position in s.

val index : string -> char -> int

index s c is String.index_from[28.53] s 0 c.

val index_opt : string -> char -> int option
The equal function for native ints.

Since: 4.03

val min : t -> t -> t

Return the smaller of the two arguments.

Since: 4.13

val max : t -> t -> t

Return the greater of the two arguments.

Since: 4.13

val seeded_hash : int -> t -> int

A seeded hash function for native ints, with the same output value as
`Hashtbl.seeded_hash[29.26]`. This function allows this module to be passed as argument to
the functor `Hashtbl.MakeSeeded[29.26]`.

Since: 5.1

val hash : t -> int

An unseeded hash function for native ints, with the same output value as
`Hashtbl.hash[29.26]`. This function allows this module to be passed as argument to the
functor `Hashtbl.Make[29.26]`.

Since: 5.1

## 29.40 Module Oo : Operations on objects

val copy : (< .. > as 'a) -> 'a

`Oo.copy` `o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`.

**Alert unsynchronized_access.** Unsynchronized accesses to mutable objects are a programming error.

val id : < .. > -> int

Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures.
index_opt s c is String.index_from_opt[28.53] s 0 c.

Since: 4.05

val rindex : string -> char -> int

rindex s c is String.rindex_from[28.53] s (length s - 1) c.

val rindex_opt : string -> char -> int option

rindex_opt s c is String.rindex_from_opt[28.53] s (length s - 1) c.

Since: 4.05

## Strings and Sequences

val to_seq : t -> char Seq.t

to_seq s is a sequence made of the string's characters in increasing order. In "unsafe-string" mode, modifications of the string during iteration will be reflected in the sequence.

Since: 4.07

val to_seqi : t -> (int * char) Seq.t

to_seqi s is like String.to_seq[28.53] but also tuples the corresponding index.

Since: 4.07

val of_seq : char Seq.t -> t

of_seq s is a string made of the sequence's characters.

Since: 4.07

## UTF decoding and validations

### UTF-8

val get_utf_8_uchar : t -> int -> Uchar.utf_decode

get_utf_8_uchar b i decodes an UTF-8 character at index i in b.

val is_valid_utf_8 : t -> bool

is_valid_utf_8 b is true if and only if b contains valid UTF-8 data.

### UTF-16BE

val get_utf_16be_uchar : t -> int -> Uchar.utf_decode

get_utf_16be_uchar b i decodes an UTF-16BE character at index i in b.

val is_valid_utf_16be : t -> bool

is_valid_utf_16be b is true if and only if b contains valid UTF-16BE data.
## 29.41 Module Option : Option values.

Option values explicitly indicate the presence or absence of a value.

**Since: 4.08**

### Options

```hkl
type 'a t = 'a option =
```

| None

| Some of 'a

The type for option values. Either `None` or a value `Some v`.

```hkl
val none : 'a option
```

```
none is None.
```

```hkl
val some : 'a -> 'a option
```

```
some v is Some v.
```

```hkl
val value : 'a option -> default:'a -> 'a
```

```
value o ~default is v if o is Some v and default otherwise.
```

```hkl
val get : 'a option -> 'a
```

```
get o is v if o is Some v and raise otherwise.
```

```
Raises Invalid_argument if o is None.
```

```hkl
val bind : 'a option -> ('a -> 'b option) -> 'b option
```

```
bind o f is f v if o is Some v and None if o is None.
```

```hkl
val join : 'a option -> 'a option
```

```
join oo is Some v if oo is Some (Some v) and None otherwise.
```

```hkl
val map : ('a -> 'b) -> 'a option -> 'b option
```

```
map f o is None if o is None and Some (f v) if o is Some v.
```

```hkl
val fold : none:'a -> some:( 'b -> 'a) -> 'b option -> 'a
```

```
fold ~none ~some o is none if o is None and some v if o is Some v.
```

```hkl
val iter : ('a -> unit) -> 'a option -> unit
```

```
iter f o is f v if o is Some v and () otherwise.
```
## UTF-16LE

val get_utf_16le_uchar: t -> int -> Uchar.utf_decode

get_utf_16le_uchar b i decodes an UTF-16LE character at index i in b.

val is_valid_utf_16le: t -> bool

is_valid_utf_16le b is true if and only if b contains valid UTF-16LE data.

## Binary decoding of integers

The functions in this section binary decode integers from strings.

All following functions raise Invalid_argument if the characters needed at index i to decode the integer are not available.

Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on Sys.big_endian[28.55].

32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.

8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values.

val get_uint8: string -> int -> int

get_uint8 b i is b's unsigned 8-bit integer starting at character index i.

Since: 4.13

val get_int8: string -> int -> int

get_int8 b i is b's signed 8-bit integer starting at character index i.

Since: 4.13

val get_uint16_ne: string -> int -> int

get_uint16_ne b i is b's native-endian unsigned 16-bit integer starting at character index i.

Since: 4.13

val get_uint16_be: string -> int -> int

get_uint16_be b i is b's big-endian unsigned 16-bit integer starting at character index i.

Since: 4.13

val get_uint16_le: string -> int -> int

get_uint16_le b i is b's little-endian unsigned 16-bit integer starting at character index i.

Since: 4.13

val get_int16_ne: string -> int -> int
Predicates and comparisons

val is_none : 'a option -> bool
is_none o is true if and only if o is None.

val is_some : 'a option -> bool
is_some o is true if and only if o is Some o.

val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool
equal eq o0 o1 is true if and only if o0 and o1 are both None or if they are Some v0 and
Some v1 and eq v0 v1 is true.

val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int
compare cmp o0 o1 is a total order on options using cmp to compare values wrapped by
Some _ . None is smaller than Some _ values.

Converting

val to_result : none:'e -> 'a option -> ('a, 'e) result
to_result ~none o is Ok v if o is Some v and Error none otherwise.

val to_list : 'a option -> 'a list
to_list o is [] if o is None and [v] if o is Some v.

val to_seq : 'a option -> 'a Seq.t
to_seq o is o as a sequence. None is the empty sequence and Some v is the singleton
sequence containing v.

29.42 Module Out_channel : Output channels.

This module provides functions for working with output channels.

See the example section[29.48] below.

Since: 4.14

Channels

type t = out_channel
The type of output channel.

type open_flag = open_flag =
| Open_rdonly
open for reading.
`get_int16_ne` b i is b's native-endian signed 16-bit integer starting at character index i.

Since: 4.13

`val get_int16_be : string -> int -> int`

`get_int16_be` b i is b's big-endian signed 16-bit integer starting at character index i.

Since: 4.13

`val get_int16_le : string -> int -> int`

`get_int16_le` b i is b's little-endian signed 16-bit integer starting at character index i.

Since: 4.13

`val get_int32_ne : string -> int -> int32`

`get_int32_ne` b i is b's native-endian 32-bit integer starting at character index i.

Since: 4.13

`val hash : t -> int`

An unseeded hash function for strings, with the same output value as `Hashtbl.hash` [28.24]. This function allows this module to be passed as argument to the functor `Hashtbl.Make` [28.24].

Since: 5.0

`val seeded_hash : int -> t -> int`

A seeded hash function for strings, with the same output value as `Hashtbl.seeded_hash` [28.24]. This function allows this module to be passed as argument to the functor `Hashtbl.MakeSeeded` [28.24].

Since: 5.0

`val get_int32_be : string -> int -> int32`

`get_int32_be` b i is b's big-endian 32-bit integer starting at character index i.

Since: 4.13

`val get_int32_le : string -> int -> int32`

`get_int32_le` b i is b's little-endian 32-bit integer starting at character index i.

Since: 4.13

`val get_int64_ne : string -> int -> int64`

`get_int64_ne` b i is b's native-endian 64-bit integer starting at character index i.

Since: 4.13

`val get_int64_be : string -> int -> int64`

`get_int64_be` b i is b's big-endian 64-bit integer starting at character index i.

Since: 4.13
| Open_wronly

open for writing.

| Open_append

open for appending: always write at end of file.

| Open_creat

create the file if it does not exist.

| Open_trunc

empty the file if it already exists.

| Open_excl

fail if Open_creat and the file already exists.

| Open_binary

open in binary mode (no conversion).

| Open_text

open in text mode (may perform conversions).

| Open_nonblock

open in non-blocking mode.

Opening modes for `Out_channel.open_gen` [29.42].

val stdout : t

The standard output for the process.

val stderr : t

The standard error output for the process.

val open_bin : string -> t

Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists.

val open_text : string -> t

Same as `Out_channel.open_bin` [29.42], but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like `Out_channel.open_bin` [29.42].

val open_gen : open_flag list -> int -> string -> t

`open_gen` mode `perm` filename opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. `Out_channel.open_text` [29.42] and `Out_channel.open_bin` [29.42] are special cases of this function.
```h
val get_int64_le : string -> int -> int64
    get_int64_le b i is b's little-endian 64-bit integer starting at character index i.
    Since: 4.13
```

## 28.54 Module StringLabels : Strings.

A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters.

The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows.

<table><thead><tr><th>positions</th><th>0</th><th>1</th><th>2</th><th>3</th><th>4</th><th>n-1</th><th>n</th></tr></thead><tbody><tr><td></td><td>---</td><td>---</td><td>---</td><td>---</td><td>---</td><td>---</td><td>---</td></tr><tr><th>indices</th><td>0</td><td>1</td><td>2</td><td>3</td><td>...</td><td>n-1</td><td></td></tr></tbody></table>

* An *index* `i` of `s` is an integer in the range `[0; n-1]`. It represents the ith byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`.

* A *position* `i` of `s` is an integer in the range `[0; n]`. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The ith byte index is between position `i` and `i+1`.

Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`.

**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B.

**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like `Bytes.t[28.8]` mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable.

The labeled version of this module can be used as described in the StdLabels[28.52] module.

### Strings

```h
type t = string

The type for strings.
```

```h
val make : int -> char -> string

make n c is a string of length n with each index holding the character c.

Raises Invalid_argument if n < 0 or n > Sys.max_string_length[28.55].
```
val with_open_bin : string -> (t -> 'a) -> 'a

with_open_bin fn f opens a channel oc on file fn and returns f oc. After f returns, either
with a value or by raising an exception, oc is guaranteed to be closed.

val with_open_text : string -> (t -> 'a) -> 'a

Like Out_channel.with_open_bin[29.42], but the channel is opened in text mode (see
Out_channel.open_text[29.42]).

val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a

Like Out_channel.with_open_bin[29.42], but can specify the opening mode and file permission, in case the file must be created (see Out_channel.open_gen[29.42]).

val close : t -> unit

Close the given channel, flushing all buffered write operations. Output functions raise a
Sys_error exception when they are applied to a closed output channel, except
Out_channel.close[29.42] and Out_channel.flush[29.42], which do nothing when applied
to an already closed channel. Note that Out_channel.close[29.42] may raise Sys_error if
the operating system signals an error when flushing or closing.

val close_noerr : t -> unit

Same as Out_channel.close[29.42], but ignore all errors.

Output

val output_char : t -> char -> unit

Write the character on the given output channel.

val output_byte : t -> int -> unit

Write one 8-bit integer (as the single character with that code) on the given output channel.
The given integer is taken modulo 256.

val output_string : t -> string -> unit

Write the string on the given output channel.

val output_bytes : t -> bytes -> unit

Write the byte sequence on the given output channel.

Advanced output

val output : t -> bytes -> int -> int -> unit

output oc buf pos len writes len characters from byte sequence buf, starting at offset pos, to the given output channel oc.

Raises Invalid_argument if pos and len do not designate a valid range of buf.
val init : int -> f:(int -> char) -> string

init n ~f is a string of length n with index i holding the character f i (called in increasing
index order).

Since: 4.02

Raises Invalid_argument if n < 0 or n > Sys.max_string_length[28.55].

val empty : string

The empty string.

Since: 4.13

val length : string -> int

length s is the length (number of bytes/characters) of s.

val get : string -> int -> char

get s i is the character at index i in s. This is the same as writing s. [i].

Raises Invalid_argument if i not an index of s.

val of_bytes : bytes -> string

Return a new string that contains the same bytes as the given byte sequence.

Since: 4.13

val to_bytes : string -> bytes

Return a new byte sequence that contains the same bytes as the given string.

Since: 4.13

val blit :

src: string -> src_pos:int -> dst:bytes -> dst_pos:int -> len:int -> unit

Same as Bytes.blit_string[28.8] which should be preferred.

Concatenating

Note. The (^)[27.2] binary operator concatenates two strings.

val concat : sep:string -> string list -> string

concat ~sep ss concatenates the list of strings ss, inserting the separator string sep
between each.

Raises Invalid_argument if the result is longer than Sys.max_string_length[28.55] bytes.

val cat : string -> string -> string

cat s1 s2 concatenates s1 and s2 (s1 ~ s2).

Since: 4.13

Raises Invalid_argument if the result is longer than Sys.max_string_length[28.55] bytes.
`val output_substring : t -> string -> int -> int -> unit`

Same as `Out_channel.output[29.42]` but take a string as argument instead of a byte sequence.

`val output_bigarray :`

```
t ->
('a, Bigarray.int8_unsigned_elt, Bigarray.c_layout)
Bigarray Array1.t -> int -> int -> unit
```

Same as `Out_channel.output[29.42]` but take the data from a bigarray.

Since: 5.2

## Flushing

`val flush : t -> unit`

Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time.

`val flush_all : unit -> unit`

Flush all open output channels; ignore errors.

## Seeking

`val seek : t -> int64 -> unit`

`seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified.

`val pos : t -> int64`

Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results).

For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `Out_channel.pos[29.42]`, then going back to this position using `Out_channel.seek[29.42]` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode.

## Attributes

`val length : t -> int64`

Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless.
## Predicates and comparisons

val equal : t -> t -> bool

equal s0 s1 is true if and only if s0 and s1 are character-wise equal.

Since: 4.05

val compare : t -> t -> int

compare s0 s1 sorts s0 and s1 in lexicographical order. compare behaves like compare[27.2] on strings but may be more efficient.

val starts_with : prefix: string -> string -> bool

starts_with ~prefix s is true if and only if s starts with prefix.

Since: 4.13

val ends_with : suffix: string -> string -> bool

ends_with ~suffix s is true if and only if s ends with suffix.

Since: 4.13

val contains_from : string -> int -> char -> bool

contains_from s start c is true if and only if c appears in s after position start.

Raises Invalid_argument if start is not a valid position in s.

val rcontains_from : string -> int -> char -> bool

rcontains_from s stop c is true if and only if c appears in s before position stop+1.

Raises Invalid_argument if stop < 0 or stop+1 is not a valid position in s.

val contains : string -> char -> bool

contains s c is String.contains_from[28.53] s 0 c.

## Extracting substrings

val sub : string -> pos:int -> len:int -> string

sub s ~pos ~len is a string of length len, containing the substring of s that starts at position pos and has length len.

Raises Invalid_argument if pos and len do not designate a valid substring of s.

val split_on_char : sep:char -> string -> string list

split_on_char ~sep s is the list of all (possibly empty) substrings of s that are delimited by the character sep.

The function's result is specified by the following invariants:

* The list is not empty.
### `val set_binary_mode`: `t -> bool -> unit`

`set_binary_mode` oc true sets the channel oc to binary mode: no translations take place during output.

`set_binary_mode` oc false sets the channel oc to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`.

This function has no effect under operating systems that do not distinguish between text mode and binary mode.

### `val is_binary_mode`: `t -> bool`

`is_binary_mode` oc returns whether the channel oc is in binary mode (see `Out_channel.set_binary_mode[29.42]`).

**Since: 5.2**

### `val set_buffered`: `t -> bool -> unit`

`set_buffered` oc true sets the channel oc to *buffered* mode. In this mode, data output on oc will be buffered until either the internal buffer is full or the function `Out_channel.flush[29.42]` or `Out_channel.flush_all[29.42]` is called, at which point it will be sent to the output device.

`set_buffered` oc false sets the channel oc to *unbuffered* mode. In this mode, data output on oc will be sent to the output device immediately.

All channels are open in *buffered* mode by default.

### `val is_buffered`: `t -> bool`

`is_buffered` oc returns whether the channel oc is buffered (see `Out_channel.set_buffered[29.42]`).

### `val isatty`: `t -> bool`

`isatty` oc is true if oc refers to a terminal or console window, false otherwise.

**Since: 5.1**

## Examples

Writing the contents of a file:

```hkl
let write_file file s =
    Out_channel.with_open_bin file
    (fun oc -> Out_channel.output_string oc s))
```
* Concatenating its elements using `sep` as a separator returns a string equal to the input `(concat (make 1 sep) (split_on_char sep s) = s)`.

* No string in the result contains the `sep` character.

**Since:** 4.05

Transforming

val map : f:(char -> char) -> string -> string
map f s is the string resulting from applying f to all the characters of s in increasing order.

**Since:** 4.00

val mapi : f:(int -> char -> char) -> string -> string
mapi ~f s is like StringLabels.map[28.54] but the index of the character is also passed to f.

**Since:** 4.02

val fold_left : f:'acc -> char -> 'acc) -> init:'acc -> string -> 'acc
fold_left f x s computes f (... (f (f x s.[0]) s.[1]) ...) s.[n-1], where n is
the length of the string s.

**Since:** 4.13

val fold_right : f:(char -> 'acc -> 'acc) -> string -> init:'acc -> 'acc
fold_right f s x computes f s.[0] (f s.[1] (... (f s.[n-1] x) ...)), where n
is the length of the string s.

**Since:** 4.13

val for_all : f:(char -> bool) -> string -> bool
for_all p s checks if all characters in s satisfy the predicate p.

**Since:** 4.13

val exists : f:(char -> bool) -> string -> bool
exists p s checks if at least one character of s satisfies the predicate p.

**Since:** 4.13

val trim : string -> string
trim s is s without leading and trailing whitespace. Whitespace characters are: ' ',
'\x0C' (form feed), '\n', '\r', and '\t'.

**Since:** 4.00

val escaped : string -> string
## 29.43 Module Pair : Operations on pairs.

Since: 5.4

### Pairs

type ('a, 'b) t = 'a * 'b
The type for pairs.

val make : 'a -> 'b -> 'a * 'b
make a b is the pair (a, b).

val fst : 'a * 'b -> 'a
fst (a, b) is a.

val snd : 'a * 'b -> 'b
snd (a, b) is b.

val swap : 'a * 'b -> 'b * 'a
swap (a, b) is (b, a).

### Iterators

val fold : ('a -> 'b -> 'c) -> 'a * 'b -> 'c
fold f (a, b) applies f to a and b.

val map : ('a -> 'c) -> ('b -> 'd) -> 'a * 'b -> 'c * 'd
map f g (a, b) applies f to a and g to b.

val iter : ('a -> unit) -> ('b -> unit) -> 'a * 'b -> unit
iter f g (a, b) first applies f to a, and then g to b.

val map_fst : ('a -> 'c) -> 'a * 'b -> 'c * 'b
map_fst f p applies f to p's first component.

val map_snd : ('b -> 'c) -> 'a * 'b -> 'a * 'c
map_snd f p applies f to p's second component.
`escaped` s is s with special characters represented by escape sequences, following the lexical conventions of OCaml.

All characters outside the US-ASCII printable range `[0x20;0x7E]` are escaped, as well as backslash (`0x2F`) and double-quote (`0x22`).

The function `Scanf.unescaped` [28.47] is a left inverse of `escaped`, i.e. `Scanf.unescaped` (`escaped` s) = s for any string s (unless `escaped` s fails).

**Raises** `Invalid_argument` if the result is longer than `Sys.max_string_length` [28.55] bytes.

**val uppercase artii : string -> string**

`uppercase artii` s is s with all lowercase letters translated to uppercase, using the US-ASCII character set.

**Since:** 4.05

**val lowercase artii : string -> string**

`lowercase artii` s is s with all uppercase letters translated to lowercase, using the US-ASCII character set.

**Since:** 4.05

**val capitalize artii : string -> string**

`capitalize artii` s is s with the first character set to uppercase, using the US-ASCII character set.

**Since:** 4.05

**val un capital ize artii : string -> string**

`uncapitalize artii` s is s with the first character set to lowercase, using the US-ASCII character set.

**Since:** 4.05

Traversing

**val iter : f:(char -> unit) -> string -> unit**

`iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]`; `f s.[1]`; ...; `f s.[length s - 1]`; (`).`

**val iteri : f:(int -> char -> unit) -> string -> unit**

`iteri` is like `StringLabels.iter` [28.54], but the function is also given the corresponding character index.

**Since:** 4.00
Predicates and comparisons

val equal :

'a -> 'a -> bool) -> ('b -> 'b -> bool) -> 'a * 'b -> 'a * 'b -> bool
equal eqa eqb (a1, b1) (a2, b2) is true if and only if eqa a1 a2 and eqb b1 b2 are
both true.

val compare :

'a -> 'a -> int) -> ('b -> 'b -> int) -> 'a * 'b -> 'a * 'b -> int
compare cmpa cmpb is a total order on pairs using cmpa to compare the first component, and
cmpb to compare the second component. It is implemented by a lexicographic order.

29.44 Module Parsing : The run-time library for parsers generated by ocamlyacc.

val symbol_start : unit -> int

symbol_start and Parsing symbol_end[29.44] are to be called in the action part of a
grammar rule only. They return the offset of the string that matches the left-hand side of the
rule: symbol_start() returns the offset of the first character; symbol_end() returns the
offset after the last character. The first character in a file is at offset 0.

val symbol_end : unit -> int

See Parsing symbol_start [29.44].

val rhs_start : int -> int

Same as Parsing symbol_start [29.44] and Parsing symbol_end [29.44], but return the
offset of the string matching the nth item on the right-hand side of the rule, where n is the
integer parameter to rhs_start and rhs_end. n is 1 for the leftmost item.

val rhs_end : int -> int

See Parsing.rhs_start [29.44].

val symbol_start_pos : unit -> Lexing position

Same as symbol_start, but return a position instead of an offset.

val symbol_end_pos : unit -> Lexing position

Same as symbol_end, but return a position instead of an offset.

val rhs_start_pos : int -> Lexing position

Same as rhs_start, but return a position instead of an offset.

val rhs_end_pos : int -> Lexing position
Searching

val index_from : string -> int -> char -> int
index_from s i c is the index of the first occurrence of c in s after position i.

Raises

* Not_found if c does not occur in s after position i.

* Invalid_argument if i is not a valid position in s.

val index_from_opt : string -> int -> char -> int option
index_from_opt s i c is the index of the first occurrence of c in s after position i (if any).

Since: 4.05

Raises Invalid_argument if i is not a valid position in s.

val rindex_from : string -> int -> char -> int
rindex_from s i c is the index of the last occurrence of c in s before position i+1.

Raises

* Not_found if c does not occur in s before position i+1.

* Invalid_argument if i+1 is not a valid position in s.

val rindex_from_opt : string -> int -> char -> int option
rindex_from_opt s i c is the index of the last occurrence of c in s before position i+1 (if any).

Since: 4.05

Raises Invalid_argument if i+1 is not a valid position in s.

val index : string -> char -> int
index s c is String.index_from[28.53] s 0 c.

val index_opt : string -> char -> int option
index_opt s c is String.index_from_opt[28.53] s 0 c.

Since: 4.05

val rindex : string -> char -> int
rindex s c is String.rindex_from[28.53] s (length s - 1) c.

val rindex_opt : string -> char -> int option
rindex_opt s c is String.rindex_from_opt[28.53] s (length s - 1) c.

Since: 4.05
Same as `rhs_end`, but return a `position` instead of an offset.

`val clear_parser : unit -> unit`

Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs.

`exception Parse_error`

Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery.

`val set_trace : bool -> bool`

Control debugging support for `ocamlyacc-generated` parsers. After `Parsing.set_trace true`, the pushdown automaton that executes the parsers prints a trace of its actions (reading a token, shifting a state, reducing by a rule) on standard output. `Parsing.set_trace false` turns this debugging trace off. The boolean returned is the previous state of the trace flag.

**Since:** 3.11

## 29.45 Module Pqueue : Priority queues.

The `Pqueue` [29.45] module implements a data structure of priority queues, given a totally ordered type for elements. This is a mutable data structure. Both min- and max-priority queues are provided.

The implementation uses a heap stored in a dynamic array, and is therefore reasonably efficient: accessing the minimum (resp. maximum) element takes constant time, and insertion and removal take time logarithmic in the size of the priority queue. Note that `of_array` runs in linear time (and thus must be preferred to repeated insertions with `add`).

It is fine to have several elements with the same priority. Nothing is guaranteed regarding the order in which they will be popped. However, it is guaranteed that the element returned by `min_elt` (or `get_min_elt`) is the one that is removed from the priority queue by `pop_min` (or `remove_min`). This is important in many algorithms, (e.g. when peeking at several priority queues and then selecting one to remove from).

**Since:** 5.4

`module type OrderedType =`

`sig`

`type t`

The type of elements.

`val compare : t -> t -> int`
## Strings and Sequences

val to_seq : t -> char Seq.t

to_seq s is a sequence made of the string's characters in increasing order. In "unsafe-string" mode, modifications of the string during iteration will be reflected in the sequence.

Since: 4.07

val to_seqi : t -> (int * char) Seq.t

to_seqi s is like StringLabels.to_seq[28.54] but also tuples the corresponding index.

Since: 4.07

val of_seq : char Seq.t -> t

of_seq s is a string made of the sequence's characters.

Since: 4.07

## UTF decoding and validations

### UTF-8

val get_utf_8_uchar : t -> int -> Uchar.utf_decode

get_utf_8_uchar b i decodes an UTF-8 character at index i in b.

val is_valid_utf_8 : t -> bool

is_valid_utf_8 b is true if and only if b contains valid UTF-8 data.

### UTF-16BE

val get_utf_16be_uchar : t -> int -> Uchar.utf_decode

get_utf_16be_uchar b i decodes an UTF-16BE character at index i in b.

val is_valid_utf_16be : t -> bool

is_valid_utf_16be b is true if and only if b contains valid UTF-16BE data.

### UTF-16LE

val get_utf_16le_uchar : t -> int -> Uchar.utf_decode

get_utf_16le_uchar b i decodes an UTF-16LE character at index i in b.

val is_valid_utf_16le : t -> bool

is_valid_utf_16le b is true if and only if b contains valid UTF-16LE data.
A total ordering function to compare elements.

This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`.

The generic structural comparison function `compare[28.2]` is a suitable ordering function for element types such as `int` or `string`.

end

Input signature of the functors `Pqueue.MakeMin[29.45]` and `Pqueue.MakeMax[29.45]`.

module type Min =
sig

## Min-priority queues

type t

The type of priority queues.

type elt

The type of priority queue elements.

val create : unit -> t

Return a new priority queue, initially empty.

val length : t -> int

Return the number of elements in a priority queue.

val is_empty : t -> bool

`is_empty q` is true iff `q` is empty, that is, iff `length q = 0`.

val add : t -> elt -> unit

`add q x` adds the element `x` in the priority queue `q`.

val add_iter : t -> ((elt -> unit) -> 'x -> unit) -> 'x -> unit

`add_iter q iter x` adds each element of `x` to the end of `q`. This is `iter (add q) x`.

val min_elt : t -> elt option

`min_elt q` is an element of `q` with minimal priority or `None` if the queue is empty. The queue is not modified.

val get_min_elt : t -> elt
Binary decoding of integers

The functions in this section binary decode integers from strings.

All following functions raise Invalid_argument if the characters needed at index i to decode
the integer are not available.

Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are
stored first. Big-endian is also known as network byte order. Native-endian encoding is either
little-endian or big-endian depending on Sys.big_endian[28.55].

32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.

8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values.

val get_uint8 : string -> int -> int
get_uint8 b i is b's unsigned 8-bit integer starting at character index i.

Since: 4.13

val get_int8 : string -> int -> int
get_int8 b i is b's signed 8-bit integer starting at character index i.

Since: 4.13

val get_uint16_ne : string -> int -> int
get_uint16_ne b i is b's native-endian unsigned 16-bit integer starting at character index i.

Since: 4.13

val get_uint16_be : string -> int -> int
get_uint16_be b i is b's big-endian unsigned 16-bit integer starting at character index i.

Since: 4.13

val get_uint16_le : string -> int -> int
get_uint16_le b i is b's little-endian unsigned 16-bit integer starting at character index i.

Since: 4.13

val get_int16_ne : string -> int -> int
get_int16_ne b i is b's native-endian signed 16-bit integer starting at character index i.

Since: 4.13

val get_int16_be : string -> int -> int
get_int16_be b i is b's big-endian signed 16-bit integer starting at character index i.

Since: 4.13

val get_int16_le : string -> int -> int
`get_min_elt` `q` returns an element of `q` with minimal priority, or raises `Invalid_argument[28.2]` if the queue is empty. The queue is not modified.

**val pop_min : t -> elt option**

`pop_min` `q` removes and returns an element in queue `q` with minimal priority, or returns `None` if the queue is empty.

**val remove_min : t -> unit**

`remove_min` `q` removes an element in queue `q` with minimal priority. It does nothing if `q` is empty.

**val clear : t -> unit**

`clear` `q` removes all elements from `q`.

**val copy : t -> t**

`copy` `q` is a new priority queue with the same elements `q` has.

## Conversions from other data structures

**val of_array : elt array -> t**

`of_array` `a` returns a new priority queue containing the elements of array `a`. Runs in linear time.

**val of_list : elt list -> t**

`of_list` `l` returns a new priority queue containing the elements of list `l`. Runs in linear time.

**val of_iter : ((elt -> unit) -> 'x -> unit) -> 'x -> t**

`of_iter` `iter x` returns a new priority queue containing the elements of `x`, obtained from `iter`.

For example, `of_iter Seq.iter s` returns a new priority queue containing all the elements of the sequence `s` (provided it is finite).

Runs in linear time (excluding the time spent in `iter`).

## Iteration

The order in which the elements of a priority queue are traversed is unspecified.

It is a programming error to mutate a priority queue (by adding or removing elements) during an iteration of the queue. Such an error may be detected and signaled by the backing dynamic array implementation, but this is not guaranteed.

**val iter_unordered : (elt -> unit) -> t -> unit**
`get_int16_le` b i is b's little-endian signed 16-bit integer starting at character index i.

Since: 4.13

`val get_int32_ne : string -> int -> int32`

`get_int32_ne` b i is b's native-endian 32-bit integer starting at character index i.

Since: 4.13

`val hash : t -> int`

An unseeded hash function for strings, with the same output value as `Hashtbl.hash` [28.24]. This function allows this module to be passed as argument to the functor `Hashtbl.Make` [28.24].

Since: 5.0

`val seeded_hash : int -> t -> int`

A seeded hash function for strings, with the same output value as `Hashtbl.seeded_hash` [28.24]. This function allows this module to be passed as argument to the functor `Hashtbl.MakeSeeded` [28.24].

Since: 5.0

`val get_int32_be : string -> int -> int32`

`get_int32_be` b i is b's big-endian 32-bit integer starting at character index i.

Since: 4.13

`val get_int32_le : string -> int -> int32`

`get_int32_le` b i is b's little-endian 32-bit integer starting at character index i.

Since: 4.13

`val get_int64_ne : string -> int -> int64`

`get_int64_ne` b i is b's native-endian 64-bit integer starting at character index i.

Since: 4.13

`val get_int64_be : string -> int -> int64`

`get_int64_be` b i is b's big-endian 64-bit integer starting at character index i.

Since: 4.13

`val get_int64_le : string -> int -> int64`

`get_int64_le` b i is b's little-endian 64-bit integer starting at character index i.

Since: 4.13
`iter_unordered` `f q` applies `f` to all elements in `q`. The order in which the elements
are passed to `f` is unspecified.

The behavior is not specified if the priority queue is modified by `f` during the iteration.

`val fold_unordered : ('acc -> elt -> 'acc) -> 'acc -> t -> 'acc`

`fold_unordered` `f accu q` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1,x2,...,xn` are the elements of `q`. The order in which the elements are passed to `f` is unspecified.

The behavior is not specified if the priority queue is modified by `f` during the iteration.

end

Output signature of the functor `Pqueue.MakeMin[29.45]`.

module MakeMin :

`functor (E : OrderedType) -> Min with type elt := E.t`

Functor building an implementation of the min-priority queue structure given a totally
ordered type for elements.

module type Max =

sig

type t

type elt

val create : unit -> t

val length : t -> int

val is_empty : t -> bool

val add : t -> elt -> unit

val add_iter : t -> ((elt -> unit) -> 'x -> unit) -> 'x -> unit

val max_elt : t -> elt option

val get_max_elt : t -> elt

val pop_max : t -> elt option

val remove_max : t -> unit

val clear : t -> unit

val copy : t -> t

val of_array : elt array -> t

val of_list : elt list -> t

val of_iter : ((elt -> unit) -> 'x -> unit) -> 'x -> t

val iter_unordered : (elt -> unit) -> t -> unit

val fold_unordered : ('acc -> elt -> 'acc) -> 'acc -> t -> 'acc

end
## 28.55 Module Sys: System interface.

Every function in this module raises `Sys_error` with an informative message when the underlying system call signal an error.

**val argv : string array**

The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program.

**val executable_name : string**

The name of the file containing the executable currently running. This name may be absolute or relative to the current directory, depending on the platform and whether the program was compiled to bytecode or a native executable.

**val file_exists : string -> bool**

Test if a file with the given name exists.

**val is_directory : string -> bool**

Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file.

**Since:** 3.10

**Raises** `Sys_error` if no file exists with the given name.

**val is fu regular file : string -> bool**

Returns `true` if the given name refers to a regular file, `false` if it refers to another kind of file.

**Since:** 5.1

**Raises** `Sys_error` if no file exists with the given name.

**val remove : string -> unit**

Remove the given file name from the file system.

**val rename : string -> string -> unit**

Rename a file or directory. `rename oldpath newpath` renames the file or directory called `oldpath`, giving it `newpath` as its new name, moving it between (parent) directories if needed. If a file named `newpath` already exists, its contents will be replaced with those of `oldpath`. Depending on the operating system, the metadata (permissions, owner, etc) of `newpath` can either be preserved or be replaced by those of `oldpath`.

**Since:** 4.06 concerning the "replace existing file" behavior

**val getenv : string -> string**

Return the value associated to a variable in the process environment.

**Raises** `Not_found` if the variable is unbound.
Output signature of the functor `Pqueue.MakeMax[29.45]`.

module MakeMax :

functor (E : OrderedType) -> Max with type elt := E.t

Functor building an implementation of the max-priority queue structure given a totally ordered type for elements.

## Polymorphic priority queues

The following, more complex functors create polymorphic queues of type `'a t`, just like other polymorphic containers (lists, arrays...). They require a notion of "polymorphic elements" `'a elt` that can be compared without depending on the values of `'a`.

One usage scenario is when the user wants to pass priorities separately from the value stored in the queue. This is done by using pairs `priority * 'a` as elements.

module Prio : OrderedType = ...

module PrioQueue = Pqueue.MakeMinPoly(struct
  type 'a t = Prio.t * 'a
  let compare (p1,_) (p2,_) = Prio comparisons p1 p2
end)

(* for example, we now have: *)
PrioQueue.add: 'a PrioQueue.t -> Prio.t * 'a -> unit
PrioQueue.min_elt: 'a PrioQueue.t -> (Prio.t * 'a) option

module type OrderedPolyType =
sig

type 'a t

The polymorphic type of elements.

val compare : 'a t -> 'b t -> int

compare is a total order on values of type `Pqueue.OrderedPolyType.t[29.45]`.

end

Input signature of the functors `Pqueue.MakeMinPoly[29.45]` and `Pqueue.MakeMaxPoly[29.45]`.

module type MinPoly =
sig

type 'a t
type 'a elt
**val getenv_opt : string -> string option**

Return the value associated to a variable in the process environment or `None` if the variable is unbound.

**Since: 4.05**

**val command : string -> int**

Execute the given shell command and return its exit code.

The argument of `Sys.command[28.55]` is generally the name of a command followed by zero, one or several arguments, separated by whitespace. The given argument is interpreted by a shell: either the Windows shell `cmd.exe` for the Win32 ports of OCaml, or the POSIX shell `sh` for other ports. It can contain shell builtin commands such as `echo`, and also special characters such as file redirections `>` and `<`, which will be honored by the shell.

Conversely, whitespace or special shell characters occurring in command names or in their arguments must be quoted or escaped so that the shell does not interpret them. The quoting rules vary between the POSIX shell and the Windows shell. The `Filename.quote_command[28.19]` performs the appropriate quoting given a command name, a list of arguments, and optional file redirections.

**val time : unit -> float**

Return the processor time, in seconds, used by the program since the beginning of execution.

**val chdir : string -> unit**

Change the current working directory of the process.

**val mkdir : string -> int -> unit**

Create a directory with the given permissions.

**Since: 4.12**

**val rmdir : string -> unit**

Remove an empty directory.

**Since: 4.12**

**val getcwd : unit -> string**

Return the current working directory of the process.

**val readdir : string -> string array**

Return the names of all files present in the given directory. Names denoting the current directory and the parent directory (`"."` and `".."` in Unix) are not returned. Each string in the result is a file name rather than a complete path. There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.

**val interactive : bool ref**
```h
val create : unit -> 'a t
val length : 'a t -> int
val is_empty : 'a t -> bool
val add : 'a t -> 'a elt -> unit
val add_iter : 'a t ->
(( 'a elt -> unit) -> 'x -> unit) -> 'x -> unit
val min_elt : 'a t -> 'a elt option
val get_min_elt : 'a t -> 'a elt
val pop_min : 'a t -> 'a elt option
val remove_min : 'a t -> unit
val clear : 'a t -> unit
val copy : 'a t -> 'a t
val of_array : 'a elt array -> 'a t
val of_list : 'a elt list -> 'a t
val of_iter : (( 'a elt -> unit) -> 'x -> unit) -> 'x -> 'a t
val iter_unordered : ('a elt -> unit) -> 'a t -> unit
val fold_unordered : ('acc -> 'a elt -> 'acc) ->
'acc -> 'a t -> 'acc
end
```

Output signature of the functor Pqueue.MakeMinPoly[29.45].

```h
module MakeMinPoly :
functor (E : OrderedPolyType) -> MinPoly with type 'a elt := 'a E.t
```

Functor building an implementation of min-priority queues given a totally ordered type for the elements.

```h
module type MaxPoly =
sig
```

```h
type 'a t

type 'a elt

val create : unit -> 'a t
val length : 'a t -> int
val is_empty : 'a t -> bool
val add : 'a t -> 'a elt -> unit
val add_iter : 'a t ->
(( 'a elt -> unit) -> 'x -> unit) -> 'x -> unit
val max_elt : 'a t -> 'a elt option
val get_max_elt : 'a t -> 'a elt
val pop_max : 'a t -> 'a elt option
```
This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`.

**Alert unsynchronized_access.** The interactive status is a mutable global state.

`val os_type : string`

Operating system currently executing the OCaml program. One of

* "Unix" (for all Unix versions, including Linux and Mac OS X),

* "Win32" (for MS-Windows, OCaml compiled with MSVC++ or MinGW-w64),

* "Cygwin" (for MS-Windows, OCaml compiled with Cygwin).

`type backend_type =
| Native
| Bytecode
| Other of string`

Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript.

**Since:** 4.04

`val backend_type : backend_type`

Backend type currently executing the OCaml program.

**Since:** 4.04

`val unix : bool`

True if `Sys.os_type` = "Unix".

**Since:** 4.01

`val win32 : bool`

True if `Sys.os_type` = "Win32".

**Since:** 4.01

`val cygwin : bool`

True if `Sys.os_type` = "Cygwin".

**Since:** 4.01

`val word_size : int`

Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64.

`val int_size : int`

Size of `int`, in bits. It is 31 (resp. 63) when using OCaml on a 32-bit (resp. 64-bit) platform. It may differ for other implementations, e.g. it can be 32 bits when compiling to JavaScript.

**Since:** 4.03
```kotlin
val remove_max: 'a t -> unit
val clear: 'a t -> unit
val copy: 'a t -> 'a t
val of_array: 'a elt array -> 'a t
val of_list: 'a elt list -> 'a t
val of_iter: (( 'a elt -> unit) -> 'x -> unit) -> 'x -> 'a t
val iter_unordered: ('a elt -> unit) -> 'a t -> unit
val fold_unordered: ('acc -> 'a elt -> 'acc) ->
    'acc -> 'a t -> 'acc
end
```

Output signature of the functor `Pqueue.MakeMaxPoly[29.45]`.

```kotlin
module MakeMaxPoly :
    functor (E : OrderedPolyType) -> MaxPoly with type 'a elt := 'a E.t
```

Functor building an implementation of max-priority queues given a totally ordered type for the elements.

## 29.46 Module Printexc: Facilities for printing exceptions and inspecting current call stack.

```kotlin
type t = exn = ..
```

The type of exception values.

```kotlin
val to_string: exn -> string
```

`Printexc.to_string` `e` returns a string representation of the exception `e`.

```kotlin
val to_string_default: exn -> string
```

`Printexc.to_string_default` `e` returns a string representation of the exception `e`, ignoring all registered exception printers.

Since: 4.09

```kotlin
val print: ('a -> 'b) -> 'a -> 'b
```

`Printexc.print` `fn x` applies `fn` to `x` and returns the result. If the evaluation of `fn x` raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application.

```kotlin
val catch: ('a -> 'b) -> 'a -> 'b
```
val big_endian : bool

Whether the machine currently executing the Caml program is big-endian.

Since: 4.00

val max_string_length : int

Maximum length of strings and byte sequences.

val max_array_length : int

Maximum length of a normal array (i.e. any array whose elements are not of type `float`).

The maximum length of a `float` array is `maxFloatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with

`--disable-flat-float-array`.

val maxFloatarray_length : int

Maximum length of a `floatarray`. This is also the maximum length of a `float` array when OCaml is configured with `--enable-flat-float-array`.

val runtimeVariant : unit -> string

Return the name of the runtime variant the program is running on. This is normally the argument given to `-runtime-variant` at compile time, but for byte-code it can be changed after compilation.

Since: 4.03

val runtime_parameters : unit -> string

Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable.

Since: 4.03

Signal handling

type signal_behavior =

| Signal_default

| Signal_IGNORE

| Signal_handle of (int -> unit)

What to do when receiving a signal:

* `Signal_default`: take the default behavior (usually: abort the program)

* `Signal_IGNORE`: ignore the signal

* `Signal_handle f`: call function `f`, giving it the signal number as argument.

val signal : int -> signal Behavior -> signal Behavior
29.46. Module Printexc : Facilities for printing exceptions and inspecting current call stack. 861

Deprecated. This function is no longer needed. Printexc .catch fn x is similar to Printexc .print [29.46], but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as Printexc .catch does. Moreover, calling Printexc .catch makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use Printexc .catch in new code.

val print_backtrace : out_channel -> unit

Printexc.print_backtrace oc prints an exception backtrace on the output channel oc . The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls.

If the call is not inside an exception handler, the returned backtrace is unspecified. If the call
is after some exception-catching code (before in the handler, or in a when-guard during the
matching of the exception handler), the backtrace may correspond to a later exception than
the handled one.

Since: 3.11

val get_backtrace : unit -> string

Printexc.get_backtrace () returns a string containing the same exception backtrace that
Printexc.print_backtrace would print. Same restriction usage than
Printexc.print_backtrace[29.46].

Since: 3.11

val record_backtrace : bool -> unit

Printexc.record_backtrace b turns recording of exception backtraces on (if b = true ) or
off (if b = false ). Initially, backtraces are not recorded, unless the b flag is given to the
program through the OCAMLRUNPARAM variable.

Since: 3.11

val backtrace_status : unit -> bool

Printexc.backtrace_status() returns true if exception backtraces are currently recorded,
false if not.

Since: 3.11

val register_printers : (exn -> string option) -> unit

Printexc.register_printers fn registers fn as an exception printer. The printer should
return None or raise an exception if it does not know how to convert the passed exception,
and Some s with s the resulting string if it can convert the passed exception. Exceptions
raised by the printer are ignored.

When converting an exception into a string, the printers will be invoked in the reverse order
of their registrations, until a printer returns a Some s value (if no such printer exists, the
runtime will use a generic printer).
Set the behavior of the system on receipt of a given signal. The first argument is the signal number. Return the behavior previously associated with the signal. If the signal number is invalid (or not available on your system), an `Invalid_argument` exception is raised.

`val set_signal : int -> signal_behavior -> unit`

Same as `Sys.signal[28.55]` but return value is ignored.

Signal numbers for the standard POSIX signals.

`val sigabrt : int`

Abnormal termination

`val sigalrm : int`

Timeout

`val sigfpe : int`

Arithmetic exception

`val sighup : int`

Hangup on controlling terminal

`val sigill : int`

Invalid hardware instruction

`val sigint : int`

Interactive interrupt (ctrl-C)

`val sigkill : int`

Termination (cannot be ignored)

`val sigpipe : int`

Broken pipe

`val sigquit : int`

Interactive termination

`val sigsegv : int`

Invalid memory reference

`val sigterm : int`

Termination

`val sigusr1 : int`

Application-defined signal 1
When using this mechanism, one should be aware that an exception backtrace is attached to
the thread that saw it raised, rather than to the exception itself. Practically, it means that
the code related to `fn` should not use the backtrace if it has itself raised an exception before.

**Since: 3.11.2**

`val use_printers : exn -> string option`

`Printexc.use_printers` e returns `None` if there are no registered printers and `Some s` with `s` the resulting string otherwise.

**Since: 4.09**

## Raw backtraces

`type raw_backtrace`

The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below.

Converting backtraces to `backtrace_slots` is slower than capturing the backtraces. If an
application processes many backtraces, it can be useful to use `raw_backtrace` to avoid or
delay conversion.

Raw backtraces cannot be marshalled. If you need marshalling, you should use the array
returned by the `backtrace_slots` function of the next section.

**Since: 4.01**

`type raw_backtrace_entry = private int`

A `raw_backtrace_entry` is an element of a `raw_backtrace`.

Each `raw_backtrace_entry` is an opaque integer, whose value is not stable between different
programs, or even between different runs of the same binary.

A `raw_backtrace_entry` can be converted to a usable form using
`backtrace_slots_of_raw_entry` below. Note that, due to inlining, a single
`raw_backtrace_entry` may convert to several `backtrace_slots`. Since the values of a
`raw_backtrace_entry` are not stable, they cannot be marshalled. If they are to be converted,
the conversion must be done by the process that generated them.

Again due to inlining, there may be multiple distinct `raw_backtrace_entry` values that
convert to equal `backtrace_slots`. However, if two `raw_backtrace_entries` are equal as
integers, then they represent the same `backtrace_slots`.

**Since: 4.12**

`val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array`

**Since: 4.12**

`val get_raw_backtrace : unit -> raw_backtrace`
val sigusr2 : int

Application-defined signal 2

val sigchld : int

Child process terminated

val sigcont : int

Continue

val sigstop : int

Stop

val sigtstp : int

Interactive stop

val sigttin : int

Terminal read from background process

val sigttou : int

Terminal write from background process

val sigvtalrm : int

Timeout in virtual time

val sigprof : int

Profiling interrupt

val sigbus : int

Bus error

Since: 4.03

val sigpoll : int

Pollable event

Since: 4.03

val sigsys : int

Bad argument to routine

Since: 4.03

val sigtrap : int

Trace/breakpoint trap

Since: 4.03
29.46. Module Printexc: Facilities for printing exceptions and inspecting current call stack. 863

`Printexc.get_raw_backtrace()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. Same restriction usage than `Printexc.print_backtrace` [29.46].

**Since: 4.01**

`val print_raw_backtrace: out_channel -> raw_backtrace -> unit`

Print a raw backtrace in the same format `Printexc.print_backtrace` uses.

**Since: 4.01**

`val raw_backtrace_to_string: raw_backtrace -> string`

Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses.

**Since: 4.01**

`val raise_with_backtrace: exn -> raw_backtrace -> 'a`

Reraise the exception using the given `raw_backtrace` for the origin of the exception

**Since: 4.05**

## Current call stack

`val get_callstack: int -> raw_backtrace`

`Printexc.get_callstack` n returns a description of the top of the call stack on the current program point (for the current thread), with at most n entries. (Note: this function is not related to exceptions at all, despite being part of the `Printexc` module.)

**Since: 4.01**

## Uncaught exceptions

`val default_uncaught_exception_handler: exn -> raw_backtrace -> unit`

`Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output.

**Since: 4.11**

`val set_uncaught_exception_handler: (exn -> raw_backtrace -> unit) -> unit`

`Printexc.set_uncaught_exception_handler` fn registers fn as the handler for uncaught exceptions. The default handler is `Printexc.default_uncaught_exception_handler` [29.46].

Note that when fn is called all the functions registered with `at_exit` [28.2] have already been called. Because of this you must make sure any output channel fn writes on is flushed.

Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself.
val sigurg : int

Urgent condition on socket

Since: 4.03

val sigxcpu : int

Timeout in cpu time

Since: 4.03

val sigxfsz : int

File size limit exceeded

Since: 4.03

exception Break

Exception raised on interactive interrupt if Sys catches Break [28.55] is on.

val catch_break : bool -> unit

catch_break governs whether interactive interrupt (ctrl-C) terminates the program or raises
the Break exception. Call catch_break true to enable raising Break, and catch_break
false to let the system terminate the program on user interrupt.

val ocaml_version : string

ocaml_version is the version of OCaml. It is a string of the form
"major.minor[.patchlevel][(+|~)additional-info]", where major, minor, and
patchlevel are integers, and additional-info is an arbitrary string. The [.patchlevel]
part was absent before version 3.08.0 and became mandatory from 3.08.0 onwards. The
[(+|~)additional-info] part may be absent.

val development_version : bool

true if this is a development version, false otherwise.

Since: 4.14

type extra_prefix =
| Plus
| Tilde

type extra_info = extra_prefix * string

Since: 4.14

type ocaml_release_info =

{ major : int ;
minor : int ;
patchlevel : int ;
extra : extra_info option ;
}
If `fn` raises an exception, both the exceptions passed to `fn` and raised by `fn` will be printed with their respective backtrace.

**Since: 4.02**

## Manipulation of backtrace information

These functions are used to traverse the slots of a raw backtrace and extract information from them in a programmer-friendly format.

`type backtrace_slots`

The abstract type `backtrace_slots` represents a single slot of a backtrace.

**Since: 4.02**

`val backtrace_slots : raw_backtrace -> backtrace_slots array option`

Returns the slots of a raw backtrace, or `None` if none of them contain useful information.

In the return array, the slot at index 0 corresponds to the most recent function call, raise, or primitive `get_backtrace` call in the trace.

Some possible reasons for returning `None` are as follows:

* none of the slots in the trace come from modules compiled with debug information (`-g`)

* the program is a bytecode program that has not been linked with debug information enabled (`ocamlc -g`)

**Since: 4.02**

`val backtrace_slots_of_raw_entry :`

`raw_backtrace_entry -> backtrace_slots array option`

Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information.

Slots are returned in the same order as `backtrace_slots`: the slot at index 0 is the most recent call, raise, or primitive, and subsequent slots represent callers.

**Since: 4.12**

```hml
type location =
  { filename : string ;
    line_number : int ;
    start_char : int ;
    end_char : int ;
    end_line : int ;

    Since: 5.2
  end_col : int ;

    Since: 5.2
}
```
**Since: 4.14**

val ocaml_release : ocaml_release_info

`ocaml_release` is the version of OCaml.

**Since: 4.14**

val enable_runtime_warnings : bool -> unit

Control whether the OCaml runtime system can emit warnings on stderr. Currently, the only supported warning is triggered when a channel created by `open_*` functions is finalized without being closed. Runtime warnings are disabled by default.

**Since: 4.03**

**Alert unsynchronized_access.** The status of runtime warnings is a mutable global state.

val runtime_warnings_enabled : unit -> bool

Return whether runtime warnings are currently enabled.

**Since: 4.03**

**Alert unsynchronized_access.** The status of runtime warnings is a mutable global state.

## Optimization

val opaque_identity : 'a -> 'a

For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function.

At runtime, `opaque_identity` disappears altogether.

A typical use of this function is to prevent pure computations from being optimized away in benchmarking loops. For example:

```hml
for _round = 1 to 100_000 do
    ignore (Sys.opaque_identity (my_pure_computation ()))
done
```

**Since: 4.03**

module Immediate64 :

sig

This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate.

module type Non_immediate =
    sig
29.46. Module Printexc: Facilities for printing exceptions and inspecting current call stack. 865

The type of location information found in backtraces. `start_char` and `end_char` are positions relative to the beginning of `line_number`. `end_col` is relative to the beginning of `end_line`.

**Since: 4.02**

`module Slot :`

`sig`

`type t = Printexc.backtrace_slots`

`val isóg : t -> bool`

`isóg slot` is true when `slot` refers to a raising point in the code, and false when it comes from a simple function call.

**Since: 4.02**

`val is inline : t -> bool`

`is inline slot` is true when `slot` refers to a call that got inlined by the compiler, and false when it comes from any other context.

**Since: 4.04**

`val location : t -> Printexc.location option`

`location slot` returns the location information of the slot, if available, and `None` otherwise.

Some possible reasons for failing to return a location are as follows:

* the slot corresponds to a compiler-inserted raise

* the slot corresponds to a part of the program that has not been compiled with debug information (`-g`)

**Since: 4.02**

`val name : t -> string option`

`name slot` returns the name of the function or definition enclosing the location referred to by the slot.

`name slot` returns `None` if the name is unavailable, which may happen for the same reasons as `location` returning `None`.

**Since: 4.11**

`val format : int -> t -> string option`

`format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`-th element of the backtrace: the 0-th element is pretty-printed differently than the others.

Whole-backtrace printing functions also skip some uninformative slots; in that case, `format pos slot` returns `None`.

**Since: 4.02**
```pascal
type t
end

module type Immediate =
sig
```

```pascal
type t
end

module Make :
functor (Immediate : Immediate) -> functor (Non_immediate : Non_immediate)
-> sig
```

```pascal
type t

type 'a repr =
| Immediate : Sys.Immediate64.Immediate.t repr
| Non_immediate : Sys.Immediate64.Non_immediate.t repr

val repr : t repr
end
```

end

## 28.56 Module Type : Type introspection.

Since: 5.1

### Type equality witness

```pascal
type ('_, '_') eq =
| Equal : ('a, 'a) eq
```

The purpose of `eq` is to represent type equalities that may not otherwise be known by the type checker (e.g. because they may depend on dynamic data).

A value of type `(a, b) eq` represents the fact that types `a` and `b` are equal.

If one has a value `eq : (a, b) eq` that proves types `a` and `b` are equal, one can use it to convert a value of type `a` to a value of type `b` by pattern matching on `Equal`:

```pascal
let cast (type a) (type b) (Equal : (a, b) Type.eq) (a : a) : b = a
```

At runtime, this function simply returns its second argument unchanged.
end

**Since: 4.02**

## Raw backtrace slots

`type raw_backtrace_slots`

This type is used to iterate over the slots of a `raw_backtrace`. For most purposes, `backtrace_slots_of_raw_entry` is easier to use.

Like `raw_backtrace_entry`, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior).

Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example).

**Since: 4.02**

`val raw_backtrace_length : raw_backtrace -> int`
`raw_backtrace_length bckt` returns the number of slots in the backtrace bckt.

**Since: 4.02**

`val get_raw_backtrace_slots : raw_backtrace -> int -> raw_backtrace_slots`
`get_raw_backtrace_slots bckt pos` returns the slot in position pos in the backtrace bckt.

**Since: 4.02**

`val convert_raw_backtrace_slots : raw_backtrace_slots -> backtrace_slots`
Extracts the user-friendly `backtrace_slots` from a low-level `raw_backtrace_slots`.

**Since: 4.02**

`val get_raw_backtrace_next_slots :`
`raw_backtrace_slots -> raw_backtrace_slots` option
`get_raw_backtrace_next_slots` slot returns the next slot inlined, if any.

Sample code to iterate over all frames (inlined and non-inlined):

```
(* Iterate over inlined frames *)
let rec iter_raw_backtrace_slots f slot =
    f slot;
match get_raw_backtrace_next_slots slot with
  | None -> ()
  | Some slot' -> iter_raw_backtrace_slots f slot'

(* Iterate over stack frames *)
```
## Type identifiers

module Id :
sig

### Type identifiers

type !'a t

The type for identifiers for type 'a.

val make : unit -> 'a t

make () is a new type identifier.

val uid : 'a t -> int

uid id is a runtime unique identifier for id.

val provably_equal : 'a t -> 'b t -> ('a, 'b) Type.eq option

provably_equal i0 i1 is Some Equal if identifier i0 is equal to i1 and None otherwise.

### Example

The following shows how type identifiers can be used to implement a simple heterogeneous key-value dictionary. In contrast to Map[27.2] values whose keys map to a single, homogeneous type of values, this dictionary can associate a different type of value to each key.

(** Heterogeneous dictionaries. *)

module Dict : sig

type t

(** The type for dictionaries. *)

type 'a key

(** The type for keys binding values of type ['a]. *)

val key : unit -> 'a key

(** [key ()] is a new dictionary key. *)

val empty : t

(** [empty] is the empty dictionary. *)

val add : 'a key -> 'a -> t -> t

(** [add k v d] is [d] with [k] bound to [v]. *)
```python
let iter_raw_backtrace f bt =
    for i = 0 to raw_backtrace_length bt - 1 do
        iter_raw_backtrace�_slots f (get_raw_backtrace_slots bt i)
    done
```

**Since:** 4.04

## Exception slots

`val exn_slots_id: exn -> int`

`Printexc.exn_slots_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime).

**Since:** 4.02

`val exn_slots_name: exn -> string`

`Printexc.exn_slots_name` exn returns the internal name of the constructor used to create the exception value `exn`.

**Since:** 4.02

# 29.47 Module Printf: Formatted output functions.

`val fprintf: out_channel -> ('a, out_channel, unit) format -> 'a`

`fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`.

The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments.

Conversion specifications have the following form:

`% [flags] [width] [.precision] type`

In short, a conversion specification consists in the `%` character, followed by optional modifiers and a type which is made of one or two characters.

The types and their meanings are:

* `d`, `i`: convert an integer argument to signed decimal. The flag `#` adds underscores to large values for readability.

* `u`, `n`, `l`, `L`, or `N`: convert an integer argument to unsigned decimal. Warning: `n`, `l`, `L`, and `N` are used for `scanf`, and should not be used for `printf`. The flag `#` adds underscores to large values for readability.
```h
val remove : 'a key -> t -> t
(** [remove k d] is [d] with the last binding of [k] removed. *)

val find : 'a key -> t -> 'a option
(** [find k d] is the binding of [k] in [d], if any. *)
end = struct
    type 'a key = 'a Type.Id.t
    type binding = B : 'a key * 'a -> binding
    type t = (int * binding) list

let key () = Type.Id.make ()
let empty = []
let add k v d = (Type.Id.uid k, B (k, v)) :: d
let remove k d = List.remove Assoc (Type.Id.uid k) d
let find : type a. a key -> t -> a option = fun k d ->
    match List.assoc_opt (Type.Id.uid k) d with
    | None -> None
    | Some (B (k', v)) ->
        match Type.Id.provably_equal k k' with
        | Some TypeEQUAL -> Some v
        | None -> assert false
end
```

end

Type identifiers.

A type identifier is a value that denotes a type. Given two type identifiers, they can be tested for equality [28.56] to prove they denote the same type. Note that:

* Unequal identifiers do not imply unequal types: a given type can be denoted by more than one identifier.

* Type identifiers can be marshalled, but they get a new, distinct, identity on unmarshalling, so the equalities are lost.

See an example [28.56] of use.

## 28.57 Module Uchar : Unicode characters.

Since: 4.03

type t
* x: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag # adds a 0x prefix to non zero values.

* X: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag # adds a 0X prefix to non zero values.

* o: convert an integer argument to unsigned octal. The flag # adds a 0 prefix to non zero values.

* s: insert a string argument.

* S: convert a string argument to OCaml syntax (double quotes, escapes).

* c: insert a character argument.

* C: convert a character argument to OCaml syntax (single quotes, escapes).

* f: convert a floating-point argument to decimal notation, in the style dddd.ddd.

* F: convert a floating-point argument to OCaml syntax (dddd. or dddd.ddd or d.ddd e+-dd). Converts to hexadecimal with the # flag (see h).

* e or E: convert a floating-point argument to decimal notation, in the style d.ddd e+-dd (mantissa and exponent).

* g or G: convert a floating-point argument to decimal notation, in style f or e, E (whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining.

* h or H: convert a floating-point argument to hexadecimal notation, in the style 0x.hhhh p+-dd (hexadecimal mantissa, exponent in decimal and denotes a power of 2).

* B: convert a boolean argument to the string true or false

* b: convert a boolean argument (deprecated; do not use in new programs).

* ld, li, lu, lx, lX, lo: convert an int32 argument to the format specified by the second letter (decimal, hexadecimal, etc).

* nd, ni, nu, nx, nX, no: convert a nativeint argument to the format specified by the second letter.

* Ld, Li, Lu, Lx, LX, Lo: convert an int64 argument to the format specified by the second letter.

* a: user-defined printer. Take two arguments and apply the first one to outchan (the current output channel) and to the second argument. The first argument must therefore have type out_channel -> 'b -> unit and the second 'b. The output produced by the function is inserted in the output of fprintf at the current point.

* t: same as %a, but take only one argument (with type out_channel -> unit) and apply it to outchan.

* { fmt %}: convert a format string argument to its type digest. The argument must have the same type as the internal format string fmt.

* ( fmt %): format string substitution. Take a format string argument and substitute it to the internal format string fmt to print following arguments. The argument must have the same type as the internal format string fmt.
The type for Unicode characters.

A value of this type represents a Unicode scalar
value[http://unicode.org/glossary/#unicode_scalar_value] which is an integer in the
ranges 0x0000...0xD7FF or 0xE000...0x10FFFF.

val min : t

min is U+0000.

val max : t
max is U+10FFF.

val bom : t

bom is U+FEFF, the byte order mark[http://unicode.org/glossary/#byte_order_mark]
(BOM) character.

Since: 4.06

val rep : t
rep is U+FFFD, the
replacement[http://unicode.org/glossary/#replacement_character] character.

Since: 4.06

val succ : t -> t
succ u is the scalar value after u in the set of Unicode scalar values.

Raises Invalid_argument if u is Uchar.max[28.57].

val pred : t -> t
pred u is the scalar value before u in the set of Unicode scalar values.

Raises Invalid_argument if u is Uchar.min[28.57].

val is_valid : int -> bool
is_valid n is true if and only if n is a Unicode scalar value (i.e. in the ranges
0x0000...0xD7FF or 0xE000...0x10FFFF).

val of_int : int -> t
of_int i is i as a Unicode character.

Raises Invalid_argument if i does not satisfy Uchar.is_valid[28.57].

val to_int : t -> int
to_int u is u as an integer.

val is_char : t -> bool
is_char u is true if and only if u is a latin1 OCaml character.
* `!`: take no argument and flush the output.

* `%`: take no argument and output one `%` character.

* `@`: take no argument and output one `@` character.

* `,`: take no argument and output nothing: a no-op delimiter for conversion specifications.

The optional `flags` are:

* `-`: left-justify the output (default is right justification).

* `0`: for numerical conversions, pad with zeroes instead of spaces.

* `+`: for signed numerical conversions, prefix number with a `+` sign if positive.

* `space`: for signed numerical conversions, prefix number with a space if positive.

* `#`: request an alternate formatting style for the integer types and the floating-point type `F`.

The optional `width` is an integer indicating the minimal width of the result. For instance, `%6d` prints an integer, prefixing it with spaces to fill at least 6 characters.

The optional `precision` is a dot `.` followed by an integer indicating how many digits follow the decimal point in the `%f`, `%e`, `%E`, `%h`, and `%H` conversions or the maximum number of significant digits to appear for the `%F`, `%g` and `%G` conversions. For instance, `%.4f` prints a `float` with 4 fractional digits.

The integer in a `width` or `precision` can also be specified as `*`, in which case an extra integer argument is taken to specify the corresponding `width` or `precision`. This integer argument precedes immediately the argument to print. For instance, `%.*f` prints a `float` with as many fractional digits as the value of the argument given before the float.

`val printf`: (`'a, out_channel, unit`), `format -> 'a'`
Same as `Format.fprintf[29.47]`, but output on `stdout`.

`val eprintf`: (`'a, out_channel, unit'`), `format -> 'a'`
Same as `Format.fprintf[29.47]`, but output on `stderr`.

`val sprintf`: (`'a, unit, string'`), `format -> 'a'`
Same as `Format.fprintf[29.47]`, but instead of printing on an output channel, return a string containing the result of formatting the arguments.

`val bprintf`: `Buffer.t -> ('a, Buffer.t, unit) format -> 'a'`
Same as `Format.fprintf[29.47]`, but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module `Buffer`[29.7]).

`val ifprintf`: `'b -> ('a, 'b, 'c, unit) format' -> 'a'`
Same as `Format.fprintf[29.47]`, but does not print anything. Useful to ignore some material when conditionally printing.

**Since: 3.10**
val of_char : char -> t
of_char c is c as a Unicode character.

val to_char : t -> char
to_char u is u as an OCaml latin1 character.
**Raises** Invalid_argument if u does not satisfy Uchar.is_char[28.57].

val equal : t -> t -> bool
equal u u' is u = u'.

val compare : t -> t -> int
compare u u' is Stdlib comparisons.

val hash : t -> int
hash u associates a non-negative integer to u.

## UTF codecs tools

type utf_decode
The type for UTF decode results. Values of this type represent the result of a Unicode
Transformation Format decoding attempt.

val utf_decode_is_valid : utf_decode -> bool
utf_decode_is_valid d is true if and only if d holds a valid decode.

val utf_decode_uchar : utf_decode -> t
utf_decode_uchar d is the Unicode character decoded by d if utf_decode_is_valid d is
true and Uchar.rep[28.57] otherwise.

val utf_decode_length : utf_decode -> int
utf_decode_length d is the number of elements from the source that were consumed by the
decode d. This is always strictly positive and smaller or equal to 4. The kind of source
elements depends on the actual decoder; for the decoders of the standard library this function
always returns a length in bytes.

val utf_decode : int -> t -> utf_decode
utf_decode n u is a valid UTF decode for u that consumed n elements from the source for
decoding. n must be positive and smaller or equal to 4 (this is not checked by the module).

val utf_decode_INVALID : int -> utf_decode
utf_decode_INVALID n is an invalid UTF decode that consumed n elements from the source
to error. n must be positive and smaller or equal to 4 (this is not checked by the module).
The resulting decode has Uchar.rep[28.57] as the decoded Unicode character.
`val ibprintf: Buffer.t -> ('a, Buffer.t, unit) format -> 'a`

Same as `Formatf.bprintf[29.47]`, but does not print anything. Useful to ignore some material when conditionally printing.

**Since:** 4.11

Formatted output functions with continuations.

`val kfprintf: (out_channel -> 'd) ->`

`out_channel -> ('a, out_channel, unit, 'd) format4 -> 'a`

Same as `fprintf`, but instead of returning immediately, passes the out channel to its first argument at the end of printing.

**Since:** 3.09

`val ikfprintf: ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a`

Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.

**Since:** 4.01

`val ksprintf: (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a`

Same as `sprintf` above, but instead of returning the string, passes it to the first argument.

**Since:** 3.09

`val kbprintf: (Buffer.t -> 'd) ->`

`Buffer.t -> ('a, Buffer.t, unit, 'd) format4 -> 'a`

Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing.

**Since:** 3.10

`val ikbprintf: (Buffer.t -> 'd) ->`

`Buffer.t -> ('a, Buffer.t, unit, 'd) format4 -> 'a`

Same as `kbprintf` above, but does not print anything. Useful to ignore some material when conditionally printing.

**Since:** 4.11

Deprecated

`val kprintf: (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a`

*Deprecated.* Use `Formatf.ksprintf` instead. A deprecated synonym for `ksprintf`.
val utf_8_byte_length : t -> int
    utf_8_byte_length u is the number of bytes needed to encode u in UTF-8.

val utf_16_byte_length : t -> int
    utf_16_byte_length u is the number of bytes needed to encode u in UTF-16.

## 28.58 Module Unit: Unit values.

Since: 4.08

### The unit type

type t = unit =

| ()

The unit type.

The constructor () is included here so that it has a path, but it is not intended to be used in user-defined data types.

val equal : t -> t -> bool

equal u1 u2 is true.

val compare : t -> t -> int

compare u1 u2 is 0.

val to_string : t -> string

to_string b is "()".

## 28.59 Module Weak: Arrays of weak pointers and hash sets of weak pointers.

### Low-level functions

type !'a t

The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program. Note that finalisation functions are run before the weak pointers are erased, because the finalisation functions can make values alive again (before 4.03 the finalisation functions were run after).

A weak pointer is said to be full if it points to a value, empty if the value was erased by the GC.

Notes:
## 29.48 Module Queue: First-in first-out queues.

This module implements queues (FIFOs), with in-place modification. See the example section [29.48] below.

**Alert unsynchronized_access.** Unsynchronized accesses to queues are a programming error.

### Unsynchronized accesses

Unsynchronized accesses to a queue may lead to an invalid queue state. Thus, concurrent accesses to queues must be synchronized (for instance with a `Mutex.t[29.38]`).

type !'a t

The type of queues containing elements of type 'a.

exception Empty

Raised when `Queue.take[29.48]` or `Queue peek[29.48]` is applied to an empty queue.

val create : unit -> 'a t

Return a new queue, initially empty.

val add : 'a -> 'a t -> unit

add x q adds the element x at the end of the queue q.

val push : 'a -> 'a t -> unit

push is a synonym for add.

val take : 'a t -> 'a

take q removes and returns the first element in queue q, or raises `Queue.Empty[29.48]` if the queue is empty.

val take_opt : 'a t -> 'a option

take_opt q removes and returns the first element in queue q, or returns `None` if the queue is empty.

**Since:** 4.08

val pop : 'a t -> 'a

pop is a synonym for take.

val peek : 'a t -> 'a

peek q returns the first element in queue q, without removing it from the queue, or raises `Queue.Empty[29.48]` if the queue is empty.

val peek_opt : 'a t -> 'a option

peek_opt q returns the first element in queue q, without removing it from the queue, or returns `None` if the queue is empty.

**Since:** 4.08
* Integers are not allocated and cannot be stored in weak arrays.

* Weak arrays cannot be marshaled using `output_value[27.2]` nor the functions of the ` Marshal[28.34] ` module.

val create : int -> 'a t

Weak.create n returns a new weak array of length n. All the pointers are initially empty.

Raises Invalid_argument if n is not comprised between zero and
Obj.Ephemeron.max_ephe_length[??] (limits included).

val length : 'a t -> int

Weak.length ar returns the length (number of elements) of ar.

val set : 'a t -> int -> 'a option -> unit

Weak.set ar n (Some el) sets the nth cell of ar to be a (full) pointer to el; Weak.set ar
n None sets the nth cell of ar to empty.

Raises Invalid_argument if n is not in the range 0 to Weak.length[28.59] ar - 1.

val get : 'a t -> int -> 'a option

Weak.get ar n returns None if the nth cell of ar is empty, Some x (where x is the value) if it
is full.

Raises Invalid_argument if n is not in the range 0 to Weak.length[28.59] ar - 1.

val get_copy : 'a t -> int -> 'a option

Weak.get_copy ar n returns None if the nth cell of ar is empty, Some x (where x is a (shallow) copy of the value) if it is full. In addition to pitfalls with mutable values, the interesting difference with get is that get_copy does not prevent the incremental GC from erasing the value in its current cycle (get may delay the erasure to the next GC cycle).

Raises Invalid_argument if n is not in the range 0 to Weak.length[28.59] ar - 1.

If the element is a custom block it is not copied.

val check : 'a t -> int -> bool

Weak.check ar n returns true if the nth cell of ar is full, false if it is empty. Note that
even if Weak.check ar n returns true, a subsequent Weak.get[28.59] ar n can return None.

Raises Invalid_argument if n is not in the range 0 to Weak.length[28.59] ar - 1.

val fill : 'a t -> int -> int -> 'a option -> unit

Weak.fill ar ofs len el sets to el all pointers of ar from ofs to ofs + len - 1.

Raises Invalid_argument if ofs and len do not designate a valid subarray of ar.

val blit : 'a t -> int -> 'a t -> int -> int -> unit

Weak.blit ar1 off1 ar2 off2 len copies len weak pointers from ar1 (starting at off1)
to ar2 (starting at off2). It works correctly even if ar1 and ar2 are the same.

Raises Invalid_argument if off1 and len do not designate a valid subarray of ar1, or if
off2 and len do not designate a valid subarray of ar2.
val top : 'a t -> 'a
top is a synonym for peek.

val drop : 'a t -> unit
drop q removes the first element in queue q, or raises Queue.Empty[29.48] if the queue is
empty.

Since: 5.3

val clear : 'a t -> unit
Discard all elements from a queue.

val copy : 'a t -> 'a t
Return a copy of the given queue.

val is_empty : 'a t -> bool
Return true if the given queue is empty, false otherwise.

val length : 'a t -> int
Return the number of elements in a queue.

val iter : ('a -> unit) -> 'a t -> unit
iter f q applies f in turn to all elements of q, from the least recently entered to the most
recently entered. The queue itself is unchanged.

val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc
fold f accu q is equivalent to List.fold_left f accu l, where l is the list of q's
elements. The queue remains unchanged.

val transfer : 'a t -> 'a t -> unit
transfer q1 q2 adds all of q1's elements at the end of the queue q2, then clears q1. It is
equivalent to the sequence iter (fun x -> add x q2) q1; clear q1, but runs in constant
time.

Iterators

val to_seq : 'a t -> 'a Seq.t
Iterate on the queue, in front-to-back order. The behavior is not specified if the queue is
modified during the iteration.

Since: 4.07

val add_seq : 'a t -> 'a Seq.t -> unit
Add the elements from a sequence to the end of the queue.

Since: 4.07
## Weak hash sets

A weak hash set is a hashed set of values. Each value may magically disappear from the set when it is not used by the rest of the program any more. This is normally used to share data structures without inducing memory leaks. Weak hash sets are defined on values from a `Hashtbl.HashedType[28.24]` module; the `equal` relation and `hash` function are taken from that module. We will say that `v` is an instance of `x` if `equal x v` is true.

The `equal` relation must be able to work on a shallow copy of the values and give the same result as with the values themselves.

### Unsynchronized accesses

Unsynchronized accesses to weak hash sets are a programming error. Unsynchronized accesses to a weak hash set may lead to an invalid weak hash set state. Thus, concurrent accesses to weak hash sets must be synchronized (for instance with a `Mutex.t[28.36]`).

```python
module type S =
    sig
```

```python
type data
```

The type of the elements stored in the table.

```python
type t
```

The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using `output_value[27.2]` or the functions of the ` Marshal[28.34]` module.

```python
val create : int -> t
```

`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed.

```python
val clear : t -> unit
```

Remove all elements from the table.

```python
val merge : t -> data -> data
```

`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`.

```python
val add : t -> data -> unit
```

`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`.

```python
val remove : t -> data -> unit
```

`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`.

```python
val find : t -> data -> data
```
```h
val of_seq : 'a Seq.t -> 'a t
```

Create a queue from a sequence.

**Since: 4.07**

## Examples

### Basic Example

A basic example:

```h
# let q = Queue.create ()
val q : '_weak1 Queue.t = <abstr>

# Queue.push 1 q; Queue.push 2 q; Queue.push 3 q
- : unit = ()

# Queue.length q
- : int = 3

# Queue.pop q
- : int = 1

# Queue.pop q
- : int = 2

# Queue.pop q
- : int = 3

# Queue.pop q
Exception: Stdlib.Queue.Empty
```

## Search Through a Graph

For a more elaborate example, a classic algorithmic use of queues is to implement a BFS (breadth-first search) through a graph.

```h
type graph = {
    edges: (int, int list) Hashtbl.t
}
```

(* Search in graph [g] using BFS, starting from node [start].
It returns the first node that satisfies [p], or [None] if
no node reachable from [start] satisfies [p].
`find` `t` `x` returns an instance of `x` found in `t`.

**Raises** `Not_found` if there is no such element.

`val find_opt : t -> data -> data option`

`find_opt` `t` `x` returns an instance of `x` found in `t` or `None` if there is no such element.

**Since:** 4.05

`val find_all : t -> data -> data list`

`find_all` `t` `x` returns a list of all the instances of `x` found in `t`.

`val mem : t -> data -> bool`

`mem` `t` `x` returns `true` if there is at least one instance of `x` in `t`, `false` otherwise.

`val iter : (data -> unit) -> t -> unit`

`iter` `f` `t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself.

`val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc`

`fold` `f` `t` `init` computes (`f` `d1` (... (`f` `dN` `init`))) where `d1` ... `dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself.

`val count : t -> int`

Count the number of elements in the table. `count` `t` gives the same result as `fold` (`fun _ n -> n+1`) `t` `0` but does not delay the deallocation of the dead elements.

`val stats : t -> int * int * int * int * int * int`

Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length.

`end`

The output signature of the functor `Weak.Make` [28.59].

module Make :

`functor (H : Hashtbl.HashedType) -> S with type data = H.t`

Functor building an implementation of the weak hash set structure. `H equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it.
*)
let search_for ~ (g:graph) ~ (start:int) (p:int -> bool) : int option =
let to_explore = Queue.create() in
let explored = Hashtbl.create 16 in

Queue.push start to_explore;
let rec loop () =
  if Queue.is_empty to_explore then None
  else
    (* node to explore *)
    let node = Queue.pop to_explore in
    explore_node node

and explore_node node =
  if not (Hashtbl.mem explored node) then (
    if p node then Some node (* found *)
    else (
      Hashtbl.add explored node ();
      let children =
        Hashtbl.find_opt g_edges node
      |> Option.value ~default:[]
      in
      List.iter (fun child -> Queue.push child to_explore) children;
      loop()
    )
  ) else loop()
  in
loop()

(* a sample graph *)
let my_graph: graph =
let edges =
  List.to_seq [
    1, [2;3];
    2, [10; 11];
    3, [4;5];
    5, [100];
    11, [0; 20];
  ]
|> Hashtbl.of_seq
in {edges}

# search_for ~g:my_graph ~start:1 (fun x -> x = 30)
- : int option = None
## 28.60 Ocaml_operators : Precedence level and associativity of operators

The following table lists the precedence level of all operator classes from the highest to the lowest precedence. A few other syntactic constructions are also listed as references.

<table><thead><tr><th>Operator class</th><th>Associativity</th></tr></thead><tbody><tr><td>!...~...</td><td>-</td></tr><tr><td>...() ...[] ...{}</td><td>-</td></tr><tr><td>\#...</td><td>left</td></tr><tr><td>function application</td><td>left</td></tr><tr><td>--</td><td>-</td></tr><tr><td>**... lsl lsr asr</td><td>right</td></tr><tr><td>*... /...%... mod land lor lxor</td><td>left</td></tr><tr><td>+...-...</td><td>left</td></tr><tr><td>::</td><td>right</td></tr><tr><td>@...^...</td><td>right</td></tr><tr><td>=...<...>...|...&...$...!=</td><td>left</td></tr><tr><td>& &amp;</td><td>right</td></tr><tr><td>or ||</td><td>right</td></tr><tr><td>,</td><td>-</td></tr><tr><td>&lt;:=</td><td>right</td></tr><tr><td>if</td><td>-</td></tr><tr><td>;</td><td>right</td></tr></tbody></table>
```python
# search_for ~g:my_graph ~start:1 (fun x -> x >= 15)
- : int option = Some 20
```

```python
# search_for ~g:my_graph ~start:1 (fun x -> x >= 50)
- : int option = Some 100
```

## 29.49 Module Random: Pseudo-random number generators (PRNG).

With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain.

In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the `Random.split` [29.49] function and used with the functions from the `Random.State` [29.49] module.

**Before 5.0** Random value generation used a different algorithm. This affects all the functions in this module which return random values.

### Basic functions

**val init : int -> unit**

Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers.

**val full_init : int array -> unit**

Same as `Random.init` [29.49] but takes more data as seed.

**val self_init : unit -> unit**

Initialize the domain-local generator with a random seed chosen in a system-dependent way. If a cryptographically secure pseudorandom number generator is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state).

**val bits : unit -> int**

Return 30 random bits in a nonnegative integer.

**val int : int -> int**

`Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0 and less than $2^{30}$.

Raises `Invalid_argument` if `bound` ≤ 0 or `bound` ≥ $2^{30}$.

**val full_int : int -> int**
`Random-full_int` bound returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` may be any positive integer.

If `bound` is less than $2^{31}$, then `Random-full_int` bound yields identical output across systems with varying `int` sizes.

If `bound` is less than $2^{30}$, then `Random-full_int` bound is equal to `Random-int[29.49]` bound.

If `bound` is at least $2^{30}$ (on 64-bit systems, or non-standard environments such as JavaScript), then `Random-full_int` returns a value whereas `Random-int[29.49]` raises `Invalid_argument[28.2]`.

**Since:** 4.13

Raises `Invalid_argument` if `bound` $\le 0$.

`val int_in_range : min:int -> max:int -> int`

`Random-int_in_range` ~`min` ~`max` returns a random integer between `min` (inclusive) and `max` (inclusive). Both `min` and `max` are allowed to be negative; `min` must be less than or equal to `max`.

If both bounds fit in 32-bit signed integers (that is, if $-2^{31} \le min$ and $max < 2^{31}$), then `int_in_range` yields identical output across systems with varying `int` sizes.

**Since:** 5.2

Raises `Invalid_argument` if `min > max`.

`val int32 : Int32.t -> Int32.t`

`Random-int32` bound returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0.

Raises `Invalid_argument` if `bound $\le 0$`.

`val int32_in_range : min:int32 -> max:int32 -> int32`

`Random-int32_in_range` ~`min` ~`max` returns a random integer between `min` (inclusive) and `max` (inclusive). Both `min` and `max` are allowed to be negative; `min` must be less than or equal to `max`.

**Since:** 5.2

Raises `Invalid_argument` if `min > max`.

`val nativeint : Nativeint.t -> Nativeint.t`

`Random nativeint` bound returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0.

Raises `Invalid_argument` if `bound $\le 0$`.

`val nativeint_in_range : min:nativeint -> max:nativeint -> nativeint`

`Random nativeint_in_range` ~`min` ~`max` returns a random integer between `min` (inclusive) and `max` (inclusive). Both `min` and `max` are allowed to be negative; `min` must be less than or equal to `max`.
# Chapter 29

## The compiler front-end

This chapter describes the OCaml front-end, which declares the abstract syntax tree used by the compiler, provides a way to parse, print and pretty-print OCaml code, and ultimately allows one to write abstract syntax tree preprocessors invoked via the `-ppx` flag (see chapters 13 and 16).

It is important to note that the exported front-end interface follows the evolution of the OCaml language and implementation, and thus does not provide **any** backwards compatibility guarantees.

The front-end is a part of **compiler-libs** library. Programs that use the **compiler-libs** library should be built as follows:

```
ocamlfind ocamlc other options -package compiler-libs.common other files
ocamlfind ocamlopt other options -package compiler-libs.common other files
```

Use of the `ocamlfind` utility is recommended. However, if this is not possible, an alternative method may be used:

```
ocamlc other options -I +compiler-libs ocamlcommon.cma other files
ocamlopt other options -I +compiler-libs ocamlcommon.cmxa other files
```

For interactive use of the **compiler-libs** library, start `ocaml` and type
```
#load "compiler-libs/ocamlcommon.cma";;.
```

### 29.1 Module Ast_mapper : The interface of a -ppx rewriter

A -ppx rewriter is a program that accepts a serialized abstract syntax tree and outputs another, possibly modified, abstract syntax tree. This module encapsulates the interface between the compiler and the -ppx rewriters, handling such details as the serialization format, forwarding of command-line flags, and storing state.

`Ast_mapper.mapper`[29.1] enables AST rewriting using open recursion. A typical mapper would be based on `Ast_mapper.default_mapper`[29.1], a deep identity mapper, and will fall back on it for handling the syntax it does not modify. For example:

```
open Asttypes
open Parsetree
open Ast_mapper
```
**Since: 5.2**

**Raises** Invalid_argument if min > max.

val int64: Int64.t -> Int64.t

Random.int64 bound returns a random integer between 0 (inclusive) and bound (exclusive). bound must be greater than 0.

**Raises** Invalid_argument if bound ≤ 0.

val int64_in_range : min:int64 -> max:int64 -> int64

Random.int64_in_range ~min ~max returns a random integer between min (inclusive) and max (inclusive). Both min and max are allowed to be negative; min must be less than or equal to max.

**Since: 5.2**

**Raises** Invalid_argument if min > max.

val float: float -> float

Random.float bound returns a random floating-point number between 0 and bound (inclusive). If bound is negative, the result is negative or zero. If bound is 0, the result is 0.

val bool: unit -> bool

Randombool () returns true or false with probability 0.5 each.

val bits32 : unit -> Int32.t

Random.bits32 () returns 32 random bits as an integer between Int32.min_int[29.29] and Int32.max_int[29.29].

**Since: 4.14**

val bits64 : unit -> Int64.t

Random.bits64 () returns 64 random bits as an integer between Int64.min_int[29.30] and Int64.max_int[29.30].

**Since: 4.14**

val nativebits : unit -> Nativeint.t

Random nativebits () returns 32 or 64 random bits (depending on the bit width of the platform) as an integer between Nativeint.min_int[29.39] and Nativeint.max_int[29.39].

**Since: 4.14**
```kotlin
let test_mapper argv =
  { default_mapper with
    expr = fun mapper expr ->
      match expr with
      | { pexp_desc = Pexp_extension ({ txt = "test" }, PStr [])} ->
        Ast_helper.Expinia nt (Const_int 42)
      | other -> default_mapper .expr mapper other; }
```

```kotlin
let () =
  register "ppx_test" test_mapper
```

This -ppx rewriter, which replaces [%test] in expressions with the constant 42, can be compiled using ocamlc -o ppx_test -I +compiler-libs ocamlcommon.cma ppx_test.ml.

**Warning:** this module is unstable and part of compiler-libs[29].

## A generic Parsetree mapper

```kotlin
type mapper =
  { attribute : mapper -> Parsetree.attribute -> Parsetree.attribute ;
    attributes : mapper -> Parsetree.attribute list -> Parsetree.attribute list ;
    binding_op : mapper -> Parsetree.bindin g_op -> Parsetree.bindin g_op ;
    case : mapper -> Parsetree.case -> Parsetree.case ;
    cases : mapper -> Parsetree.case list -> Parsetree.case list ;
    class_statement : mapper ->
      Parsetree.class_statement -> Parsetree.class_statement ;
    class_description : mapper ->
      Parsetree.class_description -> Parsetree.class_description ;
    class_expr : mapper -> Parsetree.class_expr -> Parsetree.class_expr ;
    class_field : mapper -> Parsetree.class_field -> Parsetree.class_field ;
    class_signatu re : mapper -> Parsetree.class_signatu re -> Parsetree.class_signatu re ;
    class_structure : mapper -> Parsetree.class_structure -> Parsetree.class_structure ;
    class_type : mapper -> Parsetree.class_type -> Parsetree.class_type ;
    class_type_statement : mapper ->
      Parsetree.class_type_statement -> Parsetree.class_type_statement ;
    class_type_description : mapper ->
      Parsetree.class_type_description -> Parsetree.class_type_description ;
    class_type_field : mapper -> Parsetree.class_type_field -> Parsetree.class_type_field ;
    constant : mapper -> Parsetree constant -> Parsetree constant ;
    constructor_statement : mapper ->
      Parsetree.constructor_statement -> Parsetree.constructor_statement ;
    expr : mapper -> Parsetree .expression -> Parsetree .expression ;
    extension : mapper -> Parsetree.extension -> Parsetree.extension ;
    extension_constructor : mapper ->
      Parsetree.extension_constructor -> Parsetree.extension_constructor ;
    include_statement : mapper ->
      Parsetree.include_statement -> Parsetree.include_statement ;
```
Advanced functions

The functions from module `Random.State`[29.49] manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program.

module State :
sig

type t

The type of PRNG states.

val make : int array -> t

Create a new state and initialize it with the given seed.

val make self_init : unit -> t

Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in `Random self_init`[29.49].

val copy : t -> t

Return a copy of the given state.

val bits : t -> int

val int : t -> int -> int

val full_int : t -> int -> int

val int_in_range : t -> min:int -> max:int -> int

val int32 : t -> Int32.t -> Int32.t

val int32_in_range : t -> min:int32 -> max:int32 -> int32

val nativeint : t -> Nativeint.t -> Nativeint.t

val nativeint_in_range : t -> min:nativeint -> max:nativeint -> nativeint

val int64 : t -> Int64.t -> Int64.t

val int64_in_range : t -> min:int64 -> max:int64 -> int64

val float : t -> float -> float

val bool : t -> bool

val bits32 : t -> Int32.t

val bits64 : t -> Int64.t

val nativebits : t -> Nativeint.t

These functions are the same as the basic functions, except that they use (and update) the given PRNG state instead of the default one.

val split : t -> t
```hcl
include_description : mapper ->
Parsetree.include_description -> Parsetree.include_description;
label labels : mapper ->
Parsetree.label labels -> Parsetree.label labels;
location : mapper -> Location.t -> Location.t;
module binding : mapper -> Parsetree.module binding -> Parsetree.module binding;
module declaration : mapper ->
Parsetree.module declaration -> Parsetree.module declaration;
module substitution : mapper ->
Parsetree.module substitution -> Parsetree.module substitution;
module_expr : mapper -> Parsetree.module_expr -> Parsetree.module_expr;
module_type : mapper -> Parsetree.module_type -> Parsetree.module_type;
module_type declaration : mapper ->
Parsetree.module_type declaration -> Parsetree.module_type declaration;
open declaration : mapper -> Parsetree.open declaration -> Parsetree.open declaration;
open description : mapper -> Parsetree.open description -> Parsetree.open description;
pat : mapper -> Parsetree.pattern -> Parsetree.pattern;
payload : mapper -> Parsetree_payload -> Parsetree_payload;
signature : mapper -> Parsetree signature -> Parsetree signature;
signature_item : mapper -> Parsetree signature_item -> Parsetree signature_item;
structure : mapper -> Parsetree structure -> Parsetree structure;
structure_item : mapper -> Parsetree structure_item -> Parsetree structure_item;
typ : mapper -> Parsetree.core_type -> Parsetree.core_type;
type declaration : mapper -> Parsetree.type declaration -> Parsetree.type declaration;
type extension : mapper -> Parsetree.type extension -> Parsetree.type extension;
type exception : mapper -> Parsetree.type exception -> Parsetree.type exception;
type kind : mapper -> Parsetree.type kind -> Parsetree.type kind;
value binding : mapper -> Parsetree.value binding -> Parsetree.value binding;
value description : mapper ->
Parsetree.value description -> Parsetree.value description;
with constraint : mapper -> Parsetree.with constraint -> Parsetree.with constraint;
}
```

A mapper record implements one "method" per syntactic category, using an open recursion style: each method takes as its first argument the mapper to be applied to children in the syntax tree.

```hcl
val default_mapper : mapper
```

A default mapper, which implements a "deep identity" mapping.

## Apply mappers to compilation units

```hcl
val tool_name : unit -> string
```

Can be used within a ppx preprocessor to know which tool is calling it `ocamlc`, `ocamlopt`, `ocamldoc`, `ocamldep`, `ocaml`, ... Some global variables that reflect
Draw a fresh PRNG state from the given PRNG state. (The given PRNG state is
modified.) The new PRNG is statistically independent from the given PRNG. Data can
be drawn from both PRNGs, in any order, without risk of correlation. Both PRNGs can
be split later, arbitrarily many times.

Since: 5.0

val to_binary_string : t -> string

Serializes the PRNG state into an immutable sequence of bytes. See
Random.State.of_binary_string[29.49] for deserialization.

The `string` type is intended here for serialization only, the encoding is not
human-readable and may not be printable.

Note that the serialization format may differ across OCaml versions.

Since: 5.1

val of_binary_string : string -> t

Deserializes a byte sequence obtained by calling

`Random.State.to_binary_string[29.49]`. The resulting PRNG state will produce the
same random numbers as the state that was passed as input to

`Random.State.to_binary_string[29.49]`.

Since: 5.1

Raises `Failure` if the input is not in the expected format.

Note that the serialization format may differ across OCaml versions.

Unlike the functions provided by the ` Marshal`[29.36] module, this function either
produces a valid state or fails cleanly with a `Failure` exception. It can be safely used on
user-provided, untrusted inputs.

end

val get_state : unit -> State.t

`get_state()` returns a fresh copy of the current state of the domain-local generator (which is
used by the basic functions).

val set_state : State.t -> unit

`set_state s` updates the current state of the domain-local generator (which is used by the
basic functions) by copying the state `s` into it.

val split : unit -> State.t

Draw a fresh PRNG state from the current state of the domain-local generator used by the
default functions. (The state of the domain-local generator is modified.) See
`Random.State.split`[29.49].

Since: 5.0
command-line options are automatically synchronized between the calling tool and the ppx
preprocessor: `Clflags.include_dirs[??]`, `Load_path[??]`, `Clflags.open_modules[??]`, `Clflags.for_package[??]`, `Clflags.debug[??]`.

`val apply : source:string -> target string -> mapper -> unit`

Apply a mapper (parametrized by the unit name) to a dumped parsetree found in the *source* file and put the result in the *target* file. The *structure* or *signature* field of the mapper is applied to the implementation or interface.

`val run_main : (string list -> mapper) -> unit`

Entry point to call to implement a standalone -ppx rewriter from a mapper, parametrized by
the command line arguments. The current unit name can be obtained from
*Location.input_name* [29.3]. This function implements proper error reporting for uncaught
exceptions.

## Registration API

`val register_function : (string -> (string list -> mapper) -> unit) ref`

`val register : string -> (string list -> mapper) -> unit`

Apply the *register_function*. The default behavior is to run the mapper immediately, taking arguments from the process command line. This is to support a scenario where a mapper is linked as a stand-alone executable.

It is possible to overwrite the *register_function* to define "-ppx drivers", which combine
several mappers in a single process. Typically, a driver starts by defining
*register_function* to a custom implementation, then lets ppx rewriters (linked statically or
dynamically) register themselves, and then run all or some of them. It is also possible to have
-ppx drivers apply rewriters to only specific parts of an AST.

The first argument to *register* is a symbolic name to be used by the ppx driver.

## Convenience functions to write mappers

`val map_opt : ('a -> 'b) -> 'a option -> 'b option`

`val extension_of_error : Location.error -> Parsetree.extension`

Encode an error into an 'ocaml.error' extension node which can be inserted in a generated
Parsetree. The compiler will be responsible for reporting the error.

`val attribute_of_warning : Location.t -> string -> Parsetree.attribute`

Encode a warning message into an 'ocaml.ppwarning' attribute which can be inserted in a
generated Parsetree. The compiler will be responsible for reporting the warning.
## 29.50 Module Repr: Functions defined on the low-level representations of values.

Since: 5.4

### Physical comparison

```hkl
val phys_equal : 'a -> 'a -> bool
```

`phys_equal` `e1 e2` tests for physical equality of `e1` and `e2`. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, `phys_equal e1 e2` is true if and only if physical modification of `e1` also affects `e2`. On non-mutable types, the behavior of `phys_equal` is implementation-dependent; however, it is guaranteed that `phys_equal e1 e2` implies `compare e1 e2 = 0`.

### Polymorphic comparison

```hkl
val equal : 'a -> 'a -> bool
```

`equal e1 e2` tests for structural equality of `e1` and `e2`. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises `Invalid_argument`. Equality between cyclic data structures may not terminate.

```hkl
val compare : 'a -> 'a -> int
```

`compare x y` returns 0 if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. The ordering implemented by `compare` is compatible with the comparison predicates (`=`)[28.2], (`<`)[28.2] and (`>`)[28.2], as well as the `equal` function defined above, with one difference on the treatment of the float value `nan`[28.2]. Namely, the comparison predicates treat `nan` as different from any other float value, including itself; while `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation.

`compare` applied to functional values may raise `Invalid_argument`. `compare` applied to cyclic structures may not terminate.

The `compare` function can be used as the comparison function required by the `Set.Make`[29.54] and `Map.Make`[29.35] functors, as well as the `List.sort`[29.33] and `Array.sort`[29.2] functions.

```hkl
val min : 'a -> 'a -> 'a
```

Return the smaller of the two arguments. The result is unspecified if one of the arguments contains the float value `nan`[28.2].

```hkl
val max : 'a -> 'a -> 'a
```

Return the greater of the two arguments. The result is unspecified if one of the arguments contains the float value `nan`[28.2].
Helper functions to call external mappers

val add_ppx_context_str :

tool_name: string -> Parsetree structure -> Parsetree. structure

Extract information from the current environment and encode it into an attribute which is prepended to the list of structure items in order to pass the information to an external processor.

val add_ppx_context_sig :

tool_name: string -> Parsetree. signature -> Parsetree. signature

Same as add_ppx_context_str, but for signatures.

val drop_ppx_context_str :

restore: bool -> Parsetree. structure -> Parsetree. structure

Drop the ocaml.ppx.Context attribute from a structure. If restore is true, also restore the associated data in the current process.

val drop_ppx_context_sig :

restore: bool -> Parsetree. signature -> Parsetree. signature

Same as drop_ppx_context_str, but for signatures.

## Cookies

Cookies are used to pass information from a ppx processor to a further invocation of itself, when called from the OCaml toplevel (or other tools that support cookies).

val set cookie : string -> Parsetree. expression -> unit

val get cookie : string -> Parsetree. expression option

## 29.2 Module Asttypes : Auxiliary AST types used by parsetree and typedtree.

**Warning:** this module is unstable and part of compiler-libs[29].

type constant =

| Const_int of int

| Const_char of char

| Const_string of string * Location.t * string option

| Const_float of string

| Const_int32 of int32

| Const_int64 of int64

| Const_nativeint of nativeint

type rec_flag =

| Nonrecursive
## 29.51 Module Result : Result values.

Result values handle computation results and errors in an explicit and declarative manner without resorting to exceptions.

**Since:** 4.08

### Results

```python
type ('a, 'e) t = ('a, 'e) result =
| Ok of 'a
| Error of 'e
```

The type for result values. Either a value `Ok v` or an error `Error e`.

```python
val ok : 'a -> ('a, 'e) result
    ok v is Ok v.
```

```python
val error : 'e -> ('a, 'e) result
    error e is Error e.
```

```python
val value : ('a, 'e) result -> default:'a -> 'a
    value r ~default is v if r is Ok v and default otherwise.
```

```python
val get_ok : ('a, 'e) result -> 'a
    get_ok r is v if r is Ok v and raise otherwise.
    Raises Invalid_argument if r is Error _.
```

```python
val get_ok' : ('a, string) result -> 'a
    get_ok' is like Result.get_ok[29.51] but in case of error uses the error message for raising
    Invalid_argument.
    Since: 5.4
```

```python
val get_error : ('a, 'e) result -> 'e
    get_error r is e if r is Error e and raise otherwise.
    Raises Invalid_argument if r is Ok _.
```

```python
val error_to_failure : ('a, string) result -> 'a
    error_to_failure r is v if r is Ok v and raises Failure e if r is Error e.
    Since: 5.4
```

```python
val bind : ('a, 'e) result ->
    ('a -> ('b, 'e) result) -> ('b, 'e) result
    bind r f is f v if r is Ok v and r if r is Error _.
```
```
| Recursive
type direction_flag =
| Upto
| Downto
type private_flag =
| Private
| Public
type mutable_flag =
| Immutable
| Mutable
type virtual_flag =
| Virtual
| Concrete
type override_flag =
| Override
| Fresh
type closed_flag =
| Closed
| Open
type label = string
type arg_label =
| Nolabel
| Labelled of string
    label:T -> ...
| Optional of string
    ?label:T -> ...
type 'a loc = 'a Location.loc =
{ txt : 'a ;
  loc : Location.t ;
}
type variance =
| Covariant
| Contravariant
| NoVariance
type injectivity =
| Injective
| NoInjectivity
```

## 29.3 Module Location: Source code locations (ranges of positions), used in parsetree.

**Warning:** this module is unstable and part of compiler-libs[29].
val join : (( 'a, 'e) result , 'e) result -> ( 'a, 'e) result
         join rr is r if rr is Ok r and rr if rr is Error _.

val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result
  map f r is Ok (f v) if r is Ok v and r if r is Error _.

val product : ('a, 'e) result ->
('b, 'e) result -> ('a * 'b, 'e) result
  product r0 r1 is Ok (v0, v1) if r0 is Ok v0 and r1 is Ok v2 and otherwise returns the
  error of r0, if any, or the error of r1.

Since: 5.4

val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result
  map_error f r is Error (f e) if r is Error e and r if r is Ok _.

val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c
fold ~ok ~error r is ok v if r is Ok v and error e if r is Error e.

val retract : ('a, 'a) result -> 'a
  retract r is v if r is Ok v or Error v.

Since: 5.4

val iter : ('a -> unit) -> ('a, 'e) result -> unit
  iter f r is f v if r is Ok v and () otherwise.

val iter_error : ('e -> unit) -> ('a, 'e) result -> unit
  iter_error f r is f e if r is Error e and () otherwise.

Predicates and comparisons

val is_ok : ('a, 'e) result -> bool
  is_ok r is true if and only if r is Ok _.

val is_error : ('a, 'e) result -> bool
  is_error r is true if and only if r is Error _.

val equal :
  ok:('a -> 'a -> bool) ->
  error:('e -> 'e -> bool) ->
  ('a, 'e) result -> ('a, 'e) result -> bool
  equal ~ok ~error r0 r1 tests equality of r0 and r1 using ok and error to respectively
  compare values wrapped by Ok _ and Error _.
```h
type t = Warnings.loc =
{
    loc_start : LexingITAner position;
    loc_end : LexingITAner position;
    loc_ghost : bool;
}
```

Note on the use of `LexingITAner` in this module. If `pos_fname = ""`, then use `!input_name` instead. If `pos_lnum = -1`, then `pos_bol = 0`. Use `pos_cnum` and re-parse the file to get the line and character numbers. Else all fields are correct.

```h
val none : t
```
An arbitrary value of type `t`; describes an empty ghost range.

```h
val is_none : t -> bool
```
True for `Location.some`, false any other location

```h
val in_file : string -> t
```
Return an empty ghost range located in a given file.

```h
val init : Lexing.lexbuf -> string -> unit
```
Set the file name and line number of the `lexbuf` to be the start of the named file.

```h
val curr : Lexing.lexbuf -> t
```
Get the location of the current token from the `lexbuf`.

```h
val symbol_rloc : unit -> t
val symbol_gloc : unit -> t
val rhs_loc : int -> t
```
`rhs_loc` n returns the location of the symbol at position n, starting at 1, in the current parser rule.

```h
val rhs_interval : int -> int -> t
val get_pos_info : LexingITAner position -> string * int * int
```
file, line, char

```h
type 'a loc =
{
    txt : 'a ;
    loc : t ;
}
val mknoloc : 'a -> 'a loc
val mkloc : 'a -> t -> 'a loc
```

## Input info

```h
val input_name : string ref
val input_lexbuf : Lexing.lexbuf option ref
val input_phrase_buffer : Buffer.t option ref
```
```hkl
val compare :
    ok:('a -> 'a -> int) ->
    error:('e -> 'e -> int) ->
    ('a, 'e) result -> ('a, 'e) result -> int

compare ~ok ~error r0 r1 totally orders r0 and r1 using ok and error to respectively
compare values wrapped by Ok _ and Error _ . Ok _ values are smaller than Error
 _ values.
```

## Converting

```hkl
val to_option : ('a, 'e) result -> 'a option
    to_option r is r as an option, mapping Ok v to Some v and Error _ to None.
```

```hkl
val to_list : ('a, 'e) result -> 'a list
    to_list r is [v] if r is Ok v and [] otherwise.
```

```hkl
val to_seq : ('a, 'e) result -> 'a Seq.t
    to_seq r is r as a sequence. Ok v is the singleton sequence containing v and Error _ is the
    empty sequence.
```

## Syntax

```hkl
module Syntax :
    sig
        val ( let* ) :
            ('a, 'e) result ->
            ('a -> ('b, 'e) result) -> ('b, 'e) result
        ( let* ) is Result.bind[29.51].
        val ( and* ) : ('a, 'e) result ->
            ('b, 'e) result -> ('a * 'b, 'e) result
        ( and* ) is Result product[29.51].
        val let+ : ('a, 'e) result -> ('a -> 'b) -> ('b, 'e) result
        ( let+ ) is Result.map[29.51].
        val and+ : ('a, 'e) result ->
            ('b, 'e) result -> ('a * 'b, 'e) result
        ( and+ ) is Result product[29.51].
    end
```

Binding operators.

Since: 5.4
## TLEVEL-SPECIFIC FUNCTIONS

`val echo_eof : unit -> unit`

`val separate_new_message : Format formatter -> unit`

`val reset : unit -> unit`

## Rewriting path

`val rewrite_absolute_path : string -> string`

`rewrite_absolute_path` path rewrites path to honor the `BUILD_PATH_PREFIX_MAP` variable if it is set. It does not check whether path is absolute or not. The result is as follows:

* If `BUILD_PATH_PREFIX_MAP` is not set, just return `path`.

* otherwise, rewrite using the mapping (and if there are no matching prefixes that will just return `path`).

See

the `BUILD_PATH_PREFIX_MAP`

spec[https://reproducible-builds.org/specs/build-path-prefix-map/]

`val rewrite_find_first_existing : string -> string option`

`rewrite_find_first_existing` path uses a `BUILD_PATH_PREFIX_MAP` mapping and tries to find a source in mapping that maps to a result that exists in the file system. There are the following return values:

* `None`, means either

- `BUILD_PATH_PREFIX_MAP` is not set and `path` does not exist, or

- no source prefixes of `path` in the mapping were found,

* `Some target`, means `target` exists and either

- `BUILD_PATH_PREFIX_MAP` is not set and `target = path`, or

- `target` is the first file (in priority order) that `path` mapped to that exists in the file system.

* `Not_found` raised, means some source prefixes in the map were found that matched `path`, but none of them existed in the file system. The caller should catch this and issue an appropriate error message.

See

the `BUILD_PATH_PREFIX_MAP`

spec[https://reproducible-builds.org/specs/build-path-prefix-map/]

`val rewrite_find_all_existing_dirs : string -> string list`
## 29.52 Module Scanf: Formatted input functions.

**Alert unsynchronized_access.** Unsynchronized accesses to Scanning.in_channel are a programming error.

### Introduction

#### Functional input with format strings

The module Scanf[29.52] provides formatted input functions or scanners.

The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a *formatted input channel* (or *scanning buffer*) and has type **Scanf.Scanning.in_channel**[29.52]. The more general formatted input function reads from any scanning buffer and is named **bscanf**.

Generally speaking, the formatted input functions have 3 arguments:

* the first argument is a source of characters for the input,

* the second argument is a format string that specifies the values to read,

* the third argument is a *receiver function* that is applied to the values read.

Hence, a typical call to the formatted input function **Scanf.bscanf**[29.52] is `bscanf ic fmt f`, where:

* `ic` is a source of characters (typically a *formatted input channel* with type **Scanf.Scanning.in_channel**[29.52]),

* `fmt` is a format string (the same format strings as those used to print material with module **Format**[29.47] or **Format**[29.23]),

* `f` is a function that has as many arguments as the number of values to read in the input according to `fmt`.

#### A simple example

As suggested above, the expression `bscanf ic "%d" f` reads a decimal integer `n` from the source of characters `ic` and returns `f n`.

For instance,

* if we use `stdin` as the source of characters (`Scanf.Scanning.stdin`[29.52] is the predefined *formatted input channel* that reads from standard input),

* if we define the receiver `f` as `let f x = x + 1`,

then `bscanf Scanning.stdin "%d" f` reads an integer `n` from the standard input and returns `f n` (that is `n + 1`). Thus, if we evaluate `bscanf stdin "%d" f`, and then enter 41 at the keyboard, the result we get is 42.
`rewrite_find_all_existing_dirs` `dir` accumulates a list of existing directories, `dirs`, that are the result of mapping a potentially abstract directory, `dir`, over all the mapping pairs in the `BUILD_PATH_PREFIX_MAP` environment variable, if any. The list `dirs` will be in priority order (head as highest priority).

The possible results are:

* `[]`, means either

- `BUILD_PATH_PREFIX_MAP` is not set and `dir` is not an existing directory, or

- if set, then there were no matching prefixes of `dir`.

* Some `dirs`, means `dirs` are the directories found. Either

- `BUILD_PATH_PREFIX_MAP` is not set and `dirs = [dir]`, or

- it was set and `dirs` are the mapped existing directories.

* `Not_found` raised, means some source prefixes in the map were found that matched `dir`, but none of mapping results were existing directories (possibly due to misconfiguration). The caller should catch this and issue an appropriate error message.

See

the `BUILD_PATH_PREFIX_MAP`

spec[https://reproducible-builds.org/specs/build-path-prefix-map/]

`val absolute_path : string -> string`

`absolute_path` `path` first makes an absolute path, `s` from `path`, prepending the current working directory if `path` was relative. Then `s` is rewritten using `rewrite_absolute_path`. Finally the result is normalized by eliminating instances of `'.'` or `'..'`.

## Printing locations

`val show_filename : string -> string`

In `-absname` mode, return the absolute path for this filename. Otherwise, returns the filename unchanged.

`val print_filename : Format formatter -> string -> unit`

`val print_loc : Format formatter -> t -> unit`

`val printLocs : Format formatter -> t list -> unit`

## Tolevel-specific location highlighting

`val highlight_terminfo : Lexing.lexbuf -> Format formatter -> t list -> unit`
Formatted input as a functional feature

The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also
largely different, simpler, and yet more powerful: the formatted input functions are higher-order
functionals and the parameter passing mechanism is just the regular function application not the
variable assignment based mechanism which is typical for formatted input in imperative languages;
the OCaml format strings also feature useful additions to easily define complex tokens; as expected
within a functional programming language, the formatted input functions also support polymorphism,
in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml
formatted input facility is fully type-checked at compile time.

Unsynchronized accesses

Unsynchronized accesses to a `Scanf.Scanning.in_channel[29.52]` may lead to an invalid `Scanf.Scanning.in_channel[29.52]` state. Thus, concurrent accesses to `Scanf.Scanning.in_channel[29.52]`s must be synchronized (for instance with a `Mutex.t[29.38]`).

Formatted input channel

module Scanning :

sig

type in_channel

The notion of input channel for the `Scanf[29.52]` module: those channels provide all the machinery necessary to read from any source of characters, including a `in_channel[28.2]` value. A `Scanf.Scanning.in_channel` value is also called a *formatted input channel* or *equivalently a scanning buffer*. The type `Scanf.Scanning.scanbuf[29.52]` below is an alias for `Scanning.in_channel`. Note that a `Scanning.in_channel` is not concurrency-safe: concurrent use may produce arbitrary values or exceptions.

Since: 3.12

type scanbuf = in_channel

The type of scanning buffers. A scanning buffer is the source from which a formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far.

Note: a scanning action may often require to examine one character in advance; when this 'lookahead' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character yet to be read.

val stdin : in_channel

The standard input notion for the `Scanf[29.52]` module. `Scanning.stdin` is the `Scanf.Scanning.in_channel[29.52]` formatted input channel attached to `stdin[28.2]`.

Note: in the interactive system, when input is read from `stdin[28.2]`, the newline character that triggers evaluation is part of the input; thus, the scanning specifications must properly skip this additional newline character (for instance, simply add a `'\n'` as the last character of the format string).
## Reporting errors and warnings

### The type of reports and report printers

```hkl
type msg = (Format formatter -> unit) loc

val msg : ?loc:t ->
         ('a, Format formatter, unit, msg) format4 -> 'a

type reportKind =
  | Report_error
  | Report_warning of string
  | Report_warning_as_error of string
  | Report_alert of string
  | Report_alert_as_error of string

type report =
  { kind : reportKind ;
    main : msg ;
    sub : msg list ;
  }

type reportPrinter =
  { pp : report_printers -> Format formatter -> report -> unit ;
    pp_report    : report_printers ->
                      report -> Format formatter -> reportASYM -> unit ;
    pp_main         : report_printers ->
                      report -> Format formatter -> t -> unit ;
    pp_main_txt     : report_printers ->
                      report ->
                      Format formatter -> (Format formatter -> unit) -> unit ;
    pp_submsg      : report_printers ->
                      report -> Format formatter -> msg list -> unit ;
    pp_submsg      : report_printers ->
                      report -> Format formatter -> msg -> unit ;
    pp_submsgLoc   : report_printers ->
                      report -> Format formatter -> t -> unit ;
    pp_submsg_txt  : report_printers ->
                      report ->
                      Format formatter -> (Format formatter -> unit) -> unit ;
  }
```

A printer for reports, defined using open-recursion. The goal is to make it easy to define new printers by re-using code from existing ones.

### Report printers used in the compiler

```hkl
val batch_mode_printers : report_printers
val terminfo_tosevel_printers : Lexing.lexbuf -> report_printers
```
**Since: 3.12**

type file_name = string

A convenient alias to designate a file name.

**Since: 4.00**

val open_in : file_name -> in_channel

Scanning.open_in fname returns a Scnf.Scanning.in_channel[29.52] formatted
input channel for bufferized reading in text mode from file fname.

Note: `open_in` returns a formatted input channel that efficiently reads characters in large chunks; in contrast, `from_channel` below returns formatted input channels that must read one character at a time, leading to a much slower scanning rate.

**Since: 3.12**

val open_in_bin : file_name -> in_channel

Scanning.open_in_bin fname returns a Scnf.Scanning.in_channel[29.52]
formatted input channel for bufferized reading in binary mode from file fname.

**Since: 3.12**

val close_in : in_channel -> unit

Closes the in_channel[28.2] associated with the given
Scnf.Scanning.in_channel[29.52] formatted input channel.

**Since: 3.12**

val from_file : file_name -> in_channel

An alias for Scnf.Scanning.open_in[29.52] above.

val from_file_bin : string -> in_channel

An alias for Scnf.Scanning.open_in_bin[29.52] above.

val from_string : string -> in_channel

Scanning.from_string s returns a Scnf.Scanning.in_channel[29.52] formatted
input channel which reads from the given string. Reading starts from the first character
in the string. The end-of-input condition is set when the end of the string is reached.

val from_function : (unit -> char) -> in_channel

Scanning.from_function f returns a Scnf.Scanning.in_channel[29.52] formatted
input channel with the given function as its reading method.

When scanning needs one more character, the given function is called.

When the function has no more character to provide, it must signal an end-of-input
condition by raising the exception End_of_file.
val best_t LEVEL printer : unit -> report_printers

Detects the terminal capabilities and selects an adequate printer

## Printing a report

val print_report : Format formatter -> report -> unit

Display an error or warning report.

val report_printers : (unit -> report_printers) ref

Hook for redefining the printer of reports.

The hook is a `unit -> report_printers` and not simply a `report_printers`: this is useful so that it can detect the type of the output (a file, a terminal, ...) and select a printer accordingly.

val default_report_printers : unit -> report_printers

Original report printer for use in hooks.

## Reporting warnings

### Converting a Warnings.t into a report

val report_warning : t -> Warnings.t -> report option

`report_warning` loc w produces a report for the given warning w, or None if the warning is not to be printed.

val warning_reporter : (t -> Warnings.t -> report option) ref

Hook for intercepting warnings.

val default_warning_reporter : t -> Warnings.t -> report option

Original warning reporter for use in hooks.

### Printing warnings

val formatter_for_warnings : Format formatter ref

val print_warning : t -> Format formatter -> Warnings.t -> unit

Prints a warning. This is simply the composition of `report_warning` and `print_report`.

val prerr_warning : t -> Warnings.t -> unit

Same as `print_warning`, but uses `!formatter_for_warnings` as output formatter.
```python
val from_channel : in_channel -> in_channel
```

`Scanning.from_channel` `ic` returns a `Scanf.Scanning.in_channel`[29.52] formatted input channel which reads from the regular `in_channel`[28.2] input channel `ic` argument. Reading starts at current reading position of `ic`.

```python
val end_of_input : in_channel -> bool
```

`Scanning.end_of_input` `ic` tests the end-of-input condition of the given `Scanf.Scanning.in_channel`[29.52] formatted input channel.

```python
val beginning_of_input : in_channel -> bool
```

`Scanning-beginning_of_input` `ic` tests the beginning of input condition of the given `Scanf.Scanning.in_channel`[29.52] formatted input channel.

```python
val name_of_input : in_channel -> string
```

`Scanning.name_of_input` `ic` returns the name of the character source for the given `Scanf.Scanning.in_channel`[29.52] formatted input channel.

**Since: 3.09**

end

## Type of formatted input functions

```python
type ('a, 'b, 'c, 'd) scanner = ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c
```

The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the `Scanf.Scanning.in_channel`[29.52] formatted input channel `ic`.

For instance, the `Scanf.scanf`[29.52] function below has type `('a, 'b, 'c, 'd) scanner`, since it is a formatted input function that reads from `Scanf.Scanning.stdin`[29.52]: `scanf fmt f` applies `f` to the arguments specified by `fmt`, reading those arguments from `stdin`[28.2] as expected.

If the format `fmt` has some `%r` indications, the corresponding formatted input functions must be provided *before* receiver function `f`. For instance, if `read_elem` is an input function for values of type `t`, then `bscnf ic "%r;" read_elem f` reads a value `v` of type `t` followed by a `';'` character, and returns `f v`.

**Since: 3.10**

```python
type ('a, 'b, 'c, 'd) scanner_opt = ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) format6 -> 'c
```

### exception Scan_failure of string

When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan_failure`.
## Reporting alerts

### Converting an Alert.t into a report

val report_alert : t -> Warnings.alert -> report option

report_alert loc w produces a report for the given alert w, or None if the alert is not to be printed.

val alert_reporter : (t -> Warnings.alert -> report option) ref

Hook for intercepting alerts.

val default_alert_reporter : t -> Warnings.alert -> report option

Original alert reporter for use in hooks.

## Printing alerts

val print_alert : t -> Format formatter -> Warnings.alert -> unit

Prints an alert. This is simply the composition of report_alert and print_report.

val prerr Alert : t -> Warnings.alert -> unit

Same as print Alert, but uses !formatter_for_warnings as output formatter.

val deprecated : ?def:t -> ?use:t -> t -> string -> unit

Prints a deprecation alert.

val alert : ?def:t ->

?use:t -> kind: string -> t -> string -> unit

Prints an arbitrary alert.

val auto_include Alert : string -> unit

Prints an alert that -I +lib has been automatically added to the load path

val deprecated_script Alert : string -> unit

deprecated_script Alert command foo prints an alert that command foo has been deprecated in favour of command ./foo

## Reporting errors

type error = report

An error is a report which report\_kind must be Report\_error.
## The general formatted input function

`val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner`

`bscanf` is a function that reads characters from the `Scanf.Scanning.in_channel` [29.52] formatted input channel `ic` and converts them to values according to format string `fmt`. As a final step, a receiver function `f` is applied to the values read and gives the result of the `bscanf` call.

For instance, if `f` is the function `fun s i -> i + 1`, then `Scanf.sscnf "x = 1" "%s = %i"` `f` returns 2.

Arguments `r1` to `rN` are user-defined input functions that read the argument corresponding to the `%r` conversions specified in the format string.

`val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt`

Same as `Scanf.bscanf` [29.52], but returns `None` in case of scanning failure.

Since: 5.0

## Format string description

The format string is a character string which contains three types of objects:

* plain characters, which are simply matched with the characters of the input (with a special case for space and line feed, see [29.52]),

* conversion specifications, each of which causes reading and conversion of one argument for the function `f` (see [29.52]),

* scanning indications to specify boundaries of tokens (see scanning [29.52]).

## The space character in format strings

As mentioned above, a plain character in the format string is just matched with the next character of the input; however, two characters are special exceptions to this rule: the space character (`' '`) or ASCII code 32) and the line feed character (`'
'`) or ASCII code 10). A space does not match a single space character, but any amount of 'whitespace' in the input. More precisely, a space inside the format string matches *any number* of tab, space, line feed and carriage return characters. Similarly, a line feed character in the format string matches either a single line feed or a carriage return followed by a line feed.

Matching *any* amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call `bscnf ib "Price = %d $"` (`fun p -> p`) succeeds and returns 1 when reading an input with various whitespace in it, such as `Price = 1 $`, `Price = 1 $`, or even `Price=1$`.

## Conversion specifications in format strings

Conversion specifications consist in the `%` character, followed by an optional flag, an optional field width, and followed by one or two conversion characters.

The conversion characters and their meanings are:
val error : ?loc:t -> ?sub:msg list -> string -> error

val errorf :

?loc:t ->
?sub:msg list ->
('a, Format.Formatter, unit, error) format4 -> 'a

val error_of_printers :

?loc:t ->
?sub:msg list ->
(Format.Formatter -> 'a -> unit) -> 'a -> error

val error_of_printers_file : (Format.Formatter -> 'a -> unit) -> 'a -> error

## Automatically reporting errors for raised exceptions

val register_error_of_exn : (exn -> error option) -> unit

Each compiler module which defines a custom type of exception which can surface as a user-visible error should register a "printer" for this exception using register_error_of_exn. The result of the printer is an error value containing a location, a message, and optionally sub-messages (each of them being located as well).

val error_of_exn : exn -> [ `Already_displayed | `Ok of error ] option
exception Error of error

Raising Error e signals an error e; the exception will be caught and the error will be printed.

exception Already_displayed_error

Raising Already_displayed_error signals an error which has already been printed. The exception will be caught, but nothing will be printed

val raise_errorf :

?loc:t ->
?sub:msg list ->
('a, Format.Formatter, unit, 'b) format4 -> 'a

val report_exception : Format.Formatter -> exn -> unit

Reraise the exception if it is unknown.

## 29.4 Module Longident : Long identifiers, used in parsetree.

**Warning:** this module is unstable and part of compiler-libs[29].

To print a longident, see Pprintast.longident[29.7], using Format.asprintf[28.21] to convert to a string.

type t =
| Lident of string
• d: reads an optionally signed decimal integer (0-9+).

* i: reads an optionally signed integer (usual input conventions for decimal (0-9+), hexadecimal (0x[0-9a-f]+ and 0X[0-9A-F]+), octal (0o[0-7]+), and binary (0b[0-1]+) notations are understood).

• u: reads an unsigned decimal integer.

• x or X: reads an unsigned hexadecimal integer ([0-9a-fA-F]+).

• o: reads an unsigned octal integer ([0-7]+).

* s: reads a string argument that spreads as much as possible, until the following bounding condition holds:

- a whitespace has been found (see [29.52]),

- a scanning indication (see scanning [29.52]) has been encountered,

- the end-of-input has been reached.

Hence, this conversion always succeeds: it returns an empty string if the bounding condition
holds when the scan begins.

• S: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml).

• c: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification %0c. Raise Invalid_argument, if the field width specification is greater than 1.

• C: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml).

• f, e, E, g, G: reads an optionally signed floating-point number in decimal notation, in the style dddd.ddd e/E+-dd.

• h, H: reads an optionally signed floating-point number in hexadecimal notation.

• F: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned).

• B: reads a boolean argument (true or false).

• b: reads a boolean argument (for backward compatibility; do not use in new programs).

• ld, li, lu, lx, lX, lo: reads an int32 argument to the format specified by the second letter for regular integers.

• nd, ni, nu, nx, nX, no: reads a nativeint argument to the format specified by the second letter for regular integers.
```
| Ldot of t * string
| Lapply of t * t
val flatten : t -> string list
val unflatten : string list -> t option
```

For a non-empty list `l`, `unflatten l` is Some lid where lid is the long identifier created by concatenating the elements of `l` with `Ldot`. `unflatten []` is None.

```
val last : t -> string
val parse : string -> t
```

*Deprecated.* this function may misparse its input, use "Parse.longident" or "Longident.unflatten"This function is broken on identifiers that are not just "Word.Word.word"; for example, it returns incorrect results on infix operators and extended module paths.

If you want to generate long identifiers that are a list of dot-separated identifiers, the function `Longident.unflatten[29.4]` is safer and faster. `Longident.unflatten[29.4]` is available since OCaml 4.06.0.

If you want to parse any identifier correctly, use the long-identifiers functions from the `Parse[29.5]` module, in particular `Parse.longident[29.5]`. They are available since OCaml 4.11, and also provide proper input-location support.

## 29.5 Module Parse : Entry points in the parser

**Warning:** this module is unstable and part of compiler-libs[29].

```
val implementation : Lexing.lexbuf -> Parsetree structure
val interface : Lexing.lexbuf -> Parsetree signature
val toplevel_phrase : Lexing.lexbuf -> Parsetree toplevel_phrase
val use_file : Lexing.lexbuf -> Parsetree toplevel_phrase list
val core_type : Lexing.lexbuf -> Parsetree core_type
val expression : Lexing.lexbuf -> Parsetree expression
val pattern : Lexing.lexbuf -> Parsetree pattern
val module_type : Lexing.lexbuf -> Parsetree module_type
val module_expr : Lexing.lexbuf -> Parsetree module_expr
```

The functions below can be used to parse Longident safely.

```
val longident : Lexing.lexbuf -> Longident.t
```

The function `longident` is guaranteed to parse all subclasses of `Longident.t`[29.4] used in OCaml: values, constructors, simple or extended module paths, and types or module types.

However, this function accepts inputs which are not accepted by the compiler, because they combine functor applications and infix operators. In valid OCaml syntax, only value-level identifiers may end with infix operators `Foo.( + )`. Moreover, in value-level identifiers the
* `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: reads an `int64` argument to the format specified by the second letter for regular integers.

* `[ range ]`: reads characters that matches one of the characters mentioned in the range of characters `range` (or not mentioned in it, if the range starts with `^`). Reads a `string` that can be empty, if the next input character does not match the range. The set of characters from `c1` to `c2` (inclusively) is denoted by `c1-c2`. Hence, `%[0-9]` returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, `%[0-9a-f]` returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the `^` in case of range negation); hence `[]` matches a `]` character and `[^]` matches any character that is not ]. Use `%%` and `@` to include a `%` or a `@` in a range.

* `r`: user-defined reader. Takes the next `ri` formatted input function and applies it to the scanning buffer `ib` to read the next argument. The input function `ri` must therefore have type `Scanning.in_channel -> 'a` and the argument read has type `'a`.

* `{ fmt %}`: reads a format string argument. The format string read must have the same type as the format string specification `fmt`. For instance, `"%{ %i %}"` reads any format string that can read a value of type `int`; hence, if `s` is the string `"fmt:\"number is %u\""`, then `Scanf.sссанf s "fmt: %{%i%}"` succeeds and returns the format string `"number is %u"`.

* `( fmt %)`: scanning sub-format substitution. Reads a format string `rf` in the input, then goes on scanning with `rf` instead of scanning with `fmt`. The format string `rf` must have the same type as the format string specification `fmt` that it replaces. For instance, `"%( %i %)"` reads any format string that can read a value of type `int`. The conversion returns the format string read `rf`, and then a value read using `rf`. Hence, if `s` is the string `"\"%4d\"1234.00", then `Scanf.sссанf s "%(%i%)"` (`fun fmt i -> fmt, i`) evaluates to (`"%4d", 1234`). This behaviour is not mere format substitution, since the conversion returns the format string read as additional argument. If you need pure format substitution, use special flag `_` to discard the extraneous argument: conversion `%_`( `fmt %`) reads a format string `rf` and then behaves the same as format string `rf`. Hence, if `s` is the string `"\"%4d\"1234.00", then `Scanf.sссанf s "%_(%i%)"` is simply equivalent to `Scanf.sссанf "1234.00" "%4d"`.

* `l`: returns the number of lines read so far.

* `n`: returns the number of characters read so far.

* `N` or `L`: returns the number of tokens read so far.

* `!`: matches the end of input condition.

* `%`: matches one `%` character in the input.

* `@`: matches one `@` character in the input.

* `;`: does nothing.
module path `Foo` must be simple (`M.N` rather than `F(X)`): functor applications may only appear in type-level identifiers. As a consequence, a path such as `F(X).( + )` is not a valid OCaml identifier; but it is accepted by this function.

The next functions are specialized to a subclass of `Longident.t`[29.4]

`val val_ident : Lexing.lexbuf -> Longident.t`

This function parses a syntactically valid path for a value. For instance, `x`, `M.x`, and `(+.)` are valid. Contrarily, `M.A`, `F(X).x`, and `true` are rejected.

Longident for OCaml's value cannot contain functor application. The last component of the `Longident.t`[29.4] is not capitalized, but can be an operator `A.Path.To.(%.%.(..)<-)`

`val constr_ident : Lexing.lexbuf -> Longident.t`

This function parses a syntactically valid path for a variant constructor. For instance, `A`, `M.A` and `M.(::)` are valid, but both `M.a` and `F(X).A` are rejected.

Longident for OCaml's variant constructors cannot contain functor application. The last component of the `Longident.t`[29.4] is capitalized, or it may be one of the special constructors: `true`, `false`, `()`, `[]`, `(::)`. Among those special constructors, only `(::)` can be prefixed by a module path (`A.B.C.(::)`).

`val simple_module_path : Lexing.lexbuf -> Longident.t`

This function parses a syntactically valid path for a module. For instance, `A`, and `M.A` are valid, but both `M.a` and `F(X).A` are rejected.

Longident for OCaml's module cannot contain functor application. The last component of the `Longident.t`[29.4] is capitalized.

`val extended_module_path : Lexing.lexbuf -> Longident.t`

This function parses syntactically valid path for an extended module. For instance, `A.B` and `F(A).B` are valid. Contrarily, `(.%)` or `[]` are both rejected.

The last component of the `Longident.t`[29.4] is capitalized.

`val type_ident : Lexing.lexbuf -> Longident.t`

This function parses syntactically valid path for a type or a module type. For instance, `A`, `t`, `M.t` and `F(X).t` are valid. Contrarily, `(.%)` or `[]` are both rejected.

In path for type and module types, only operators and special constructors are rejected.

## 29.6 Module Parsetree: Abstract syntax tree produced by parsing

**Warning:** this module is unstable and part of compiler-libs[29].

```hml
type constant =
  | Pconst_integer of string * char option
```
Following the % character that introduces a conversion, there may be the special flag `_`: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if `f` is the function `fun i -> i + 1`, and `s` is the string `"x = 1"`, then `Scanf.sscnf s "%_s = %i" f` returns 2.

The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, `%6d` reads an integer, having at most 6 decimal digits; `%4f` reads a float with at most 4 characters; and `%8[\000-\255]` returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input).

Notes:

* as mentioned above, a `%s` conversion always succeeds, even if there is nothing to read in the input: in this case, it simply returns `""`.

* in addition to the relevant digits, `'-'` characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions.

* the `scanf` facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module `Str[32.1]`), stream parsers, `ocamllex`-generated lexers, `ocamlyacc`-generated parsers.

## Scanning indications in format strings

Scanning indications appear just after the string conversions `%s` and `%[ range ]` to delimit the end of the token. A scanning indication is introduced by a `@` character, followed by some plain character `c`. It means that the string token should end just before the next matching `c` (which is skipped). If no `c` character is encountered, the string token spreads as much as possible. For instance, `"%s@\t"` reads a string up to the next tab character or to the end of input. If a `@` character appears anywhere else in the format string, it is treated as a plain character.

Note:

* As usual in format strings, `%` and `@` characters must be escaped using `%%` and `%%@`; this rule still holds within range specifications and scanning indications. For instance, format `"%s@%%"` reads a string up to the next `%` character, and format `"%s@%%@"` reads a string up to the next `@`.

* The scanning indications introduce slight differences in the syntax of `Scanf[29.52]` format strings, compared to those used for the `AMENTF[29.47]` module. However, the scanning indications are similar to those used in the `Format[29.23]` module; hence, when producing formatted text to be scanned by `Scanf.bscanf[29.52]`, it is wise to use printing functions from the `Format[29.23]` module (or, if you need to use functions from `AMENTF[29.47]`, banish or carefully double check the format strings that contain `'@'` characters).

## Exceptions during scanning

Scanners may raise the following exceptions when the input cannot be read according to the format string:
Integer constants such as `3 31 3L 3n`.

Suffixes `[g-z]` `[G-Z]` are accepted by the parser. Suffixes except `'l'`, `'L'` and `'n'` are rejected by the typechecker.

**Pconst_char of char**

Character such as `'c'`.

**Pconst_string of string * Location.t * string option**

Constant string such as `"constant"` or `{delim|other constant|delim}`.

The location span the content of the string, without the delimiters.

**Pconst_float of string * char option**

Float constant such as `3.4`, `2e5` or `1.4e-4`.

Suffixes `g-zG-Z` are accepted by the parser. Suffixes are rejected by the typechecker.

`type location_stack = Location.t list`

## Extension points

```hml
type attribute =
{
    attr_name : string Asttypes.loc ;
    attr_payload : payload ;
    attr_loc : Location.t ;
}
```

Attributes such as `[@id ARG]` and `[@@id ARG]`.

Metadata containers passed around within the AST. The compiler ignores unknown attributes.

**type extension = string Asttypes.loc * payload**

Extension points such as `[%id ARG]` and `[%%id ARG]`.

Sub-language placeholder – rejected by the typechecker.

**type attributes = attribute list**

```hml
type payload =
| PStr of structure
| PSig of signature
```

: SIG in an attribute or an extension point

**PTyp of core_type**

: T in an attribute or an extension point

**PPat of pattern * expression option**

? P or ? P when E, in an attribute or an extension point
* Raise `ScanfScan_failure[29.52]` if the input does not match the format.

* Raise `Failure` if a conversion to a number is not possible.

* Raise `End_of_file` if the end of input is encountered while some more characters are needed to read the current conversion specification.

* Raise `Invalid_argument` if the format string is invalid.

**Note:**

* as a consequence, scanning a `%s` conversion never raises exception `End_of_file`: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or `""` if none were ever read.

## Specialised formatted input functions

**val sscnf :** `string -> ('a, 'b, 'c, 'd) scanner`

Same as `Scanf.bscanf[29.52]`, but reads from the given string.

**val sscnf_opt :** `string -> ('a, 'b, 'c, 'd) scanner_opt`

Same as `Scanf.sscnf[29.52]`, but returns `None` in case of scanning failure.

**Since:** 5.0

**val scanf :** `('a, 'b, 'c, 'd) scanner`

Same as `Scanf.bscanf[29.52]`, but reads from the predefined formatted input channel

`Scanf.Scanning.stdin[29.52]` that is connected to `stdin[28.2]`.

**val scanf_opt :** `('a, 'b, 'c, 'd) scanner_opt`

Same as `Scanf.sprintf[29.52]`, but returns `None` in case of scanning failure.

**Since:** 5.0

**val kscnf :**

`Scanning.in_channel ->`

`(Scanning.in_channel -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner`

Same as `Scanf.bscanf[29.52]`, but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments.

**val ksscnf :**

`string ->`

`(Scanning.in_channel -> exn -> 'd) -> ('a, 'b, 'c, 'd) scanner`

Same as `Scanf.kscnf[29.52]` but reads from the given string.

**Since:** 4.02
Core language

Type expressions

```c
type core_type =
{
    ptyp_desc : core_type_desc ;
    ptyp_loc : Location.t ;
    ptyp_loc_stack : location_stack ;
    ptyp_attributes : attributes ;
    ...
    [@id1] [@id2]
}

type core_type_desc =
| Ptyp_any
- 
| Ptyp_var of string
    A type variable such as 'a
| PtypArrow of Asttypes.arg_label * core_type * core_type
    PtypArrow.lbl, T1, T2) represents:
    • T1 -> T2 when lbl is Nolabel[??],
    • ~1:T1 -> T2 when lbl is Labelled[??],
    • ?1:T1 -> T2 when lbl is Optional[??].
| Ptyp_tuple of core_type list
    Ptyp_tuple([T1; ... ; Tn]) represents a product type T1 * ... * Tn.
    Invariant: n >= 2.
| Ptyp_constr of Longident.t Asttypes.loc * core_type list
    Ptyp_constr(lident, 1) represents:
    • tconstr when l=[],
    • T tconstr when l=[T],
    • (T1, ..., Tn) tconstr when l=[T1; ... ; Tn].
| Ptyp_object of object_field list * Asttypes closed_flag
    Ptyp_object([ l1:T1; ...; ln:Tn ], flag) represents:
    • < l1:T1; ...; ln:Tn > when flag is Closed[??],
    • < l1:T1; ...; ln:Tn; .. > when flag is Open[??].
| Ptyp_class of Longident.t Asttypes.loc * core_type list
    Ptyp_class(tconstr, 1) represents:
    • #tconstr when l=[],
```
Reading format strings from input

val b扫描format:
    Scanning.in_channel ->
    ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
    ((('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g

    bscanf_format ic fmt f reads a format string token from the formatted input channel ic,
    according to the given format string fmt, and applies f to the resulting format string value.

Since: 3.09

Raises Scan_failure if the format string value read does not have the same type as fmt.

val sscanf_format:
    string ->
    ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
    ((('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> 'g

    Same as Scanf.bscanf_format[29.52], but reads from the given string.

Since: 3.09

val format_from_string:
    string ->
    ('a, 'b, 'c, 'd, 'e, 'f) format6 ->
    ('a, 'b, 'c, 'd, 'e, 'f) format6

    format_from_string s fmt converts a string argument to a format string, according to the
    given format string fmt.

Since: 3.10

Raises Scan_failure if s, considered as a format string, does not have the same type as fmt.

val unescaped: string -> string

unescaped s return a copy of s with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, Scanf.unescaped has the following property: for all string s, Scanf.unescaped (String.escaped s) = s.

Always return a copy of the argument, even if there is no escape sequence in the argument.

Since: 4.00

Raises Scan_failure if s is not properly escaped (i.e. s has invalid escape sequences or
special characters that are not properly escaped). For instance, Scanf.unescaped "\"" will
fail.

29.53 Module Seq : Sequences.

A sequence of type 'a Seq.t can be thought of as a **delayed list**, that is, a list whose elements are computed only when they are demanded by a consumer. This allows sequences to be produced and
* `T #tconstr` when `l=[T]`,

* `(T1, ..., Tn) #tconstr` when `l=[T1; ... ; Tn]`.

| `Ptyp_alias` of `core_type` * `string`
  T as 'a.

| `Ptyp_variant` of `row_field` list * `Asttypes closed_flag` * `Asttypes.label` list option
  `Ptyp_variant([`A;`B], flag, labels) represents:

* `[`A|`B`] when flag is `Closed[??]`, and labels is `None`,

* `[> `A|`B`] when flag is `Open[??]`, and labels is `None`,

* `[< `A|`B`] when flag is `Closed[??]`, and labels is `Some []`,

* `[< `A|`B` > `X` `Y`] when flag is `Closed[??]`, and labels is `Some ["X";"Y"]`.

| `Ptyp_pol` of `string` `Asttypes.loc` list * `core_type`
  'a1 ... 'an. T

Can only appear in the following context:

* As the `Parsetree.core_type[29.6]` of a `Ppat_constraint[??]`
  node corresponding to a constraint on a let-binding:

```
let x : 'a1 ... 'an. T = e ...
```

* Under `Cfk_virtual[??]` for methods (not values).

* As the `Parsetree.core_type[29.6]` of a `Pctf_method[??]` node.

* As the `Parsetree.core_type[29.6]` of a `Pexp_pol[??]` node.

* As the `pld_type[??]` field of a `Parsetree.label labels` [29.6].

* As a `Parsetree.core_type[29.6]` of a `Ptyp_object[??]` node.

* As the `pval_type[??]` field of a `Parsetree.value_description[29.6]`.

| `Ptyp_package` of `package_type`
  (module S).

| `Ptyp_extension` of `extension`
  [%id].

type `package_type` = `Longident.t` `Asttypes.loc` *
(Longident.t `Asttypes.loc` * `core_type`) list
As `Parsetree/package_type[29.6]` typed values:

* `(S, [])` represents `(module S),`
transformed lazily (one element at a time) rather than eagerly (all elements at once). This also
allows constructing conceptually infinite sequences.

The type `'a Seq.t` is defined as a synonym for `unit -> 'a Seq.node`. This is a function type: therefore, it is opaque. The consumer can **query** a sequence in order to request the next element (if there is one), but cannot otherwise inspect the sequence in any way.

Because it is opaque, the type `'a Seq.t` does *not* reveal whether a sequence is:

* **persistent**, which means that the sequence can be used as many times as desired, producing the same elements every time, just like an immutable list; or

* **ephemeral**, which means that the sequence is not persistent. Querying an ephemeral sequence might have an observable side effect, such as incrementing a mutable counter. As a common special case, an ephemeral sequence can be **affine**, which means that it must be queried at most once.

It also does *not* reveal whether the elements of the sequence are:

* **pre-computed and stored** in memory, which means that querying the sequence is cheap;

* **computed when first demanded and then stored** in memory, which means that querying the sequence once can be expensive, but querying the same sequence again is cheap; or

* **re-computed every time they are demanded**, which may or may not be cheap.

It is up to the programmer to keep these distinctions in mind so as to understand the time and space requirements of sequences.

For the sake of simplicity, most of the documentation that follows is written under the implicit assumption that the sequences at hand are persistent. We normally do not point out *when* or *how many times* each function is invoked, because that would be too verbose. For instance, in the description of `map`, we write: "if `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`. If we wished to be more explicit, we could point out that the transformation takes place on demand: that is, the elements of `map f xs` are computed only when they are demanded. In other words, the definition `let ys = map f xs` terminates immediately and does not invoke `f`. The function call `f x0` takes place only when the first element of `ys` is demanded, via the function call `ys()`. Furthermore, calling `ys()` twice causes `f x0` to be called twice as well. If one wishes for `f` to be applied at most once to each element of `xs`, even in scenarios where `ys` is queried more than once, then one should use `let ys = memoize (map f xs)`.

As a general rule, the functions that build sequences, such as `map`, `filter`, `scan`, `take`, etc., produce sequences whose elements are computed only on demand. The functions that eagerly consume sequences, such as `is_empty`, `find`, `length`, `iter`, `fold_left`, etc., are the functions that force computation to take place.

When possible, we recommend using sequences rather than dispensers (functions of type `unit -> 'a option` that produce elements upon demand). Whereas sequences can be persistent or ephemeral, dispensers are always ephemeral, and are typically more difficult to work with than sequences. Two conversion functions, `Seq.to_dispenser[29.53]` and `Seq.of_dispenser[29.53]`, are provided.

Since: 4.07
* `(S, [(t1, T1); ...; (tn, Tn)])` represents `(module S with type t1 = T1 and ... and tn = Tn)`.

```h
type row_field =
{
    prf_desc : row_field_desc ;
    prf_loc : Location.t ;
    prf_attributes : attributes ;
}

type row_field_desc =
| Rtag of Asttypes.label Asttypes.loc * bool * core_type list
    Rtag(`A, b, l) represents:
    * `A` when b is true and l is [],
    * `A` of T when b is false and l is [T],
    * `A` of T1 & .. & Tn when b is false and l is [T1;...Tn],
    * `A` of & T1 & .. & Tn when b is true and l is [T1;...Tn].
```

* The `bool` field is true if the tag contains a constant (empty) constructor.

* `&` occurs when several types are used for the same constructor (see 4.2 in the manual).

```c
| Rinherit of core_type
    [ | t ]
type object_field =
{
    pof_desc : object_field_desc ;
    pof_loc : Location.t ;
    pof_attributes : attributes ;
}
type object_field_desc =
| Otag of Asttypes.label Asttypes.loc * core_type
| Oinherit of core_type
```

## Patterns

```c
type pattern =
{
    ppat_desc : pattern_desc ;
    ppat_loc : Location.t ;
    ppat_loc_stack : location_stack ;
    ppat_attributes : attributes ;
    ...      [@id1] [@id2]
}
type pattern_desc =
| Ppat_any
```
type 'a t = unit -> 'a node

A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. Such a sequence is queried by performing a function application `xs()`. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail.

type 'a node =
| Nil
| Cons of 'a * 'a t

A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence.

## Consuming sequences

The functions in this section consume their argument, a sequence, either partially or completely:

* `is_empty` and `uncons` consume the sequence down to depth 1. That is, they demand the first argument of the sequence, if there is one.

* `iter`, `fold_left`, `length`, etc., consume the sequence all the way to its end. They terminate only if the sequence is finite.

* `for_all`, `exists`, `find`, etc. consume the sequence down to a certain depth, which is a priori unpredictable.

Similarly, among the functions that consume two sequences, one can distinguish two groups:

* `iter2` and `fold_left2` consume both sequences all the way to the end, provided the sequences have the same length.

* `for_all2`, `exists2`, `equal`, `compare` consume the sequences down to a certain depth, which is a priori unpredictable.

The functions that consume two sequences can be applied to two sequences of distinct lengths: in that case, the excess elements in the longer sequence are ignored. (It may be the case that one excess element is demanded, even though this element is not used.)

None of the functions in this section is lazy. These functions are consumers: they force some computation to take place.

val `is_empty` : 'a t -> bool

`is_empty xs` determines whether the sequence `xs` is empty.

It is recommended that the sequence `xs` be persistent. Indeed, `is_empty xs` demands the head of the sequence `xs`, so, if `xs` is ephemeral, it may be the case that `xs` cannot be used any more after this call has taken place.

**Since:** 4.14

val `uncons` : 'a t -> ('a * 'a t) option
The pattern _.

| Ppat_var of string Asttypes.loc

A variable pattern such as x

| Ppat_alias of pattern * string Asttypes.loc

An alias pattern such as P as 'a

| PpatConstant of constant

Patterns such as 1, 'a', "true", 1.0, 11, 1L, 1n

| Ppat_interval of constant * constant

Patterns such as 'a'..'z'.

Other forms of interval are recognized by the parser but rejected by the type-checker.

| Ppat_tuple of pattern list

Patterns (P1, ..., Pn).

Invariant: n >= 2

| Ppat_construct of Longident.t Asttypes.loc

* (string Asttypes.loc list * pattern) option

Ppat_construct(C, args) represents:

• C when args is None,

• C P when args is Some ([], P)

• C (P1, ..., Pn) when args is Some ([], Ppat_tuple [P1; ...; Pn])

• C (type a b) P when args is Some ([a; b], P)

| Ppat le variant of Asttypes.label * pattern option

Ppat le variant(`A, pat) represents:

• `A when pat is None,

• `A P when pat is Some P

| Ppat_record of (Longident.t Asttypes.loc * pattern) list * Asttypes closed_flag

Ppat_record([((11, P1); ...; (1n, Pn)], flag) represents:

• { l1=P1; ...; ln=Pn } when flag is Closed[??]

• { l1=P1; ...; ln=Pn; _ } when flag is Open[??]

Invariant: n > 0

| Ppat_array of pattern list

Pattern [| P1; ...; Pn |]

| Ppat_or of pattern * pattern

Pattern P1 | P2
If `xs` is empty, then `uncons xs` is `None`.

If `xs` is nonempty, then `uncons xs` is `Some (x, ys)` where `x` is the head of the sequence and `ys` its tail.

**Since:** 4.14

`val length : 'a t -> int`

`length xs` is the length of the sequence `xs`.

Does not terminate if `xs` is infinite.

**Since:** 4.14

`val iter : ('a -> unit) -> 'a t -> unit`

`iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right.

It terminates only if the sequence `xs` is finite.

`val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc`

`fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right.

An accumulator of type `'a` is threaded through the calls to `f`.

It terminates only if the sequence `xs` is finite.

`val iteri : (int -> 'a -> unit) -> 'a t -> unit`

`iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`.

It terminates only if the sequence `xs` is finite.

`iteri f xs` is equivalent to `iter (fun (i, x) -> f i x) (zip (ints 0) xs)`.

**Since:** 4.14

`val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc`

`fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`.

An accumulator of type `'b` is threaded through the calls to `f`.

It terminates only if the sequence `xs` is finite.

`fold_lefti f accu xs` is equivalent to `fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)`.

**Since:** 4.14

`val for_all : ('a -> bool) -> 'a t -> bool`

`for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`.

May not terminate if `xs` is infinite.

**Since:** 4.14
| Ppat_constraint of pattern * core_type
  Pattern (P : T)

| Ppat_type of Longident.t Asttypes.loc
  Pattern #tconst

| Ppat_lazy of pattern
  Pattern lazy P

| Ppat_unpack of string option Asttypes.loc
  Ppat_unpack(s) represents:

• (module P) when s is Some "P"

• (module_) when s is None

Note: (module P : S) is represented as Ppat_constraint(Ppat_unpack(Some "P"), Ptyp_package S)

| Ppat_exception of pattern
  Pattern exception P

| Ppat_extensions of extension
  Pattern [%id]

| Ppat_open of Longident.t Asttypes.loc * pattern
  Pattern M.(P)

Value expressions

type expression =
{ pexp_desc : expression_desc ;
pexp_loc : Location.t ;
pexp_loc_stack : location_stack ;
pexp_attributes : attributes ;
... [@id1] [@id2]

}

type expression_desc =
| Pexp_ident of Longident.t Asttypes.loc
  Identifiers such as x and M.x

| PexpConstant of constant
  Expressions constant such as 1, 'a', "true", 1.0, 11, 1L, 1n

| Pexp_let of Asttypes.rec_flag * value list * expression
  Pexp_let flag, [(P1,E1) ; ... ; (Pn,En)], E) represents:

• let P1 = E1 and ... and Pn = EN in E when flag is Nonrecursive[??],
val exists : ('a -> bool) -> 'a t -> bool

exists p xs determines whether at least one element x of the sequence xs satisfies p x.

May not terminate if `xs` is infinite.

**Since:** 4.14

val find : ('a -> bool) -> 'a t -> 'a option

find p xs returns Some `x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element.

It returns `None` if there is no such element.

May not terminate if `xs` is infinite.

**Since:** 4.14

val find_index : ('a -> bool) -> 'a t -> int option

find_index p xs returns Some `i`, where `i` is the index of the first element of the sequence `xs` that satisfies `p x`, if there is such an element.

It returns `None` if there is no such element.

May not terminate if `xs` is infinite.

**Since:** 5.1

val find_map : ('a -> 'b option) -> 'a t -> 'b option

find_map f xs returns Some `y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`.

It returns `None` if there is no such element.

May not terminate if `xs` is infinite.

**Since:** 4.14

val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option

Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.

May not terminate if `xs` is infinite.

**Since:** 5.1

val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit

iter2 f xs ys invokes `f x` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`.

If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.

Iteration terminates only if at least one of the sequences `xs` and `ys` is finite.

`iter2 f xs ys` is equivalent to `iter (fun (x, y) -> f x y) (zip xs ys)`.

**Since:** 4.14
* let rec P1 = E1 and ... and Pn = EN in E when flag is Recursive[??].

| Pexp_function of case list

function P1 -> E1 | ... | Pn -> En

| Pexp Fun of Asttypes.arg_label * expression option * pattern
* expression

PexpFun.lbl, exp0, P, E1) represents:

* fun P -> E1 when.lbl is Nolabel[??] and exp0 is None

* fun ~l:P -> E1 when.lbl is Labelled l[??] and exp0 is None

* fun ?l:P -> E1 when.lbl is Optional l[??] and exp0 is None

* fun ?l:(P = E0) -> E1 when.lbl is Optional l[??] and exp0 is Some E0

Notes:

* If E0 is provided, only Optional[??] is allowed.

* fun P1 P2 .. Pn -> E1 is represented as nested PexpFun[??].

* let f P = E is represented using PexpFun[??].

| Pexp_apply of expression * (Asttypes.arg_label * expression) list

Pexp_apply(E0, [(l1, E1) ; ... ; (ln, En)]) represents E0 ~l1:E1 ...
~ln:En

li can be Nolabel[??] (non labeled argument), Labelled[??] (labelled arguments) or
Optional[??] (optional argument).

Invariant: n > 0

| Pexp_match of expression * case list

match E0 with P1 -> E1 | ... | Pn -> En

| Pexpkirry of expression * case list

try E0 with P1 -> E1 | ... | Pn -> En

| Pexp_tuple of expression list

Expressions (E1, ..., En)

Invariant: n >= 2

| Pexp_construct of Longident.t Asttypes.loc * expression option

Pexp_construct(C, exp) represents:

• C when exp is None,

• C E when exp is Some E,

* C (E1, ..., En) when exp is Some (Pexp_tuple[E1;...;En])

| Pexp le variant of Asttypes.label * expression option
```hkl
val fold_left2 : ('acc -> 'a -> 'b -> 'acc) -> 'acc -> 'a t -> 'b t -> 'acc
```

`fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`.

An accumulator of type `'a` is threaded through the calls to `f`.

If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.

Iteration terminates only if at least one of the sequences `xs` and `ys` is finite.

`fold_left2 f accu xs ys` is equivalent to `fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)`.

**Since:** 4.14

```hkl
val for_all2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool
```

`for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`.

If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if `xs` or `ys` is empty, then `for_all2 p xs ys` is true. This is where `for_all2` and `equal` differ: `equal eq xs ys` can be true only if `xs` and `ys` have the same length.

May not terminate if both of the sequences `xs` and `ys` are infinite.

`for_all2 p xs ys` is equivalent to `for_all (fun b -> b) (map2 p xs ys)`.

**Since:** 4.14

```hkl
val exists2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool
```

`exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`.

If the sequences `xs` and `ys` have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.

May not terminate if both of the sequences `xs` and `ys` are infinite.

`exists2 p xs ys` is equivalent to `exists (fun b -> b) (map2 p xs ys)`.

**Since:** 4.14

```hkl
val equal : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool
```

Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal.

May not terminate if both of the sequences `xs` and `ys` are infinite.

**Since:** 4.14

```hkl
val compare : ('a -> 'b -> int) -> 'a t -> 'b t -> int
```
Pexp(`A, exp) represents

• `A when exp is None

• `A E when exp is Some E

| Pexp_record of (Longident.t Asttypes.loc * expression) list
* expression option

Pexp_record([((l1,P1); ... ; (ln,Pn)], exp0) represents

• `{ l1=P1; ...; ln=Pn }` when exp0 is None

• `{ E0 with l1=P1; ...; ln=Pn }` when exp0 is Some E0

Invariant: n > 0

| Pexp_field of expression * Longident.t Asttypes.loc
E.1

| Pexp_setfield of expression * Longident.t Asttypes.loc * expression
E1.1 <- E2

| Pexp_array of expression list
[| E1; ...; En |]

| Pexp_ifthenelse of expression * expression * expression option
if E1 then E2 else E3

| Pexp_sequence of expression * expression
E1; E2

| Pexpwhile of expression * expression
while E1 do E2 done

| Pexp_for of pattern * expression * expression

* Asttypes direction_flag * expression
`Pexp_for(i, E1, E2, direction, E3)` represents:

• `for i = E1 to E2 do E3 done` when direction is `Upto[??]`

• `for i = E1 downto E2 do E3 done` when direction is `Downto[??]`

| Pexp_constraint of expression * core_type
(E : T)

| Pexp_coerce of expression * core_type option * core_type
`Pexp_coerce(E, from, T)` represents

• `(E :> T)` when from is `None`,

• `(E : TO :> T)` when from is `Some TO`.

| Pexp_send of expression * Asttypes.label Asttypes.loc
Provided the function `cmp` defines a preorder on elements, compare `cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder.

For more details on comparison functions, see `Array.sort` [29.2].

May not terminate if both of the sequences `xs` and `ys` are infinite.

**Since:** 4.14

## Constructing sequences

The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded.

`val empty : 'a t`

`empty` is the empty sequence. It has no elements. Its length is 0.

`val return : 'a -> 'a t`

`return x` is the sequence whose sole element is `x`. Its length is 1.

`val cons : 'a -> 'a t -> 'a t`

`cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`.

Writing `cons (f()) xs` causes the function call `f()` to take place immediately. For this call to be delayed until the sequence is queried, one must instead write `(fun () -> Cons(f(), xs))`.

**Since:** 4.11

`val singleton : 'a -> 'a t`

`singleton x` returns the one-element sequence containing only `x`.

**Since:** 5.4

`val init : int -> (int -> 'a) -> 'a t`

`init n f` is the sequence `f 0; f 1; ...; f (n-1)`.

`n` must be nonnegative.

If desired, the infinite sequence `f 0; f 1; ...` can be defined as `map f (ints 0)`.

**Since:** 4.14

**Raises:** `Invalid_argument` if `n` is negative.

`val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t`

`unfold` constructs a sequence out of a step function and an initial state.

If `f u` is `None` then `unfold f u` is the empty sequence. If `f u` is `Some (x, u')` then `unfold f u` is the nonempty sequence `cons x (unfold f u')`.

For example, `unfold (function [] -> None | h :: t -> Some (h, t)) 1` is equivalent to `List.to_seq 1`.

**Since:** 4.11
E # m

| Pexp_new of Longident.t Asttypes.loc
  new M.c

| Pexp_setinstvar of Asttypes.label Asttypes.loc * expression
  x <- 2

| Pexp_override of (Asttypes.label Asttypes.loc * expression) list
  {< x1 = E1; ...; xn = En >}

| Pexp_letmodule of string option Asttypes.loc * module_expr * expression
  let module M = ME in E

| Pexp_letexception of extension_constructor * expression
  let exception C in E

| Pexp assert of expression
  assert E.

Note: assert false is treated in a special way by the type-checker.

| Pexp_lazy of expression
  lazy E

| Pexpibusy of expression * core_type option
  Used for method bodies.

Can only be used as the expression under Cfk_concrete[??] for methods (not values).

| Pexp_object of class_structure
  object ... end

| Pexp_newtype of string Asttypes.loc * expression
  fun (type t) -> E

| Pexp_pack of module_expr
  (module ME).

(module ME : S) is represented as Pexp_constraint(Pexp_pack ME, Ptyp_package S)

| Pexp_open of open declaration * expression
  - M.(E)

• let open M in E

• let open! M in E

| Pexp_letop of letop

- let* P = E0 in E1

• let* P0 = E00 and* P1 = E01 in E1
val repeat : 'a -> 'a t

repeat x is the infinite sequence where the element x is repeated indefinitely.

repeat x is equivalent to cycle (return x).

Since: 4.14

val forever : (unit -> 'a) -> 'a t

forever f is an infinite sequence where every element is produced (on demand) by the
function call f().

For instance, `forever Randombool` is an infinite sequence of random bits.

`forever f` is equivalent to `map f (repeat())`.

Since: 4.14

val cycle : 'a t -> 'a t

cycle xs is the infinite sequence that consists of an infinite number of repetitions of the
sequence xs.

If `xs` is an empty sequence, then `cycle xs` is empty as well.

Consuming (a prefix of) the sequence `cycle xs` once can cause the sequence `xs` to be
consumed more than once. Therefore, `xs` must be persistent.

Since: 4.14

val iterate : ('a -> 'a) -> 'a -> 'a t

iterate f x is the infinite sequence whose elements are x, f x, f (f x), and so on.

In other words, it is the orbit of the function f, starting at x.

Since: 4.14

Transforming sequences

The functions in this section are lazy: that is, they return sequences whose elements are computed
only when demanded.

val map : ('a -> 'b) -> 'a t -> 'b t

map f xs is the image of the sequence `xs` through the transformation `f`.

If `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`.

val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t

mapi is analogous to map, but applies the function `f` to an index and an element.

`mapi f xs` is equivalent to `map2 f (ints 0) xs`.

Since: 4.14

val filter : ('a -> bool) -> 'a t -> 'a t
```
| Pexp_extension of extension
    [%id]
| Pexp_unreachable
.
type case =
{ pc_lhs : pattern ;
pc-guard : expression option ;
pc_rhs : expression ;
}
Values of type Parsetree.case[29.6] represents (P -> E) or (P when E0 -> E)
type letop =
{ let_ : binding_op ;
ands : binding_op list ;
body : expression ;
}
type binding_op =
{ pbop_op : string Asttypes.loc ;
pbop_pat : pattern ;
pbop_exp : expression ;
pbop_loc : Location.t ;
}
```

## Value descriptions

```
type value_description =
{ pval_name : string Asttypes.loc ;
pval_type : core_type ;
pvalPrim : string list ;
pval_attributes : attributes ;
... [@@id1] [@@id2]
pval_loc : Location.t ;
}
Values of type Parsetree.value_description[29.6] represents:
```

* val x: T, when pvalPrim[??] is []

* external x: T = "s1" ... "sn" when pvalPrim[??] is ["s1";..."sn"]

## Type declarations

```
type typeDeclaration =
{ ptype_name : string Asttypes.loc ;
 ptype_params : (core_type * (Asttypes.variance * Asttypes injectivity)) list ;
}