filter p xs is the sequence of the elements x of xs that satisfy p x.

In other words, `filter p xs` is the sequence `xs`, deprived of the elements `x` such that `p x` is
false.

```hkl
val filteri : (int -> 'a -> bool) -> 'a t -> 'a t
```

Same as `Seq.filter` [29.53], but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument.

Since: 5.4

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

`filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`.

`filter_map f xs` is equivalent to `map Option.get (filter Option.is_some (map f xs))`.

```hkl
val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t
```

If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators
[a0; a1; a2; ...] where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on.

Thus, `scan f a0 xs` is conceptually related to `fold_left f a0 xs`. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators.

For instance, `scan (+) 0` transforms a sequence of integers into the sequence of its partial sums.

If `xs` has length `n` then `scan f a0 xs` has length `n+1`.

Since: 4.14

```hkl
val take : int -> 'a t -> 'a t
```

`take n xs` is the sequence of the first `n` elements of `xs`.

If `xs` has fewer than `n` elements, then `take n xs` is equivalent to `xs`.

`n` must be nonnegative.

Since: 4.14

**Raises** `Invalid_argument` if `n` is negative.

```hkl
val drop : int -> 'a t -> 'a t
```

`drop n xs` is the sequence `xs`, deprived of its first `n` elements.

If `xs` has fewer than `n` elements, then `drop n xs` is empty.

`n` must be nonnegative.

`drop` is lazy: the first `n+1` elements of the sequence `xs` are demanded only when the first element of `drop n xs` is demanded.

Since: 4.14

**Raises** `Invalid_argument` if `n` is negative.
```c
('a1,...,'an) t

ptype_cstrs : (core_type * core_type * Location.t) list ;
    ... constraint T1=T1' ... constraint Tn=Tn'

ptype kind : type kind ;
ptype_private : Asttypes.private_flag ;
    for = private ...

ptype MANIFEST : core_type option ;
    represents = T

ptype_attributes : attributes ;
    ... [@@id1] [@@id2]

ptype loc : Location.t ;
}
```

Here are type declarations and their representation, for various ptype kind[??] and ptype MANIFEST[??] values:

* type t when type kind is PtypeAbstract[??], and manifest is None,

* type t = TO when type kind is PtypeAbstract[??], and manifest is Some TO,

* type t = C of T | ... when type kind is PtypeVariant[??], and manifest is None,

* type t = TO = C of T | ... when type kind is PtypeVariant[??], and manifest is Some TO,

* type t = {1: T; ...} when type kind is PtypeRecord[??], and manifest is None,

* type t = TO = {1 : T; ...} when type kind is PtypeRecord[??], and manifest is Some TO,

* type t = .. when type kind is PtypeOpen[??], and manifest is None.

```c
type type kind =
| Ptype Abstract
| Ptype Variant of constructor声明list
| Ptype Record of label声明list
    Invariant: non-empty list

| Ptype Open
```

```c
type label声明list =
{ pld_name : string Asttypes.loc ;
    pld mutable : Asttypes.mutable_flag ;
    pld_type : core_type ;
    pld loc : Location.t ;
    pld attributes : attributes ;
    l : T [@id1] [@id2]
}
```
```hkl
val takewhile : ('a -> bool) -> 'a t -> 'a t
```

`takewhile` `p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`.

**Since:** 4.14

```hkl
val dropwhile : ('a -> bool) -> 'a t -> 'a t
```

`dropwhile` `p xs` is the sequence `xs`, deprived of the prefix `takewhile p xs`.

**Since:** 4.14

```hkl
val group : ('a -> 'a -> bool) -> 'a t -> 'a t t
```

Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`.

Every element of `group eq xs` is a nonempty sequence of equal elements.

The concatenation `concat(group eq xs)` is equal to `xs`.

Consuming `group eq xs`, and consuming the sequences that it contains, can cause `xs` to be consumed more than once. Therefore, `xs` must be persistent.

**Since:** 4.14

```hkl
val memoize : 'a t -> 'a t
```

The sequence `memoize xs` has the same elements as the sequence `xs`.

Regardless of whether `xs` is ephemeral or persistent, `memoize xs` is persistent: even if it is queried several times, `xs` is queried at most once.

The construction of the sequence `memoize xs` internally relies on suspensions provided by the module `Lazy[29.31]`. These suspensions are *not* thread-safe. Therefore, the sequence `memoize xs` must *not* be queried by multiple threads concurrently.

**Since:** 4.14

### exception Forced_twice

This exception is raised when a sequence returned by `Seq once[29.53]` (or a suffix of it) is queried more than once.

**Since:** 4.14

```hkl
val once : 'a t -> 'a t
```

The sequence `once xs` has the same elements as the sequence `xs`.

Regardless of whether `xs` is ephemeral or persistent, `once xs` is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception `Forced_twice` is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once.

**Since:** 4.14

Raises `Forced_twice` if `once xs`, or a suffix of it, is queried more than once.

```hkl
val transpose : 'a t t -> 'a t t
```
}

- `{ ... ; l: T; ... }` when `pld mutable[??]` is Immutable[??],

• `{ ... ; mutable l: T; ... }` when `pld mutable[??]` is Mutable[??].

Note: T can be a `Ptyp poly[??].`

```h
type constructor declaration =
{
    pcd_name : string Asttypes.loc ;
    pcd_vars : string Asttypes.loc list ;
    pcd_args : constructor arguments ;
    pcd_res : core_type option ;
    pcd_loc : Location.t ;
    pcd_attributes : attributes ;

    C of ... [@id1] [@id2]
}
```

}

```h
type constructor arguments =
| Pcstr_tuple of core_type list
| Pcstr_record of label declaration list
```

Values of type `Parsetree.Constructor_declaration[29.6]` represents the constructor arguments of:

• C of `T1 * ... * Tn` when `res = None`, and `args = Pcstr_tuple [T1; ... ; Tn]`,

• C: `TO` when `res = Some TO`, and `args = Pcstr_tuple []`,

• C: `T1 * ... * Tn -> TO` when `res = Some TO`, and `args = Pcstr_tuple [T1; ... ; Tn]`,

• C of `{...}` when `res = None`, and `args = Pcstr_record [...]`,

• C: `{...} -> TO` when `res = Some TO`, and `args = Pcstr_record [...]`.

```h
type type extension =
{
    ptyext_path : Longident.t Asttypes.loc ;
    ptyext_params : (core_type * (Asttypes.variance * Asttypes injectivity)) list ;
    ptyext constructors : extension constructor list ;
    ptyext_private : Asttypes.private_flag ;
    ptyext loc : Location.t ;
    ptyext_attributes : attributes ;

    ... @@id1 @@id2
}
```

}

Definition of new extensions constructors for the extensive sum type `t (type t += ...)`.

```h
type extension constructor =
{ pext_name : string Asttypes.loc ;
```
If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`.

The rows of the matrix `xss` are not required to have the same length.

The matrix `xss` is not required to be finite (in either direction).

The matrix `xss` must be persistent.

**Since:** 4.14

## Combining sequences

```hkl
val append : 'a t -> 'a t -> 'a t
```

`append xs ys` is the concatenation of the sequences `xs` and `ys`.

Its elements are the elements of `xs`, followed by the elements of `ys`.

**Since:** 4.11

```hkl
val concat : 'a t t -> 'a t
```

If `xss` is a sequence of sequences, then `concat xss` is its concatenation.

If `xss` is the sequence `xs0; xs1; ...` then `concat xss` is the sequence `xs0 @ xs1 @ ...`.

**Since:** 4.13

```hkl
val flat_map : ('a -> 'b t) -> 'a t -> 'b t
```

`flat_map f xs` is equivalent to `concat (map f xs)`.

```hkl
val concat_map : ('a -> 'b t) -> 'a t -> 'b t
```

`concat_map f xs` is equivalent to `concat (map f xs)`.

`concat_map` is an alias for `flat_map`.

**Since:** 4.13

```hkl
val zip : 'a t -> 'b t -> ('a * 'b) t
```

`zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`.

If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.

`zip xs ys` is equivalent to `map2 (fun a b -> (a, b)) xs ys`.

**Since:** 4.14

```hkl
val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t
```

`map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`.

If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored.
```c
pextKind : extension_constructorKind ;
pextLoc : Location.t ;
pext_attributes : attributes ;
    C of ... [@id1] [@id2]
}

type type_exception =
{ ptyexn_constructor : extension_constructor ;
ptyexnLoc : Location.t ;
ptyexn_attributes : attributes ;
    ... [@@id1] [@@id2]
}

Definition of a new exception (exception E).

type extension_constructorKind =
| Pext Decl of string Asttypes.loc list * constructor_argument
    * core_type option
    Pext Decl(existentials, c_args, t_opt) describes a new extension constructor.
    It can be:
```

* C of T1 * ... * Tn when:

- existentials is [],

- c_args is [T1; ...; Tn],

- t_opt is None

* C: TO when

- existentials is [],

- c_args is [],

- t_opt is Some TO.

* C: T1 * ... * Tn -> TO when

- existentials is [],

- c_args is [T1; ...; Tn],

- t_opt is Some TO.

* C: 'a... . T1 * ... * Tn -> TO when

- existentials is ['a;...],

- c_args is [T1; ... ; Tn],

- t_opt is Some TO.

```c
| Pext_rebind of Longident.t Asttypes.loc
    Pext_rebind(D) re-export the constructor D with the new name C
```
`map2 f xs ys` is equivalent to `map (fun (x, y) -> f x y) (zip xs ys)`.

**Since:** 4.14

`val interleave : 'a t -> 'a t -> 'a t`

`interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on.

When one of the sequences `xs` and `ys` is exhausted, `interleave xs ys` continues with the rest of the other sequence.

**Since:** 4.14

`val sorted_merge : ('a -> 'a -> int) -> 'a t -> 'a t -> 'a t`

If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`.

For more details on comparison functions, see `Array.sort` [29.2].

**Since:** 4.14

`val product : 'a t -> 'b t -> ('a * 'b) t`

`product xs ys` is the Cartesian product of the sequences `xs` and `ys`.

For every element `x` of `xs` and for every element `y` of `ys`, the pair `(x, y)` appears once as an element of `product xs ys`.

The order in which the pairs appear is unspecified.

The sequences `xs` and `ys` are not required to be finite.

The sequences `xs` and `ys` must be persistent.

**Since:** 4.14

`val map_product : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t`

The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`.

For every element `x` of `xs` and for every element `y` of `ys`, the element `f x y` appears once as an element of `map_product f xs ys`.

The order in which these elements appear is unspecified.

The sequences `xs` and `ys` are not required to be finite.

The sequences `xs` and `ys` must be persistent.

`map_product f xs ys` is equivalent to `map (fun (x, y) -> f x y) (product xs ys)`.

**Since:** 4.14
Class language

Type expressions for the class language

```c
type class_type =
{
    pcty_desc : class_type_desc;
    pcty_loc : Location.t;
    pcty_attributes : attributes;
    ...
    [@id1] [@id2]
}

type class_type_desc =
| Pcty_constr of Longident.t Asttypes.loc * core_type list
    - c
    • ['a1, ..., 'an] c
| Pcty signature of class signature
    object ... end
| Pcty arrow of Asttypes.arg_label * core_type * class_type
    Pctyarrow.lbl, T, CT) represents:
    • T -> CT when lbl is Nolabel[??],
    • ~1:T -> CT when lbl is Labelled l[??],
    • ?1:T -> CT when lbl is Optional l[??].
| Pcty extension of extension
    %id
| Pcty open of open_description * class_type
    let open M in CT
type class signature =
{
    pcsig self : core_type;
    pcsig_fields : class_type_field list;
}

Values of type class signature represents:
• object('selfpat) ... end
• object ... end when pcsig self[??] is Ptyp_any[??]
type class_type_field =
{
    pctf_desc : class_type_field_desc;
    pctf_loc : Location.t;
    pctf_attributes : attributes;
```
Splitting a sequence into two sequences

val unzip : ('a * 'b) t -> 'a t * 'b t

unzip transforms a sequence of pairs into a pair of sequences.

unzip xs is equivalent to (map fst xs, map snd xs).

Querying either of the sequences returned by unzip xs causes xs to be queried. Therefore,
querying both of them causes xs to be queried twice. Thus, xs must be persistent and cheap.
If that is not the case, use unzip (memoize xs).

Since: 4.14

val split : ('a * 'b) t -> 'a t * 'b t

split is an alias for unzip.

Since: 4.14

val partition_map : ('a -> ('b, 'c) Either.t) -> 'a t -> 'b t * 'c t

partition_map f xs returns a pair of sequences (ys, zs), where:

* ys is the sequence of the elements y such that f x = Left y, where x ranges over xs;

* zs is the sequence of the elements z such that f x = Right z, where x ranges over xs.

partition_map f xs is equivalent to a pair of filter_map Either.find_left (map f xs) and filter_map Either.find_right (map f xs).

Querying either of the sequences returned by partition_map f xs causes xs to be queried.
Therefore, querying both of them causes xs to be queried twice. Thus, xs must be persistent
and cheap. If that is not the case, use partition_map f (memoize xs).

Since: 4.14

val partition : ('a -> bool) -> 'a t -> 'a t * 'a t

partition p xs returns a pair of the subsequence of the elements of xs that satisfy p and
the subsequence of the elements of xs that do not satisfy p.

partition p xs is equivalent to filter p xs, filter (fun x -> not (p x)) xs.

Consuming both of the sequences returned by partition p xs causes xs to be consumed
twice and causes the function f to be applied twice to each element of the list. Therefore, f
should be pure and cheap. Furthermore, xs should be persistent and cheap. If that is not the
case, use partition p (memoize xs).

Since: 4.14
```c
... [@@id1] [@@id2]
}
type class_type_field_desc =
| Pctf_inherit of class_type
    inherit CT
| Pctf_val of (Asttypes.label Asttypes.loc * Asttypes.mutable_flag *
    Asttypes.virtual_flag * core_type)
    val x: T
| Pctf_method of (Asttypes.label Asttypes.loc * Asttypes.private_flag *
    Asttypes.virtual_flag * core_type)
    method x: T
    Note: T can be a Ptyp_polym[??].
| Pctf_constraint of (core_type * core_type)
    constraint T1 = T2
| Pctf_attribute of attribute
    [@@@id]
| Pctf_extension of extension
    [%%id]
type 'a class =
{   pci_virt : Asttypes.virtual_flag ;
   pci_params : (core_type * (Asttypes.variance * Asttypes injectivity)) list ;
   pci_name : string Asttypes.loc ;
   pci_expr : 'a ;
   pci_loc : Location.t ;
   pci_attributes : attributes ;
    ... [@@id1] [@@id2]
}
```

Values of type `class_expr` `class infos` represents:

* class c = ...

* class ['a1, ..., 'an] c = ...

* class virtual c = ...

They are also used for "class type" declaration.

```c
type class_description = class_type class_info;
```

```c
type class_type_declaration = class_type class_info;
```
## Converting between sequences and dispensers

A dispenser is a representation of a sequence as a function of type `unit -> 'a option`. Every time this function is invoked, it returns the next element of the sequence. When there are no more elements, it returns `None`. A dispenser has mutable internal state, therefore is ephemeral: the sequence that it represents can be consumed at most once.

val of_dis dispenser : (unit -> 'a option) -> 'a t

`of_dis dispenser it` is the sequence of the elements produced by the dispenser `it`. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use `memoize (of_dis dispenser it)`.

**Since:** 4.14

val to_dis dispenser : 'a t -> unit -> 'a option

`to_dis dispenser xs` is a fresh dispenser on the sequence `xs`.

This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently.

**Since:** 4.14

## Sequences of integers

val ints : int -> int t

`ints i` is the infinite sequence of the integers beginning at `i` and counting up.

**Since:** 4.14

## 29.54 Module Set : Sets over ordered types.

This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance.

The `Set.Make[29.54]` functor constructs implementations for any type, given a `compare` function. For instance:

module IntPairs =
  struct
    type t = int * int
    let compare (x0,y0) (x1,y1) =
      match Stdlib compares x0 x1 with
        0 -> Stdlib compare y0 y1
      | c -> c
  end
Value expressions for the class language

```c
type class_expr =
{
    pcl_desc : class_expr_desc;
    pcl_loc : Location.t;
    pcl_attributes : attributes;
    ... [@id1] [@id2]
}

type class_expr_desc =
| Pcl_constr of Longident.t Asttypes.loc * core_type list
c and ['a1, ..., 'an] c
| Pcl_structure of class_structure
object ... end
| PclFun of Asttypes.arg_label * expression option * pattern
* class_expr
    PclFun.lbl, exp0, P, CE) represents:
        fun P -> CE when label is Nolabel[??] and exp0 is None,
        fun l1:P -> CE when label is Labelled l[??] and exp0 is None,
        fun ?l:P -> CE when label is Optional l[??] and exp0 is None,
        fun ?l:(P = E0) -> CE when label is Optional l[??] and exp0 is Some E0.
| Pcl_apply of class_expr * (Asttypes.arg_label * expression) list
    Pcl_apply(CE, [(l1,E1); ... ; (ln,En)]) represents CE ~l1:E1 ... ~ln:En.
    li can be empty (non labeled argument) or start with ? (optional argument).
    Invariant: n > 0
| Pcl_let of Asttypes.rec_flag * value_bind list * class_expr
    Pcl_let(rec, [(P1, E1); ... ; (Pn, En)], CE) represents:
        let P1 = E1 and ... and Pn = EN in CE when rec is Nonrecursive[??],
        let rec P1 = E1 and ... and Pn = EN in CE when rec is Recursive[??].
| Pcl_constraint of class_expr * class_type
    (CE : CT)
| Pcl_extension of extension
    [%id]
| Pcl_open of open_description * class_expr
    let open M in CE
```
```python
module PairsSet = Set.Make(IntPairs)

let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13))
```

This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`.

```python
module type OrderedType =
    sig
        type t
        The type of the set elements.

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

A total ordering function over the set 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`. Example: a suitable ordering function is the generic structural comparison function `compare` [28.2].

```python
end

Input signature of the functor Set.Make[29.54].

module type S =
    sig
```

## Sets

```python
type elt
    The type of the set elements.

type t
    The type of sets.

val empty : t
    The empty set.

val add : elt -> t -> t
```

`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).

**Before 4.03** Physical equality was not ensured.

```python
val singleton : elt -> t
    singleton `x` returns the one-element set containing only `x`.
```
```c
type class_structure =
{
    pcstr self : pattern ;
    pcstr_fields : class_field list ;
}
```

Values of type `Parsetree.class_structure[29.6]` represents:

* `object(selfpat) ... end`

* `object ... end` when `pcstr self[??]` is `Ppat_any[??]`

```c
type class_field =
{
    pcf_desc : class_field_desc ;
    pcf_loc : Location.t ;
    pcf_attributes : attributes ;
    ...
    [@@id1] [@@id2]
}
```

```c
}
```

```c
type class_field_desc =
| Pcf_inherit of Asttypes gasp desc * class_expr * string Asttypes.loc option
    Pcf_inherit flag, CE, s) represents:
```

* `inherit CE` when `flag` is `Fresh[??]` and `s` is `None`,

* `inherit CE` as `x` when `flag` is `Fresh[??]` and `s` is `Some x`,

* `inherit! CE` when `flag` is `Override[??]` and `s` is `None`,

* `inherit! CE` as `x` when `flag` is `Override[??]` and `s` is `Some x`

```c
| Pcf_val of (Asttypes.label Asttypes.loc * Asttypes.multiple_flag * class_fieldKind)
    Pcf_val(x, flag, kind) represents:
```

* `val x = E` when `flag` is `Immutable[??]` and `kind` is `Cfk_concrete(Fresh, E)[??]`

* `val virtual x: T` when `flag` is `Immutable[??]` and `kind` is `Cfk_virtual(T)[??]`

* `val mutable x = E` when `flag` is `Mutable[??]` and `kind` is `Cfk_concrete(Fresh, E)[??]`

* `val mutable virtual x: T` when `flag` is `Mutable[??]` and `kind` is `Cfk_virtual(T)[??]`

```c
| Pcf_method of (Asttypes.label Asttypes.loc * Asttypes.private_flag * class_fieldKind)
    - method x = E (E can be a Pexp_polymode)
```

* `method virtual x: T` (T can be a `Ptyp_polymode`)
val remove : elt -> t -> t

remove x s returns a set containing all elements of s, except x. If x was not in s, s is
returned unchanged (the result of the function is then physically equal to s).

Before 4.03 Physical equality was not ensured.

val union : t -> t -> t

Set union.

val inter : t -> t -> t

Set intersection.

val disjoint : t -> t -> bool

Test if two sets are disjoint.

Since: 4.08

val diff : t -> t -> t

Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`.

val cardinal : t -> int

Return the number of elements of a set.

Elements

val elements : t -> elt list

Return the list of all elements of the given set. The returned list is sorted in increasing
order with respect to the ordering `Ord comparisons`, where `Ord` is the argument given to
`Set.Make[29.54]`.

val min_elt : t -> elt

Return the smallest element of the given set (with respect to the `Ord comparisons` ordering),
or raise `Not_found` if the set is empty.

val min_elt_opt : t -> elt option

Return the smallest element of the given set (with respect to the `Ord comparisons` ordering),
or `None` if the set is empty.

Since: 4.05

val max_elt : t -> elt

Same as `Set.S.min_elt[29.54]`, but returns the largest element of the given set.
```
| Pcf_constraint of (core_type * core_type)
    constraint T1 = T2

| Pcf_initialize of expression
    initializer E

| Pcf_attribute of attribute
    [@@@id]

| Pcf_extension of extension
    [%id]

type class_fieldKind =
  | Cfk_virtual of core_type
  | Cfk_concrete of Asttypes gasp * expression
type class_declaration = class_expr class infos
```

## Module language

### Type expressions for the module language

```
type module_type =
{
  pmty_desc : module_type_desc ;
  pmty_loc : Location.t ;
  pmty_attributes : attributes ;
  ...
  [@id1] [@id2]
}
type module_type_desc =
  | Pmty_ident of Longident.t Asttypes.loc
  | Pmty_ident(S) represents S
  | Pmty signature of signature
  | sig ... end
  | Pmty functor of functor parameter * module_type
  | functor(X : MT1) -> MT2
  | Pmty_with of module_type * with_constraint list
  | MT with ...
  | Pmty_typeof of module_expr
  | module type of ME
  | Pmty_extension of extension
  | [%id]
  | Pmty_alias of Longident.t Asttypes.loc
  | (module M)
```
**val max_elt_opt : t -> elt option**

Same as `Set.S.min_elt_opt` [29.54], but returns the largest element of the given set.

**Since:** 4.05

**val choose : t -> elt**

Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.

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

Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets.

**Since:** 4.05

## Searching

**val find : elt -> t -> elt**

`find` `x s` returns the element of `s` equal to `x` (according to `Ord comparisons`), or raise `Not_found` if no such element exists.

**Since:** 4.01

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

`find_opt` `x s` returns the element of `s` equal to `x` (according to `Ord comparisons`), or `None` if no such element exists.

**Since:** 4.05

**val find_first : (elt -> bool) -> t -> elt**

`find_first` `f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists.

For example, `find_first(f fun e -> Ord comparisons e x >= 0) s` will return the first element `e` of `s` where `Ord comparisons e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`.

**Since:** 4.05

**val find_first_opt : (elt -> bool) -> t -> elt option**

`find_first_opt` `f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists.

**Since:** 4.05

**val find_last : (elt -> bool) -> t -> elt**
type functor_parameter =
| Unit
()  
| Named of string option Asttypes.loc * module_type
  Named(name, MT) represents:

• (X : MT) when name is Some X,

• (_ : MT) when name is None

type signature = signature_item list

type signature_item =
{ psig_desc : signature_item_desc ;
  psig_loc : Location.t ;
}

type signature_item_desc =
| Psig_value of value_description
- val x: T

• external x: T = "s1" ... "sn"

| Psig_type of Asttypes.rec_flag * type_declaration list
  type t1 = ... and ... and tn = ...

| Psig_typesubst of type_declaration list
  type t1 := ... and ... and tn := ...

| Psig_typesubst of type_extension
  type t1 += ...

| Psig_exception of type_exception
  exception C of T

| Psig_module of module_declaration
  module X = M and module X : MT

| Psig_modsubst of module_substitution
  module X := M

| Psig_recmodule of module_declaration list
  module rec X1 : MT1 and ... and Xn : MTn

| Psig_modtype of module_type_declaration
  module type S = MT and module type S

| Psig_modtypesubst of module_type_declaration
  module type S := ...

| Psig_open of open_description
`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists.

**Since: 4.05**

`val find_last_opt : (elt -> bool) -> t -> elt option`

`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists.

**Since: 4.05**

## Traversing

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

`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements.

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

`fold f s init` computes (`f xN ... (f x2 (f x1 init)) ...`), where `x1 ... xN` are the elements of `s`, in increasing order.

## Transforming

`val map : (elt -> elt) -> t -> t`

`map f s` is the set whose elements are `f a0, f a1... f aN`, where `a0, a1... aN` are the elements of `s`.

The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements.

If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.)

**Since: 4.04**

`val filter : (elt -> bool) -> t -> t`

`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`).

**Before 4.03** Physical equality was not ensured.

`val filter_map : (elt -> elt option) -> t -> t`
```
open X
| Psig_include of include_description
    include MT
| Psig_class of class_description list
class c1 : ... and ... and cn : ...
| Psig_class_type of class_type declaration list
class type ct1 = ... and ... and ctn = ...
| Psig_attribute of attribute
    [@@@id]
| Psig_extension of extension * attributes
    [%%id]
type module declaration =
{ pmd_name : string option Asttypes.loc ;
pmd_type : module_type ;
pmd_attributes : attributes ;
    ... [@@id1] [@@id2]
pmd_loc : Location.t ;
}
Values of type module declaration represents S : MT
type module_substitution =
{ pms_name : string Asttypes.loc ;
pms manifest : Longident.t Asttypes.loc ;
pms_attributes : attributes ;
    ... [@@id1] [@@id2]
pms_loc : Location.t ;
}
Values of type module_substitution represents S : = M
type module_type declaration =
{ pmtd_name : string Asttypes.loc ;
pmtd_type : module_type option ;
pmtd_attributes : attributes ;
    ... [@@id1] [@@id2]
pmtd_loc : Location.t ;
}
Values of type module_type_statement represents:
```

* S = MT,
`filter_map` f s returns the set of all v such that f x = Some v for some element x of s.

For example,

`filter_map` (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s
is the set of halves of the even elements of s.

If no element of s is changed or dropped by f (if f x = Some x for each element x),
then s is returned unchanged: the result of the function is then physically equal to s.

Since: 4.11

val partition : (elt -> bool) -> t -> t * t

partition f s returns a pair of sets (s1, s2), where s1 is the set of all the elements of s that satisfy the predicate f, and s2 is the set of all the elements of s that do not satisfy f.

val split : elt -> t -> t * bool * t

split x s returns a triple (l, present, r), where l is the set of elements of s that
are strictly less than x; r is the set of elements of s that are strictly greater than x;
present is false if s contains no element equal to x, or true if s contains an element
equal to x.

Predicates and comparisons

val is_empty : t -> bool

Test whether a set is empty or not.

val mem : elt -> t -> bool

mem x s tests whether x belongs to the set s.

val equal : t -> t -> bool

equal s1 s2 tests whether the sets s1 and s2 are equal, that is, contain equal elements.

val compare : t -> t -> int

Total ordering between sets. Can be used as the ordering function for doing sets of sets.

val subset : t -> t -> bool

subset s1 s2 tests whether the set s1 is a subset of the set s2.

val for_all : (elt -> bool) -> t -> bool

for_all f s checks if all elements of the set satisfy the predicate f.

val exists : (elt -> bool) -> t -> bool

exists f s checks if at least one element of the set satisfies the predicate f.
* S for abstract module type declaration, when `pmtd_type[??]` is `None`.

```python
type 'a open =
{
    popen_expr : 'a ;
    popen_override : Asttypes Override_flag ;
    popen_loc : Location.t ;
    popen_attributes : attributes ;
}
```

Values of type `'a open_info`s represents:

* `open! X` when `popen_override[??]` is `Override[??]` (silences the "used identifier shadowing" warning)

* `open X` when `popen_override[??]` is `Fresh[??]`

`type open_description = Longident.t Asttypes.loc open_info`

Values of type `open_description` represents:

* `open M.N`

* `open M(N).O`

`type open_statement = module_expr open_info`

Values of type `open_statement` represents:

* `open M.N`

* `open M(N).O`

* `open struct ... end`

```python
type 'a include_info =
{
    pincl_mod : 'a ;
    pincl_loc : Location.t ;
    pincl_attributes : attributes ;
}
```

`type include_description = module_type include_info`
Values of type `include_description` represents `include MT`

`type include_statement = module_expr include_info`
Values of type `include_statement` represents `include ME`

```python
type with_constraint =
| Pwith_type of Longident.t Asttypes.loc * type_statement
    with type X.t = ...
```

Note: the last component of the longident must match the name of the `type_statement`.
Converting

val to_list : t -> elt list

to_list s is Set.S[29.54] s.

Since: 5.1

val of_list : elt list -> t

of_list l creates a set from a list of elements. This is usually more efficient than
folding add over the list, except perhaps for lists with many duplicated elements.

Since: 4.02

val to_seq_from : elt -> t -> elt Seq.t

to_seq_from x s iterates on a subset of the elements of s in ascending order, from x or above.

Since: 4.07

val to_seq : t -> elt Seq.t

Iterate on the whole set, in ascending order

Since: 4.07

val to_rev_seq : t -> elt Seq.t

Iterate on the whole set, in descending order

Since: 4.12

val add_seq : elt Seq.t -> t -> t

Add the given elements to the set, in order.

Since: 4.07

val of_seq : elt Seq.t -> t

Build a set from the given bindings

Since: 4.07

end

Output signature of the functor Set.Make[29.54].

module Make :

functor (Ord : OrderedType) -> S with type elt = Ord.t

Functor building an implementation of the set structure given a totally ordered type.
| Pwith_module of Longident.t Asttypes.loc * Longident.t Asttypes.loc
  with module X.Y = Z

| Pwith_modtype of Longident.t Asttypes.loc * module_type
  with module type X.Y = Z

| Pwith_modtypesubst of Longident.t Asttypes.loc * module_type
  with module type X.Y := sig end

| Pwith_typesubst of Longident.t Asttypes.loc * typeDeclaration
  with type X.t := ..., same format as [Pwith_type]

| Pwith_modsubst of Longident.t Asttypes.loc * Longident.t Asttypes.loc
  with module X.Y := Z

Value expressions for the module language

type module_expr =
{ pmod_desc : module_expr_desc ;
pmod_loc : Location.t ;
pmod_attributes : attributes ;
... [@id1] [@id2]

}

type module_expr_desc =
| Pmod_ident of Longident.t Asttypes.loc
  X
| Pmod_structure of structure
  struct ... end
| Pmod functor of functor_parameter * module_expr
  functor(X : MT1) -> ME
| Pmod_apply of module_expr * module_expr
  ME1(ME2)
| Pmod_apply_unit of module_expr
  ME1()
| Pmod_constraint of module_expr * module_type
  (ME : MT)
| Pmod_unpack of expression
  (val E)
| Pmod_extension of extension
  [%id]
## 29.55 Module Semaphore : Semaphores

A semaphore is a thread synchronization device that can be used to control access to a shared resource.

Two flavors of semaphores are provided: counting semaphores and binary semaphores.

**Since:** 4.12

### Counting semaphores

A counting semaphore is a counter that can be accessed concurrently by several threads. The typical use is to synchronize producers and consumers of a resource by counting how many units of the resource are available.

The two basic operations on semaphores are:

* "release" (also called "V", "post", "up", and "signal"), which increments the value of the counter. This corresponds to producing one more unit of the shared resource and making it available to others.

* "acquire" (also called "P", "wait", "down", and "pend"), which waits until the counter is greater than zero and decrements it. This corresponds to consuming one unit of the shared resource.

**module Counting :**

```
sig
```

```
type t
```

The type of counting semaphores.

```
val make : int -> t
```

`make n` returns a new counting semaphore, with initial value `n`. The initial value `n` must be nonnegative.

**Raises** `Invalid_argument` if `n < 0`

```
val release : t -> unit
```

`release s` increments the value of semaphore `s`. If other threads are waiting on `s`, one of them is restarted. If the current value of `s` is equal to `max_int`, the value of the semaphore is unchanged and a `Sys_error` exception is raised to signal overflow.

**Raises** `Sys_error` if the value of the semaphore would overflow

```
val acquire : t -> unit
```

`acquire s` blocks the calling thread until the value of semaphore `s` is not zero, then atomically decrements the value of `s` and returns.

```
val try_acquire : t -> bool
```
type structure = structure_item list
type structure_item =
  { pstr_desc : structure_item_desc ;
    pstr_loc : Location.t ;
  }

type structure_item_desc =
  | Pstr_eval of expression * attributes
    E

| Pstr_value of Asttypes.rec_flag * value_bindist list
  Pstr_value(rec, [(P1, E1 ; ... ; (Pn, En))]) represents:

• let P1 = E1 and ... and Pn = EN when rec is Nonrecursive[??],

• let rec P1 = E1 and ... and Pn = EN when rec is Recursive[??].

| Pstr primitive of value_description
  - val x: T

• external x: T = "s1" ... "sn"

| Pstr_type of Asttypes.rec_flag * type declaration list
  type t1 = ... and ... and tn = ...

| Pstr_typeext of type_extension
  type t1 += ...

| Pstr_exception of type_exception
  - exception C of T

• exception C = M.X

| Pstr_module of module_bindin
  module X = ME

| Pstr_recmodule of module_bindin list
  module rec X1 = ME1 and ... and Xn = MEn

| Pstr_modtype of module_type_declaration
  module type S = MT

| Pstr_open of open_declaration
  open X

| Pstr_class of class_declaration list
  class c1 = ... and ... and cn = ...

| Pstr_class_type of class_type_declaration list
class type ct1 = ... and ... and ctn = ...
`try_acquire` s immediately returns `false` if the value of semaphore `s` is zero. Otherwise, the value of `s` is atomically decremented and `try_acquire` s returns `true`.

`val get_value : t -> int`

`get_value` s returns the current value of semaphore `s`. The current value can be modified at any time by concurrent `Semaphore.Counting.release[29.55]` and `Semaphore.Counting.acquire[29.55]` operations. Hence, the `get_value` operation is racy, and its result should only be used for debugging or informational messages.

`end`

## Binary semaphores

Binary semaphores are a variant of counting semaphores where semaphores can only take two values, 0 and 1.

A binary semaphore can be used to control access to a single shared resource, with value 1 meaning "resource is available" and value 0 meaning "resource is unavailable".

The "release" operation of a binary semaphore sets its value to 1, and "acquire" waits until the value is 1 and sets it to 0.

A binary semaphore can be used instead of a mutex (see module Mutex[29.38]) when the mutex discipline (of unlocking the mutex from the thread that locked it) is too restrictive. The "acquire" operation corresponds to locking the mutex, and the "release" operation to unlocking it, but "release" can be performed in a thread different than the one that performed the "acquire". Likewise, it is safe to release a binary semaphore that is already available.

module Binary :

`sig`

`type t`

The type of binary semaphores.

`val make : bool -> t`

`make b` returns a new binary semaphore. If `b` is `true`, the initial value of the semaphore is 1, meaning "available". If `b` is `false`, the initial value of the semaphore is 0, meaning "unavailable".

`val release : t -> unit`

`release` s sets the value of semaphore `s` to 1, putting it in the "available" state. If other threads are waiting on `s`, one of them is restarted.

`val acquire : t -> unit`

`acquire` s blocks the calling thread until the semaphore `s` has value 1 (is available), then atomically sets it to 0 and returns.

`val try_acquire : t -> bool`
```c
| Pstr_include of include declaration
    include ME

| Pstr_attribute of attribute
    [@@@id]

| Pstr_extension of extension * attributes
    [%%id]

type value_constraint =
  | Pvc_constraint of { locally abstract_univars : string Asttypes.loc list ;
  | typ : core_type ;
  }
  | Pvc_coercion of { ground : core_type option ;
  | coercion : core_type ;
  }
```

- `Pvc_constraint { locally_abstract_univars = [] ; typ }` is a simple type constraint on a value binding: `let x : typ`

* More generally, in `Pvc_constraint { locally_abstract_univars ; typ } locally_abstract_univars` is the list of locally abstract type variables in `let x : type a ... . typ`

* `Pvc_coercion { ground=None; coercion }` represents `let x :> typ`

* `Pvc_coercion { ground=Some g; coercion }` represents `let x : g :> typ`

```c
type value_bind =
{
    pvb_pat : pattern ;
    pvb_expr : expression ;
    pvb_constraint : value_constraint option ;
    pvb_attributes : attributes ;
    pvb_loc : Location.t ;
}
```

`let pat : type_constraint = exp`

```c
type module_bind =
{
    pmb_name : string option Asttypes.loc ;
    pmb_expr : module_expr ;
    pmb_attributes : attributes ;
    pmb_loc : Location.t ;
}
```

Values of type `module_bind` represents `module X = ME`
`try_acquire` s immediately returns `false` if the semaphore `s` has value 0. If `s` has value 1, its value is atomically set to 0 and `try_acquire` s returns `true`.

end

## 29.56 Module Stack : Last-in first-out stacks.

This module implements stacks (LIFOs), with in-place modification.

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

### Unsynchronized accesses

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

type !'a t

The type of stacks containing elements of type `'a`.

**exception Empty**

Raised when `Stack.pop[29.56]` or `Stack.top[29.56]` is applied to an empty stack.

val create : unit -> 'a t

Return a new stack, initially empty.

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

`push` `x` `s` adds the element `x` at the top of stack `s`.

val pop : 'a t -> 'a

`pop` `s` removes and returns the topmost element in stack `s`, or raises `Stack.Empty[29.56]` if the stack is empty.

val pop_opt : 'a t -> 'a option

`pop_opt` `s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty.

**Since: 4.08**

val drop : 'a t -> unit

`drop` `s` removes the topmost element in stack `s`, or raises `Stack.Empty[29.56]` if the stack is empty.

**Since: 5.1**

val top : 'a t -> 'a

`top` `s` returns the topmost element in stack `s`, or raises `Stack.Empty[29.56]` if the stack is empty.
## TLEVEL

## Tplevel phrases

```c
type toplevel_phrase =
  | Ptop_def of structure
  | Ptop_dir of toplevel_directive
  #use, #load ...
```

```c
type toplevel_directive =
{
    pdir_name : string Asttypes.loc ;
    pdir_arg : directive_argument option ;
    pdir_loc : Location.t ;
}
```

```c
type directive_argument =
{
    pdira_desc : directive_argument_desc ;
    pdira_loc : Location.t ;
}
```

```c
type directive_argument_desc =
  | Pdir_string of string
  | Pdir_int of string * char option
  | Pdir_ident of Longident.t
  | Pdir_bool of bool
```

## 29.7 Module Pprintast : Pretty-printers for Parsetree [29.6]

**Warning:** this module is unstable and part of compiler-libs [29].

```python
type space_formatter = (unit, Format.formatter, unit) format
val longident : Format.formatter -> Longident.t -> unit
val expression : Format.formatter -> Parsetree.expression -> unit
val string_of_expression : Parsetree.expression -> string
val pattern : Format.formatter -> Parsetree.pattern -> unit
val core_type : Format.formatter -> Parsetree.core_type -> unit
val signature : Format.formatter -> Parsetree signature -> unit
val structure : Format.formatter -> Parsetree structure -> unit
val string_of_structure : Parsetree structure -> string
val module_expr : Format.formatter -> Parsetree.module_expr -> unit
val toplevel_phrase : Format.formatter -> Parsetree.tosevel_phrase -> unit
val top_phrase : Format.formatter -> Parsetree.tosevel_phrase -> unit
val class_field : Format.formatter -> Parsetree.class_field -> unit
val class_type_field : Format.formatter -> Parsetree.class_type_field -> unit
```
val top_opt : 'a t -> 'a option

top_opt s returns the topmost element in stack s, or None if the stack is empty.

Since: 4.08

val clear : 'a t -> unit

Discard all elements from a stack.

val copy : 'a t -> 'a t

Return a copy of the given stack.

val is_empty : 'a t -> bool

Return true if the given stack is empty, false otherwise.

val length : 'a t -> int

Return the number of elements in a stack. Time complexity O(1)

val iter : ('a -> unit) -> 'a t -> unit

iter f s applies f in turn to all elements of s, from the element at the top of the stack to
the element at the bottom of the stack. The stack itself is unchanged.

val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc

fold f accu s is (f (... (f (f accu x1) x2) ...) xn) where x1 is the top of the stack, x2 the second element, and xn the bottom element. The stack is unchanged.

Since: 4.03

Stacks and Sequences

val to_seq : 'a t -> 'a Seq.t

Iterate on the stack, top to bottom. It is safe to modify the stack during iteration.

Since: 4.07

val add_seq : 'a t -> 'a Seq.t -> unit

Add the elements from the sequence on the top of the stack.

Since: 4.07

val of_seq : 'a Seq.t -> 'a t

Create a stack from the sequence.

Since: 4.07
val class_expr : Format formatter -> Parsetree.class_expr -> unit
val class_type : Format formatter -> Parsetree.class_type -> unit
val module_type : Format formatter -> Parsetree.module_type -> unit
val structure_item : Format formatter -> Parsetree structure_item -> unit
val signature_item : Format formatter -> Parsetree signature_item -> unit
val binding : Format formatter -> Parsetree.value_bindin g -> unit
val payload : Format formatter -> Parsetree_payload -> unit
val tyvar : Format formatter -> string -> unit

Print a type variable name, taking care of the special treatment required for the single quote
character in second position.
## 29.57 Module StdLabels : Standard labeled libraries.

This meta-module provides versions of the StdLabels Array[29.57], StdLabels. Bytes[29.57], StdLabels. List[29.57] and StdLabels. String[29.57] modules where function arguments are systematically labeled. It is intended to be opened at the top of source files, as shown below.

```hkl
open StdLabels

let to_upper = String.map ~f:Char.uppercaseocos
let seq len = List.init ~f:(fun i -> i) ~len
let everything = Array.create_matrix ~dimx:42 ~dimy:42 42
```

module Array :
  ArrayLabels

module Bytes :
  BytesLabels

module List :
  ListLabels

module String :
  StringLabels

## 29.58 Module String : 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.

```
positions      0  1  2  3  4  n-1  n
              +---+---+---+---+
indices       | 0 | 1 | 2 | 3 | ... | n-1 |
              +---+---+---+---+
```

* 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[29.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`[29.57] 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[29.60]`.

### 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[29.60]`.

### 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[29.8]` which should be preferred.
# Chapter 30

## The unix library: Unix system calls

The `unix` library makes many Unix system calls and system-related library functions available to OCaml programs. This chapter describes briefly the functions provided. Refer to sections 2 and 3 of the Unix manual for more details on the behavior of these functions.

Not all functions are provided by all Unix variants. If some functions are not available, they will raise `Invalid_arg` when called.

Programs that use the `unix` library must be linked as follows:

`ocamlc other options -I +unix unix.cma other files`

`ocamlopt other options -I +unix unix.cmxa other files`

For interactive use of the `unix` library, do:

`ocamlmktop -o mytop -I +unix unix.cma`

`./mytop`

or (if dynamic linking of C libraries is supported on your platform), start `ocaml` and type

`# #directory "+unix";;`

`# #load "unix.cma";;`

**Windows:**

A fairly complete emulation of the Unix system calls is provided in the Windows version of OCaml. The end of this chapter gives more information on the functions that are not supported under Windows.

### 30.1 Module Unix : Interface to the Unix system.

To use the labeled version of this module, add `module Unix = UnixLabels` in your implementation.

Note: all the functions of this module (except `Unix.error_message[30.1]` and `Unix.handle_unix_error[30.1]`) are liable to raise the `Unix.Unix_error[30.1]` exception whenever the underlying system call signals an error.
Concatenating

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

val concat : 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[29.60] 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[29.60] bytes.

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.03 (4.05 in StringLabels)

val compare : t -> t -> int

compare s0 s1 sorts s0 and s1 in lexicographical order. compare behaves like compare[28.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 [29.58] s 0 c.
Error report

type error =

| E2BIG

Argument list too long

| EACCES

Permission denied

| EAGAIN

Resource temporarily unavailable; try again

| EBADF

Bad file descriptor

| EBUSY

Resource unavailable

| ECHILD

No child process

| EDEADLK

Resource deadlock would occur

| EDOM

Domain error for math functions, etc.

| EEXIST

File exists

| EFAULT

Bad address

| EFBIG

File too large

| EINTR

Function interrupted by signal

| EINVAL

Invalid argument

| EIO

Hardware I/O error

| EISDIR

Is a directory

| EMFILE

Too many open files by the process
## 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`. If `s` is empty, the result is the singleton list `[]`.

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[29.58]` 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
| EMLINK

Too many links

| ENAMETOOLONG

Filename too long

| ENFILE

Too many open files in the system

| ENODEV

No such device

| ENOENT

No such file or directory

| ENOEXEC

Not an executable file

| ENOLCK

No locks available

| ENOMEM

Not enough memory

| ENOSPC

No space left on device

| ENOSYS

Function not supported

| ENOTDIR

Not a directory

| ENOTEMPTY

Directory not empty

| ENOTTY

Inappropriate I/O control operation

| ENXIO

No such device or address

| EPERM

Operation not permitted

| EPIPE

Broken pipe

| ERANGE

Result too large
val exists : (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

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[29.52]` 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[29.60] bytes.

val uppercase波: string -> string

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

Since: 4.03 (4.05 in StringLabels)

val lowercase波: string -> string

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

Since: 4.03 (4.05 in StringLabels)

val capitalize波: string -> string

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

Since: 4.03 (4.05 in StringLabels)

val un capital ize波: string -> string

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

Since: 4.03 (4.05 in StringLabels)
| EROFS

Read-only file system

| ESPIPE

Invalid seek e.g. on a pipe

| ESRCH

No such process

| EXDEV

Invalid link

| EWOULDBLOCK

Operation would block

| EINPROGRESS

Operation now in progress

| EALREADY

Operation already in progress

| ENOTSOCK

Socket operation on non-socket

| EDESTADDRREQ

Destination address required

| EMSGSIZE

Message too long

| EPROTOTYPE

Protocol wrong type for socket

| ENOPROTOOPT

Protocol not available

| EPROTONOSUPPORT

Protocol not supported

| ESOCKTNOSUPPORT

Socket type not supported

| EOPNOTSUPP

Operation not supported on socket

| EPFNOSUPPORT

Protocol family not supported

| EAFNOSUPPORT

Address family not supported by protocol family
## 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[29.58], 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[29.58] s 0 c.

val index_opt : string -> char -> int option
| EADDRINUSE

Address already in use

| EADDRNOTAVAIL

Can't assign requested address

| ENETDOWN

Network is down

| ENETUNREACH

Network is unreachable

| ENETRESET

Network dropped connection on reset

| ECONNABORTED

Software caused connection abort

| ECONNRESET

Connection reset by peer

| ENOBUFS

No buffer space available

| EISCONN

Socket is already connected

| ENOTCONN

Socket is not connected

| ESHUTDOWN

Can't send after socket shutdown

| ETOOMANYREFS

Too many references: can't splice

| ETIMEDOUT

Connection timed out

| ECONNREFUSED

Connection refused

| EHOSTDOWN

Host is down

| EHOSTUNREACH

No route to host

| ELOOP

Too many levels of symbolic links
index_opt s c is String.index_from_opt[29.58] s 0 c.

Since: 4.05

val rindex : string -> char -> int

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

val rindex_opt : string -> char -> int option

rindex_opt s c is String.rindex_from_opt[29.58] 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.

Since: 4.07

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

to_seqi s is like String.to_seq[29.58] 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.
### EVERFLOW

File size or position not representable

### EUNKNOWNERR of int

Unknown error

The type of error codes. Errors defined in the POSIX standard and additional errors from UNIX98 and BSD. All other errors are mapped to EUNKNOWNERR.

### exception Unix_error of error * string * string

Raised by the system calls below when an error is encountered. The first component is the error code; the second component is the function name; the third component is the string parameter to the function, if it has one, or the empty string otherwise.

`UnixLabels.Unix_error[??]` and `Unix.Unix_error[30.1]` are the same, and catching one will catch the other.

### val error_message : error -> string

Return a string describing the given error code.

### val handle_unix_error : ('a -> 'b) -> 'a -> 'b

`handle_unix_error` `f` `x` applies `f` to `x` and returns the result. If the exception `Unix.Unix_error[30.1]` is raised, it prints a message describing the error and exits with code 2.

## Access to the process environment

### val environment : unit -> string array

Return the process environment, as an array of strings with the format `"variable=value"`. The returned array is empty if the process has special privileges.

### val unsafe_environment : unit -> string array

Return the process environment, as an array of strings with the format `"variable=value"`. Unlike `Unix-environment[30.1]`, this function returns a populated array even if the process has special privileges. See the documentation for `Unix.unsafe_getenv[30.1]` for more details.

**Since:** 4.06 (4.12 in UnixLabels)

### val getenv : string -> string

Return the value associated to a variable in the process environment, unless the process has special privileges.

**Raises** `Not_found` if the variable is unbound or the process has special privileges.

This function is identical to `Sys.getenv[28.55]`.

### val unsafe_getenv : string -> string
## UTF-16LE

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

```rust
val is_valid_utf_16le: t -> bool
```

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

## Spellchecking

```rust
val edit_distance: ?limit:int -> t -> t -> int
```

edit_distance s0 s1 is the number of single character edits (understood as insertion, deletion, substitution, transposition) that are needed to change s0 into s1.

If limit is provided the function returns with limit as soon as it was determined that s0 and s1 have distance of at least limit. This is faster if you have a fixed limit, for example for spellchecking.

The function assumes the strings are UTF-8 encoded and uses `Uchar.t[29.62]` for the notion of character. Decoding errors are replaced by `Uchar.rep[29.62]`. Normalizing the strings to NFC[https://unicode.org/glossary/#normalization_form_c] gives better results.

**Note.** This implements the simpler Optimal String Alignment (OSA) distance, not the Damerau-Levenshtein distance. With this function "ca" and "abc" have a distance of 3 not 2.

**Since:** 5.4

```rust
val spellcheck:
```

```hsl
?max_dist:(string -> int) ->
```

```hsl
((string -> unit) -> unit) -> string -> string list
```

spellcheck iter_dict s are the strings enumerated by the iterator iter_dict whose edit distance[29.58] to s is the smallest and at most max_dist s. If multiple corrections are returned their order is as found in iter_dict. The default max_dist s is:

* 0 if s has 0 to 2 Unicode characters.

* 1 if s has 3 to 4 Unicode characters.

* 2 otherwise.

If your dictionary is a list `l`, a suitable `iter_dict` is given by `(fun yield -> List.iter yield l)`.

All strings are assumed to be UTF-8 encoded, decoding errors are replaced by `Uchar.rep[29.62]` characters.

**Since:** 5.4
Return the value associated to a variable in the process environment.

Unlike `Unix.getenv[30.1]`, this function returns the value even if the process has special privileges. It is considered unsafe because the programmer of a setuid or setgid program must be careful to avoid using maliciously crafted environment variables in the search path for executables, the locations for temporary files or logs, and the like.

**Since: 4.06**

**Raises** `Not_found` if the variable is unbound.

`val putenv : string -> string -> unit`

`putenv name value` sets the value associated to a variable in the process environment. `name` is the name of the environment variable, and `value` its new associated value.

## Process handling

`type process_status =`

`| WEXITED of int`

The process terminated normally by `exit`; the argument is the return code.

`| WSIGNALED of int`

The process was killed by a signal; the argument is the signal number.

`| WSTOPPED of int`

The process was stopped by a signal; the argument is the signal number.

The termination status of a process. See module `Sys`[28.55] for the definitions of the standard signal numbers. Note that they are not the numbers used by the OS.

On Windows: only `WEXITED` is used (as there are no inter-process signals) but with specific return codes to indicate special termination causes. Look for `NTSTATUS` values in the Windows documentation to decode such error return codes. In particular, `STATUS_ACCESS_VIOLATION` error code is the 32-bit `0xC0000005`: as `Int32.of_int` `0xC0000005` is -1073741819, `WEXITED` -1073741819 is the Windows equivalent of `WSIGNALED Sys sigsegv`.

`type wait_flag =`

`| WNOHANG`

Do not block if no child has died yet, but immediately return with a pid equal to 0.

`| WUNTRACED`

Report also the children that receive stop signals.

**Flags** for `Unix.waitpid[30.1]`.

`val execv : string -> string array -> 'a`

`execv prog args` execute the program in file `prog`, with the arguments `args`, and the current process environment. These `execv*` functions never return: on success, the current program is replaced by the new one.
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[29.60].

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
On Windows: the CRT simply spawns a new process and exits the current one. This will have unwanted consequences if e.g. another process is waiting on the current one. Using Unix.create_process[30.1] or one of the open_process_* functions instead is recommended.

**Raises Unix_error on failure**

**val execve : string -> string array -> string array -> 'a**

Same as Unix.execv[30.1], except that the third argument provides the environment to the program executed.

**val execvp : string -> string array -> 'a**

Same as Unix.execv[30.1], except that the program is searched in the path.

**val execvpe : string -> string array -> string array -> 'a**

Same as Unix.execve[30.1], except that the program is searched in the path.

**val fork : unit -> int**

Fork a new process. The returned integer is 0 for the child process, the pid of the child process for the parent process.

**Raises Invalid_argument on Windows.** Use Unix.create_process[30.1] or threads instead.

**val wait : unit -> int * process_status**

Wait until one of the children processes die, and return its pid and termination status.

**Raises Invalid_argument on Windows.** Use Unix.waitpid[30.1] instead.

**val waitpid : wait_flag list -> int -> int * process_status**

Same as Unix.wait[30.1], but waits for the child process whose pid is given. A pid of -1 means wait for any child. A pid of 0 means wait for any child in the same process group as the current process. Negative pid arguments represent process groups. The list of options indicates whether waitpid should return immediately without waiting, and whether it should report stopped children.

On Windows: can only wait for a given PID, not any child process.

**val system : string -> process_status**

Execute the given command, wait until it terminates, and return its termination status. The string is interpreted by the shell `/bin/sh` (or the command interpreter `cmd.exe` on Windows) and therefore can contain redirections, quotes, variables, etc. To properly quote whitespace and shell special characters occurring in file names or command arguments, the use of `Filename.quote_command[28.19]` is recommended. The result `WEXITED 127` indicates that the shell couldn't be executed.

**val _exit : int -> 'a**
`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` [29.26]. This function allows this module to be passed as argument to the functor `Hashtbl.Make` [29.26].

Since: 5.0

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

A seeded hash function for strings, 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.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
Terminate the calling process immediately, returning the given status code to the operating
system: usually 0 to indicate no errors, and a small positive integer to indicate failure. Unlike
exit[27.2], Unix._exit[30.1] performs no finalization whatsoever: functions registered with
at_exit[27.2] are not called, input/output channels are not flushed, and the C run-time
system is not finalized either.

The typical use of Unix._exit[30.1] is after a Unix.fork[30.1] operation, when the child
process runs into a fatal error and must exit. In this case, it is preferable to not perform any
finalization action in the child process, as these actions could interfere with similar actions
performed by the parent process. For example, output channels should not be flushed by the
child process, as the parent process may flush them again later, resulting in duplicate output.

Since: 4.12

val getpid : unit -> int

Return the pid of the process.

val getppid : unit -> int

Return the pid of the parent process.

Raises Invalid_argument on Windows (because it is meaningless)

val nice : int -> int

Change the process priority. The integer argument is added to the "nice" value. (Higher
values of the "nice" value mean lower priorities.) Return the new nice value.

Raises Invalid_argument on Windows

Basic file input/output

type file_descr

The abstract type of file descriptors.

val stdin : file_descr

File descriptor for standard input.

val stdout : file_descr

File descriptor for standard output.

val stderr : file_descr

File descriptor for standard error.

type open_flag =

| O_RDONLY

Open for reading

| O_WRONLY
## 29.59 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><tr><td></td><td>---</td><td>---</td><td>---</td><td>---</td><td>---</td><td>---</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[29.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[29.57] 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[29.60]`.

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[29.60]`.
Open for writing

| O_RDWR

Open for reading and writing

| O_NONBLOCK

Open in non-blocking mode

| O_APPEND

Open for append

| O_CREAT

Create if nonexistent

| O_TRUNC

Truncate to 0 length if existing

| O_EXCL

Fail if existing

| O_NOCTTY

Don't make this dev a controlling tty

| O_DSYNC

Writes complete as 'Synchronised I/O data integrity completion'

| O_SYNC

Writes complete as 'Synchronised I/O file integrity completion'

| O_RSYNC

Reads complete as writes (depending on O_SYNC/O_DSYNC)

| O_SHARE_DELETE

Windows only: allow the file to be deleted while still open

| O_CLOEXEC

Set the close-on-exec flag on the descriptor returned by Unix.openfile[30.1]. See Unix.set_close_on_exec[30.1] for more information.

| O_KEEPEXEC

Clear the close-on-exec flag. This is currently the default.

The flags to Unix.openfile[30.1].

type file_perm = int

The type of file access rights, e.g. 0o640 is read and write for user, read for group, none for others

val openfile : string -> open_flag list -> file_perm -> file_descr

Open the named file with the given flags. Third argument is the permissions to give to the file if it is created (see Unix.umask[30.1]). Return a file descriptor on the named file.
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[29.8] which should be preferred.

Concatenating

Note. The (^)[28.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[29.60] 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[29.60] bytes.
val close : file_descr -> unit

Close a file descriptor.

val fsync : file_descr -> unit

Flush file buffers to disk.

Since: 4.08 (4.12 in UnixLabels)

val read : file_descr -> bytes -> int -> int -> int

read fd buf pos len reads len bytes from descriptor fd, storing them in byte sequence buf, starting at position pos in buf. Return the number of bytes actually read.

val write : file_descr -> bytes -> int -> int -> int

write fd buf pos len writes len bytes to descriptor fd, taking them from byte sequence buf, starting at position pos in buff. Return the number of bytes actually written. write repeats the writing operation until all bytes have been written or an error occurs.

val single_write : file_descr -> bytes -> int -> int -> int

Same as Unix.write[30.1], but attempts to write only once. Thus, if an error occurs, single_write guarantees that no data has been written.

val write_substring : file_descr -> string -> int -> int -> int

Same as Unix.write[30.1], but take the data from a string instead of a byte sequence.

Since: 4.02

val single_write_substring : file_descr -> string -> int -> int -> int

Same as Unix.single_write[30.1], but take the data from a string instead of a byte sequence.

Since: 4.02

## Interfacing with the standard input/output library

val in_channel_of_descr : file_descr -> in_channel

Create an input channel reading from the given descriptor. The channel is initially in binary mode; use set_binary_mode_in ic false if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.

On Windows: set_binary_mode_in[27.2] always fails on channels created with this function.

Beware that input channels are buffered, so more characters may have been read from the descriptor than those accessed using channel functions. Channels also keep a copy of the current position in the file.

Closing the channel ic returned by in_channel_of_descr fd using close_in ic also closes the underlying descriptor fd. It is incorrect to close both the channel ic and the descriptor fd.
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[28.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 [29.58] 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. If s is empty, the result is the singleton list [""].

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

* The list is not empty.
If several channels are created on the same descriptor, one of the channels must be closed, but not the others. Consider for example a descriptor `s` connected to a socket and two channels `ic = in_channel_of_descr s` and `oc = out_channel_of_descr s`. The recommended closing protocol is to perform `close_out oc`, which flushes buffered output to the socket then closes the socket. The `ic` channel must not be closed and will be collected by the GC eventually.

`val out_channel_of_descr : file_descr -> out_channel`

Create an output channel writing on the given descriptor. The channel is initially in binary mode; use `set_binary_mode_out oc false` if text mode is desired. Text mode is supported only if the descriptor refers to a file or pipe, but is not supported if it refers to a socket.

On Windows: `set_binary_mode_out[27.2]` always fails on channels created with this function.

Beware that output channels are buffered, so you may have to call `flush[27.2]` to ensure that all data has been sent to the descriptor. Channels also keep a copy of the current position in the file.

Closing the channel `oc` returned by `out_channel_of_descr fd` using `close_out oc` also closes the underlying descriptor `fd`. It is incorrect to close both the channel `ic` and the descriptor `fd`.

See Unix. `in_channel_of_descr[30.1]` for a discussion of the closing protocol when several channels are created on the same descriptor.

`val descr_of_in_channel : in_channel -> file_descr`

Return the descriptor corresponding to an input channel.

`val descr_of_out_channel : out_channel -> file_descr`

Return the descriptor corresponding to an output channel.

## Seeking and truncating

`type seek_command =`

`| SEEK_SET`
indicates positions relative to the beginning of the file

`| SEEK_CUR`
indicates positions relative to the current position

`| SEEK_END`
indicates positions relative to the end of the file

Positioning modes for Unix. `lseek[30.1]`.

`val lseek : file_descr -> int -> seek_command -> int`

Set the current position for a file descriptor, and return the resulting offset (from the beginning of the file).
* 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[29.59] 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
`val truncate : string -> int -> unit`

Truncates the named file to the given size.

`val ftruncate : file_descr -> int -> unit`

Truncates the file corresponding to the given descriptor to the given size.

## File status

`type file kind =`

`| S_REG`

Regular file

`| S_DIR`

Directory

`| S CHR`

Character device

`| S BLK`

Block device

`| S LNK`

Symbolic link

`| S FIFO`

Named pipe

`| S SOCK`

Socket

`type stats =`

`{ st_dev : int ;`

Device number

`st_ino : int ;`

Inode number

`st kind : file kind ;`

Kind of the file

`st perm : file perm ;`

Access rights

`st nlink : int ;`

Number of links

`st_uid : int ;`

User id of the owner
`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` [29.52] 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` [29.60] bytes.

**val uppercaseascii: string -> string**

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

**Since:** 4.05

**val lowercaseascii: string -> string**

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

**Since:** 4.05

**val capitalizeascii: string -> string**

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

**Since:** 4.05

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

`uncapitalizeascii` 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` [29.59], but the function is also given the corresponding character index.

**Since:** 4.00
```c
st_gid : int ;
        Group ID of the file's group

st_rdev : int ;
        Device ID (if special file)

st_size : int ;
        Size in bytes

st_atime : float ;
        Last access time

st_mtime : float ;
        Last modification time

st_ctime : float ;
        Last status change time
}

The information returned by the Unix.stat[30.1] calls.
```

* `val stat : string -> stats`
  Return the information for the named file.

* `val lstat : string -> stats`
  Same as Unix.stat[30.1], but in case the file is a symbolic link, return the information for the link itself.

* `val fstat : file_descr -> stats`
  Return the information for the file associated with the given descriptor.

* `val isatty : file_descr -> bool`
  Return true if the given file descriptor refers to a terminal or console window, false otherwise.

## File operations on large files

```python
module LargeFile :
    sig
        val lseek : Unix.file_descr -> int64 -> Unix.seek_command -> int64
        See lseek.

        val truncate : string -> int64 -> unit
        See truncate.
```
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[29.58] s 0 c.

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

Since: 4.05

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

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

Since: 4.05
val ftruncate : Unix.file_descr -> int64 -> unit
See ftruncate.

type stats =
{
  st_dev : int;
    Device number
  st_ino : int;
    Inode number
  stKind : Unix.fileKind; // This is the kind of file
  st_perm : Unix.file_perm;
    Access rights
  st_nlink : int;
    Number of links
  st_uid : int;
    User id of the owner
  st_gid : int;
    Group ID of the file's group
  st_rdev : int;
    Device ID (if special file)
  st_size : int64;
    Size in bytes
  st_atime : float;
    Last access time
  st_mtime : float;
    Last modification time
  st_ctime : float;
    Last status change time
}

}
val stat : string -> stats
val lstat : string -> stats
val fstat : Unix.file_descr -> stats
## 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.

    Since: 4.07

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

    to_seqi s is like StringLabels.to_seq[29.59] 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.
end

File operations on large files. This sub-module provides 64-bit variants of the functions Unix.LargeFile.lseek[30.1] (for positioning a file descriptor), Unix.LargeFile.truncate[30.1] and Unix.LargeFile.ftruncate[30.1] (for changing the size of a file), and Unix.LargeFile.stat[30.1], Unix.LargeFile.lstat[30.1] and Unix.LargeFile.fstat[30.1] (for obtaining information on files). These alternate functions represent positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), thus allowing operating on files whose sizes are greater than `max_int`.

## Mapping files into memory

```python
val map_file :
    file_descr ->
    ?pos:int64 ->
    ('a, 'b) Bigarray.kind ->
    'c Bigarraylayout ->
    bool -> int array -> ('a, 'b, 'c) Bigarray.Genarray.t
```

Memory mapping of a file as a Bigarray. `map_file fd kind layout shared dims` returns a Bigarray of kind `kind`, layout `layout`, and dimensions as specified in `dims`. The data contained in this Bigarray are the contents of the file referred to by the file descriptor `fd` (as opened previously with `Unix.openfile`[30.1], for example). The optional `pos` parameter is the byte offset in the file of the data being mapped; it defaults to 0 (map from the beginning of the file).

If `shared` is `true`, all modifications performed on the array are reflected in the file. This requires that `fd` be opened with write permissions. If `shared` is `false`, modifications performed on the array are done in memory only, using copy-on-write of the modified pages; the underlying file is not affected.

`Unix.map_file`[30.1] is much more efficient than reading the whole file in a Bigarray, modifying that Bigarray, and writing it afterwards.

To adjust automatically the dimensions of the Bigarray to the actual size of the file, the major dimension (that is, the first dimension for an array with C layout, and the last dimension for an array with Fortran layout) can be given as `-1`. `Unix.map_file`[30.1] then determines the major dimension from the size of the file. The file must contain an integral number of sub-arrays as determined by the non-major dimensions, otherwise `Failure` is raised.

If all dimensions of the Bigarray are given, the file size is matched against the size of the Bigarray. If the file is larger than the Bigarray, only the initial portion of the file is mapped to the Bigarray. If the file is smaller than the big array, the file is automatically grown to the size of the Bigarray. This requires write permissions on `fd`.

Array accesses are bounds-checked, but the bounds are determined by the initial call to `map_file`. Therefore, you should make sure no other process modifies the mapped file while you're accessing it, or a `SIGBUS` signal may be raised. This happens, for instance, if the file is shrunk.
## Spellchecking

```h
val edit_distance : ?limit:int -> t -> t -> int
```

`edit_distance s0 s1` is the number of single character edits (understood as insertion, deletion, substitution, transposition) that are needed to change `s0` into `s1`.

If `limit` is provided the function returns with `limit` as soon as it was determined that `s0` and `s1` have distance of at least `limit`. This is faster if you have a fixed limit, for example for spellchecking.

The function assumes the strings are UTF-8 encoded and uses `Uchar.t[29.62]` for the notion of character. Decoding errors are replaced by `Uchar.rep[29.62]`. Normalizing the strings to NFC[https://unicode.org/glossary/#normalization_form_c] gives better results.

**Note.** This implements the simpler Optimal String Alignment (OSA) distance, not the Damerau-Levenshtein distance. With this function `ca` and `abc` have a distance of 3 not 2.

**Since:** 5.4

```h
val spellcheck :
```

```h
?max_dist:(string -> int) ->
((string -> unit) -> unit) -> string -> string list
```

`spellcheck iter_dict s` are the strings enumerated by the iterator `iter_dict` whose edit distance [29.59] to `s` is the smallest and at most `max_dist s`. If multiple corrections are returned their order is as found in `iter_dict`. The default `max_dist s` is:

* 0 if `s` has 0 to 2 Unicode characters.

* 1 if `s` has 3 to 4 Unicode characters.

* 2 otherwise.

If your dictionary is a list `l`, a suitable `iter_dict` is given by `(fun yield -> List.iter yield l)`.

All strings are assumed to be UTF-8 encoded, decoding errors are replaced by `Uchar.rep[29.62]` characters.

**Since:** 5.4

## 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[29.60]`.

32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers.
`Invalid_argument` or `Failure` may be raised in cases where argument validation fails.

**Since: 4.06**

## Operations on file names

**val unlink : string -> unit**

Removes the named file.

If the named file is a directory, raises:

* `EPERM` on POSIX compliant system

* `EISDIR` on Linux ≥ 2.1.132

* `EACCESS` on Windows

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

`rename src dst` changes the name of a file from `src` to `dst`, moving it between directories if needed. If `dst` already exists, its contents will be replaced with those of `src`. Depending on the operating system, the metadata (permissions, owner, etc) of `dst` can either be preserved or be replaced by those of `src`.

**val link : ?follow:bool -> string -> string -> unit**

`link ?follow src dst` creates a hard link named `dst` to the file named `src`.

**Raises**

* `ENOSYS` On Unix if `?follow:` is requested, but `linkat` is unavailable.

* `ENOSYS` On Windows if `?follow:` is requested.

**val realpath : string -> string**

`realpath p` is an absolute pathname for `p` obtained by resolving all extra / characters, relative path segments and symbolic links.

**Since: 4.13**

## File permissions and ownership

**type accessari p**

| R_OK

Read permission

| W_OK

Write permission

| X_OK

Execution permission
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_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
### F_OK

File exists

Flags for the Unix.access[30.1] call.

### val chmod : string -> file_perm -> unit

Change the permissions of the named file.

### val fchmod : file_descr -> file_perm -> unit

Change the permissions of an opened file.

**Raises** Invalid_argument on Windows

### val chown : string -> int -> int -> unit

Change the owner uid and owner gid of the named file.

**Raises** Invalid_argument on Windows

### val fchown : file_descr -> int -> int -> unit

Change the owner uid and owner gid of an opened file.

**Raises** Invalid_argument on Windows

### val umask : file_perm -> file_perm

Set the process's file mode creation mask, and return the previous mask.

**Raises** Invalid_argument on Windows

### val access : string -> access permission list -> unit

Check that the process has the given permissions over the named file.

On Windows: execute permission X_OK cannot be tested, just tests for read permission instead.

**Raises** Unix_error otherwise.

## Operations on file descriptors

### val dup : ?cloexec:bool -> file_descr -> file_descr

Return a new file descriptor referencing the same file as the given descriptor. See Unix.set_close_on_exec[30.1] for documentation on the cloexec optional argument.

### val dup2 : ?cloexec:bool -> file_descr -> file_descr -> unit

dup2 src dst duplicates src to dst, closing dst if already opened. See Unix.set_close_on_exec[30.1] for documentation on the cloexec optional argument.

### val set_nonblock : file_descr -> unit
An unseeded hash function for strings, 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.0**

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

A seeded hash function for strings, 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.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**

## 29.60 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.
Set the “non-blocking” flag on the given descriptor. When the non-blocking flag is set, reading on a descriptor on which there is temporarily no data available raises the `EAGAIN` or `EWOULDBLOCK` error instead of blocking; writing on a descriptor on which there is temporarily no room for writing also raises `EAGAIN` or `EWOULDBLOCK`.

val clear_nonblock : file_descr -> unit

Clear the “non-blocking” flag on the given descriptor. See `Unix.set_nonblock[30.1]`.

val set_close_on_exec : file_descr -> unit

Set the “close-on-exec” flag on the given descriptor. A descriptor with the close-on-exec flag is automatically closed when the current process starts another program with one of the `exec`, `create_process` and `open_process` functions.

It is often a security hole to leak file descriptors opened on, say, a private file to an external program: the program, then, gets access to the private file and can do bad things with it. Hence, it is highly recommended to set all file descriptors “close-on-exec”, except in the very few cases where a file descriptor actually needs to be transmitted to another program.

The best way to set a file descriptor “close-on-exec” is to create it in this state. To this end, the `openfile` function has `O_CLOEXEC` and `O_KEEPEXEC` flags to enforce “close-on-exec” mode or “keep-on-exec” mode, respectively. All other operations in the Unix module that create file descriptors have an optional argument `?cloexec:bool` to indicate whether the file descriptor should be created in “close-on-exec” mode (by writing `~cloexec:true`) or in “keep-on-exec” mode (by writing `~cloexec:false`). For historical reasons, the default file descriptor creation mode is “keep-on-exec”, if no `cloexec` optional argument is given. This is not a safe default, hence it is highly recommended to pass explicit `cloexec` arguments to operations that create file descriptors.

The `cloexec` optional arguments and the `O_KEEPEXEC` flag were introduced in OCaml 4.05. Earlier, the common practice was to create file descriptors in the default, “keep-on-exec” mode, then call `set_close_on_exec` on those freshly-created file descriptors. This is not as safe as creating the file descriptor in “close-on-exec” mode because, in multithreaded programs, a window of vulnerability exists between the time when the file descriptor is created and the time `set_close_on_exec` completes. If another thread spawns another program during this window, the descriptor will leak, as it is still in the “keep-on-exec” mode.

Regarding the atomicity guarantees given by `~cloexec:true` or by the use of the `O_CLOEXEC` flag: on all platforms it is guaranteed that a concurrently-executing Caml thread cannot leak the descriptor by starting a new process. On Linux, this guarantee extends to concurrently-executing C threads. As of Feb 2017, other operating systems lack the necessary system calls and still expose a window of vulnerability during which a C thread can see the newly-created file descriptor in “keep-on-exec” mode.

val clear_close_on_exec : file_descr -> unit

Clear the “close-on-exec” flag on the given descriptor. See `Unix.set_close_on_exec[30.1]`.
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.

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
## Directories

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

Create a directory with the given permissions (see Unix.umask[30.1]).

**val rmdir : string -> unit**

Remove an empty directory.

**val chdir : string -> unit**

Change the process working directory.

**val getcwd : unit -> string**

Return the name of the current working directory.

**val chroot : string -> unit**

Change the process root directory.

**Raises Invalid_argument on Windows**

**type dir_handle**

The type of descriptors over opened directories.

**val opendir : string -> dir_handle**

Open a descriptor on a directory

**val readdir : dir_handle -> string**

Return the next entry in a directory.

**Raises End_of_file when the end of the directory has been reached.**

**val rewinddir : dir_handle -> unit**

Reposition the descriptor to the beginning of the directory

**val closedir : dir_handle -> unit**

Close a directory descriptor.

## Pipes and redirections

**val pipe : ?cloexec:bool -> unit -> file_descr * file_descr**

Create a pipe. The first component of the result is opened for reading, that's the exit to the pipe. The second component is opened for writing, that's the entrance to the pipe. See Unix.set_close_on_exec[30.1] for documentation on the cloexec optional argument.

**val mkifo : string -> file_perm -> unit**

Create a named pipe with the given permissions (see Unix.umask[30.1]).

**Raises Invalid_argument on Windows**
Execute the given shell command and return its exit code.

The argument of `Sys.command[29.60]` 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[29.21]` 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 io_buffer_size : int**

Size of C buffers used by the runtime system and IO primitives of the unix library.

Primitives that read from or write to values of type `string` or `bytes` generally use an intermediate buffer of this size to avoid holding the domain lock.

**Since: 5.4**

**val interactive : bool ref**
## High-level process and redirection management

**val create_process :**

```
string ->
```

```
string array -> file_descr -> file_descr -> file_descr -> int
```

`create_process prog args stdin stdout stderr` creates a new process that executes the program in file `prog`, with arguments `args`. The pid of the new process is returned immediately; the new process executes concurrently with the current process. The standard input and outputs of the new process are connected to the descriptors `stdin`, `stdout` and `stderr`. Passing e.g. `Unix.stdout[30.1]` for `stdout` prevents the redirection and causes the new process to have the same standard output as the current process. The executable file `prog` is searched in the path. The new process has the same environment as the current process.

**val create_process_env :**

```
string ->
```

```
string array ->
```

```
string array -> file_descr -> file_descr -> file_descr -> int
```

`create_process_env prog args env stdin stdout stderr` works as `Unix.create_process[30.1]`, except that the extra argument `env` specifies the environment passed to the program.

**val open_process_in : string -> in_channel**

High-level pipe and process management. This function runs the given command in parallel with the program. The standard output of the command is redirected to a pipe, which can be read via the returned input channel. The command is interpreted by the shell `/bin/sh` (or `cmd.exe` on Windows), cf. `Unix.system[30.1]`. The `Filename.quote_command[28.19]` function can be used to quote the command and its arguments as appropriate for the shell being used. If the command does not need to be run through the shell, `Unix.open_process_args_in[30.1]` can be used as a more robust and more efficient alternative to `Unix.open_process_in[30.1]`.

**val open_process_out : string -> out_channel**

Same as `Unix.open_process_in[30.1]`, but redirect the standard input of the command to a pipe. Data written to the returned output channel is sent to the standard input of the command. Warning: writes on output channels are buffered, hence be careful to call `flush[27.2]` at the right times to ensure correct synchronization. If the command does not need to be run through the shell, `Unix.open_process_args_out[30.1]` can be used instead of `Unix.open_process_out[30.1]`.

**val open_process : string -> in_channel * out_channel**

Same as `Unix.open_process_out[30.1]`, but redirects both the standard input and standard output of the command to pipes connected to the two returned channels. The input channel is connected to the output of the command, and the output channel to the input of the command. If the command does not need to be run through the shell, `Unix.open_process_args[30.1]` can be used instead of `Unix.open_process[30.1]`.
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**
val open_process_full :

string ->

string array -> in_channel * out_channel * in_channel

Similar to Unix.open_process[30.1], but the second argument specifies the environment passed to the command. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the command. If the command does not need to be run through the shell, Unix.open_process_args_full[30.1] can be used instead of Unix.open_process_full[30.1].

val open_process_args : string -> string array -> in_channel * out_channel

open_process_args prog args runs the program prog with arguments args. Note that the first argument is by convention the filename of the program being executed, just like Sys.argv.(0). The new process executes concurrently with the current process. The standard input and output of the new process are redirected to pipes, which can be respectively read and written via the returned channels. The input channel is connected to the output of the program, and the output channel to the input of the program.

Warning: writes on output channels are buffered, hence be careful to call flush[27.2] at the right times to ensure correct synchronization.

The executable file prog is searched for in the path. This behaviour changed in 4.12; previously prog was looked up only in the current directory.

The new process has the same environment as the current process.

Since: 4.08

val open_process_args_in : string -> string array -> in_channel

Same as Unix.open_process_args[30.1], but redirects only the standard output of the new process.

Since: 4.08

val open_process_args_out : string -> string array -> out_channel

Same as Unix.open_process_args[30.1], but redirects only the standard input of the new process.

Since: 4.08

val open_process_args_full :

string ->

string array ->

string array -> in_channel * out_channel * in_channel

Similar to Unix.open_process_args[30.1], but the third argument specifies the environment passed to the new process. The result is a triple of channels connected respectively to the standard output, standard input, and standard error of the program.

Since: 4.08

val process_in_pid : in_channel -> int
`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 `max_floatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with `--disable-flat-float-array`.

`val max_floatarray_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 runtime_variant : 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

`val pollActions : unit -> unit`

Run any pending runtime actions, such as minor collections, major GC slices, signal handlers, finalizers, or `memprof` callbacks.

**Since:** 5.3

Signal handling

`type signal = int`

The type for signal numbers.

Negative numbers are used by OCaml to provide a platform-independent number for signals recognised by OCaml. Positive numbers are always the platform-dependent value for a given signal. The function `Sys.signal_of_int[29.60]` converts known platform-dependent numbers to independent ones, and `Sys.signal_to_int[29.60]` does the reverse.

**Since:** 5.4
Return the pid of a process opened via Unix.open_process_in[30.1] or Unix.open_process_args_in[30.1].

Since: 4.08 (4.12 in UnixLabels)

val process_out_pid : out_channel -> int

Return the pid of a process opened via Unix.open_process_out[30.1] or Unix.open_process_args_out[30.1].

Since: 4.08 (4.12 in UnixLabels)

val process_pid : in_channel * out_channel -> int

Return the pid of a process opened via Unix.open_process[30.1] or Unix.open_process_args[30.1].

Since: 4.08 (4.12 in UnixLabels)

val process_full_pid : in_channel * out_channel * in_channel -> int

Return the pid of a process opened via Unix.open_process_full[30.1] or Unix.open_process_args_full[30.1].

Since: 4.08 (4.12 in UnixLabels)

val close_process_in : in_channel -> process_status

Close channels opened by Unix.open_process_in[30.1], wait for the associated command to terminate, and return its termination status.

val close_process_out : out_channel -> process_status

Close channels opened by Unix.open_process_out[30.1], wait for the associated command to terminate, and return its termination status.

val close_process : in_channel * out_channel -> process_status

Close channels opened by Unix.open_process[30.1], wait for the associated command to terminate, and return its termination status.

val close_process_full :

in_channel * out_channel * in_channel ->
process_status

Close channels opened by Unix.open_process_full[30.1], wait for the associated command to terminate, and return its termination status.

## Symbolic links

val symlink : ?to_dir:bool -> string -> string -> unit
type signal Behavior =
| Signal_default
| Signal_IGNORE
| Signal_handle of (signal -> 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 an argument.

`val signal : signal -> signal Behavior -> signal Behavior`

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.

If a platform-dependent signal number is used, it will be converted to a platform-independent signal using `Sys.signal_of_int[29.60]` before calling the handler.

`val set_signal : signal -> signal Behavior -> unit`

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

Signal numbers for the standard POSIX signals.

`val sigabrt : signal`
Abnormal termination

`val sigalrm : signal`
Timeout

`val sigfpe : signal`
Arithmetic exception

`val sighup : signal`
Hangup on controlling terminal

`val sigill : signal`
Invalid hardware instruction

`val sigint : signal`
Interactive interrupt (ctrl-C)

`val sigkill : signal`
Termination (cannot be ignored)
`symlink ?to_dir src dst` creates the file `dst` as a symbolic link to the file `src`. On Windows, `~to_dir` indicates if the symbolic link points to a directory or a file; if omitted, `symlink` examines `src` using `stat` and picks appropriately, if `src` does not exist then `false` is assumed (for this reason, it is recommended that the `~to_dir` parameter be specified in new code). On Unix, `~to_dir` is ignored.

Windows symbolic links are available in Windows Vista onwards. There are some important differences between Windows symlinks and their POSIX counterparts.

Windows symbolic links come in two flavours: directory and regular, which designate whether the symbolic link points to a directory or a file. The type must be correct - a directory symlink which actually points to a file cannot be selected with `chdir` and a file symlink which actually points to a directory cannot be read or written (note that Cygwin's emulation layer ignores this distinction).

When symbolic links are created to existing targets, this distinction doesn't matter and `symlink` will automatically create the correct kind of symbolic link. The distinction matters when a symbolic link is created to a non-existent target.

The other caveat is that by default symbolic links are a privileged operation. Administrators will always need to be running elevated (or with UAC disabled) and by default normal user accounts need to be granted the `SeCreateSymbolicLinkPrivilege` via Local Security Policy (`secpol.msc`) or via Active Directory.

`Unix.has_symlink`[30.1] can be used to check that a process is able to create symbolic links.

**val has_symlink : unit -> bool**

Returns `true` if the user is able to create symbolic links. On Windows, this indicates that the user not only has the `SeCreateSymbolicLinkPrivilege` but is also running elevated, if necessary. On other platforms, this is simply indicates that the symlink system call is available.

**Since: 4.03**

**val readlink : string -> string**

Read the contents of a symbolic link.

## Polling

```hkl
val select :
    file_descr list ->
    file_descr list ->
    file_descr list ->
    float -> file_descr list * file_descr list * file_descr list
```

Wait until some input/output operations become possible on some channels. The three list arguments are, respectively, a set of descriptors to check for reading (first argument), for writing (second argument), or for exceptional conditions (third argument). The fourth argument is the maximal timeout, in seconds; a negative fourth argument means no timeout (unbounded wait). The result is composed of three sets of descriptors: those ready for reading
val sigpipe : signal

Broken pipe

val sigquit : signal

Interactive termination

val sigsegv : signal

Invalid memory reference

val sigterm : signal

Termination

val sigusr1 : signal

Application-defined signal 1

val sigusr2 : signal

Application-defined signal 2

val sigchld : signal

Child process terminated

val sigcont : signal

Continue

val sigstop : signal

Stop (cannot be caught or ignored)

val sigtstp : signal

Interactive stop

val sigttin : signal

Terminal read from background process

val sigttou : signal

Terminal write from background process

val sigvtalrm : signal

Timeout in virtual time

val sigprof : signal

Profiling interrupt

val sigbus : signal
(first component), ready for writing (second component), and over which an exceptional condition is pending (third component).

## Locking

### type lock_command =

```
| FULOCK
```

Unlock a region

```
| F_LOCK
```

Lock a region for writing, and block if already locked

```
| FTLOCK
```

Lock a region for writing, or fail if already locked

```
| F_TEST
```

Test a region for other process locks

```
| FRLOCK
```

Lock a region for reading, and block if already locked

```
| F_TRLOCK
```

Lock a region for reading, or fail if already locked

Commands for Unix.lockf[30.1].

### val lockf : file_descr -> lock_command -> int -> unit

`lockf fd mode len` puts a lock on a region of the file opened as `fd`. The region starts at the current read/write position for `fd` (as set by `Unix.lseek[30.1]`), and extends `len` bytes forward if `len` is positive, `len` bytes backwards if `len` is negative, or to the end of the file if `len` is zero. A write lock prevents any other process from acquiring a read or write lock on the region. A read lock prevents any other process from acquiring a write lock on the region, but lets other processes acquire read locks on it.

The `F_LOCK` and `F_TLOCK` commands attempts to put a write lock on the specified region. The `F_RLOCK` and `F_TRLOCK` commands attempts to put a read lock on the specified region. If one or several locks put by another process prevent the current process from acquiring the lock, `F_LOCK` and `F_RLOCK` block until these locks are removed, while `F_TLOCK` and `F_TRLOCK` fail immediately with an exception. The `F_ULOCK` removes whatever locks the current process has on the specified region. Finally, the `F_TEST` command tests whether a write lock can be acquired on the specified region, without actually putting a lock. It returns immediately if successful, or fails otherwise.

What happens when a process tries to lock a region of a file that is already locked by the same process depends on the OS. On POSIX-compliant systems, the second lock operation succeeds and may "promote" the older lock from read lock to write lock. On Windows, the second lock operation will block or fail.
Bus error

**Since:** 4.03

val sigpoll : signal

Pollable event

**Since:** 4.03

val sigsys : signal

Bad argument to routine

**Since:** 4.03

val sigtrap : signal

Trace/breakpoint trap

**Since:** 4.03

val sigurg : signal

Urgent condition on socket

**Since:** 4.03

val sigxcpu : signal

Timeout in cpu time

**Since:** 4.03

val sigxfsz : signal

File size limit exceeded

**Since:** 4.03

val sigio : signal

I/O is possible on a descriptor

**Since:** 5.4

val sigwinch : signal

Window size change

**Since:** 5.4

val signal_to_string : signal -> string

signal_to_string formats an OCaml signal as a C POSIX constant[http://pubs.opengroup.org/onlinepubs/9799919799/basedefs/signal.h.html] or "SIG(%d)" for platform-dependent signal numbers.

**Since:** 5.4

**Raises** Invalid_argument for unrecognised negative numbers.
## Signals

Note: installation of signal handlers is performed via the functions `Sys.signal[28.55]` and `Sys.set_signal[28.55]`.

val kill : int -> int -> unit

kill pid signal sends signal number signal to the process with id pid.

On Windows: only the `Sys sigkill[28.55]` signal is emulated.

type sigprocmask_command =
| SIG_SETMASK
| SIG_BLOCK
| SIG_UNBLOCK

val sigprocmask : sigprocmask_command -> int list -> int list

sigprocmask mode sigs changes the set of blocked signals. If mode is `SIG_SETMASK`, blocked signals are set to those in the list `sigs`. If mode is `SIG_BLOCK`, the signals in `sigs` are added to the set of blocked signals. If mode is `SIG_UNBLOCK`, the signals in `sigs` are removed from the set of blocked signals. `sigprocmask` returns the set of previously blocked signals.

When the `systhreads` version of the `Thread` module is loaded, this function redirects to `Thread sigmask`. I.e., `sigprocmask` only changes the mask of the current thread.

**Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)

val sigpending : unit -> int list

Return the set of blocked signals that are currently pending.

**Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)

val sigsuspend : int list -> unit

sigsuspend sigs atomically sets the blocked signals to `sigs` and waits for a non-ignored, non-blocked signal to be delivered. On return, the blocked signals are reset to their initial value.

**Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)

val pause : unit -> unit

Wait until a non-ignored, non-blocked signal is delivered.

**Raises** `Invalid_argument` on Windows (no inter-process signals on Windows)

## Time functions

type process_times =
{
  tms_utime : float ;
  User time for the process
tms_stime : float ;
val signal_of_int : int -> signal

signal_of_int n converts a platform-dependent signal number n to an OCaml signal number.

For positive *n* this is *n* itself if OCaml does not have a platform-independent signal number for *n*.

Since: 5.4

Raises Invalid_argument if *n* is negative.

val signal_to_int : signal -> int

signal_to_int n converts an OCaml signal number n to a platform-dependent signal number.

For positive *n* this is *n* itself.

Since: 5.4

Raises Invalid_argument for unrecognised negative numbers.

exception Break

Exception raised on interactive interrupt if `Sys.catch_break[29.60]` is enabled.

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.

Inside multi-threaded programs, the Break exception will arise in any one of the active threads, and will keep arising on further interactive interrupt until all threads are terminated. Use signal masks from Thread sigmask to direct the interrupt towards a specific thread.

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
System time for the process

tms_cutime : float ;

User time for the children processes

tms_cstime : float ;

System time for the children processes

}

The execution times (CPU times) of a process.

type tm =
{
    tm_sec : int ;
        Seconds 0..60
    tm_min : int ;
        Minutes 0..59
    tm_hour : int ;
        Hours 0..23
    tm_mday : int ;
        Day of month 1..31
    tm_mon : int ;
        Month of year 0..11
    tm_year : int ;
        Year - 1900
    tm_wday : int ;
        Day of week (Sunday is 0)
    tm_yday : int ;
        Day of year 0..365
    tm_isdst : bool ;
        Daylight time savings in effect
}

The type representing wallclock time and calendar date.

val time : unit -> float

Return the current time since 00:00:00 GMT, Jan. 1, 1970, in seconds.

val gettimeofday : unit -> float

Same as Unix.time[30.1], but with resolution better than 1 second.

val gmtime : float -> tm
```hml
    type ocaml_release_info =
    {
        major : int ;
        minor : int ;
        patchlevel : int ;
        extra : extra_info option ;
    }
```

**Since: 4.14**

```hml
val ocaml_release : ocaml_release_info
    ocaml_release is the version of OCaml.
```

**Since: 4.14**

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

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

```hml
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. However, it does prevent the argument from being garbage collected until the location where the call would have occurred.

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

```hml
module Immediate64 :
    sig
```
Convert a time in seconds, as returned by Unix.time[30.1], into a date and a time. Assumes UTC (Coordinated Universal Time), also known as GMT. To perform the inverse conversion, set the TZ environment variable to "UTC", use Unix.mktime[30.1], and then restore the original value of TZ.

### `val localtime`: `float` -> `tm`

Convert a time in seconds, as returned by Unix.time[30.1], into a date and a time. Assumes the local time zone. The function performing the inverse conversion is Unix.mktime[30.1].

### `val mktime`: `tm` -> `float` * `tm`

Convert a date and time, specified by the `tm` argument, into a time in seconds, as returned by Unix.time[30.1]. The `tm_isdst`, `tm_wday` and `tm_yday` fields of `tm` are ignored. Also return a normalized copy of the given `tm` record, with the `tm_wday`, `tm_yday`, and `tm_isdst` fields recomputed from the other fields, and the other fields normalized (so that, e.g., 40 October is changed into 9 November). The `tm` argument is interpreted in the local time zone.

### `val alarm`: `int` -> `int`

Schedule a `SIGALRM` signal after the given number of seconds.

**Raises** `Invalid_argument` on Windows

### `val sleep`: `int` -> `unit`

Stop execution for the given number of seconds.

### `val sleepf`: `float` -> `unit`

Stop execution for the given number of seconds. Like `sleep`, but fractions of seconds are supported.

**Since:** 4.03 (4.12 in UnixLabels)

### `val times`: `unit` -> `process_times`

Return the execution times of the process.

On Windows: partially implemented, will not report timings for child processes.

### `val utimes`: `string` -> `float` -> `float` -> `unit`

Set the last access time (second arg) and last modification time (third arg) for a file. Times are expressed in seconds from 00:00:00 GMT, Jan. 1, 1970. If both times are 0.0, the access and last modification times are both set to the current time.

### `type interval_timer` =

| `ITIMER_REAL`
  decrements in real time, and sends the signal `SIGALRM` when expired.

| `ITIMER_VIRTUAL`
  decrements in process virtual time, and sends `SIGVTALRM` when expired.

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

```python
module type Non_immediate =
    sig
```

```python
type t
end
```

```python
module type Immediate =
    sig
```

```python
type t
end
```

```python
module Make :
```

```python
functor (Immediate : Immediate) -> functor (Non_immediate : Non_immediate) ->
    sig
```

```python
type t

type 'a repr =
```

```python
| Immediate : Sys.Immediate64.Immediate.t repr
```

```python
| Non_immediate : Sys.Immediate64.Non_immediate.t repr
```

```python
val repr : t repr
end
```

```python
end
```

```python
end
```

## 29.61 Module Type : Type introspection.

Since: 5.1

### Type equality witness

```python
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`:
(for profiling) decrements both when the process is running and when the system is
running on behalf of the process; it sends `SIGPROF` when expired.

The three kinds of interval timers.

```fortran
type interval_timer_status =
```

{ it_interval : float ;

Period

it_value : float ;

Current value of the timer

}

The type describing the status of an interval timer

val getitimer : interval_timer -> interval_timer_status

Return the current status of the given interval timer.

Raises Invalid_argument on Windows

val setitimer :

interval_timer ->

interval_timer_status -> interval_timer_status

setitimer t s sets the interval timer t and returns its previous status. The s argument is interpreted as follows: s.it_value, if nonzero, is the time to the next timer expiration; s.it_interval, if nonzero, specifies a value to be used in reloading it_value when the timer expires. Setting s.it_value to zero disables the timer. Setting s.it_interval to zero causes the timer to be disabled after its next expiration.

Raises Invalid_argument on Windows

## User id, group id

val getuid : unit -> int

Return the user id of the user executing the process.

On Windows: always returns 1.

val geteuid : unit -> int

Return the effective user id under which the process runs.

On Windows: always returns 1.

val setuid : int -> unit

Set the real user id and effective user id for the process.

Raises Invalid_argument on Windows

val getgid : unit -> int
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.

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[28.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. *)
Return the group id of the user executing the process.

On Windows: always returns 1.

`val getegid : unit -> int`

Return the effective group id under which the process runs.

On Windows: always returns 1.

`val setgid : int -> unit`

Set the real group id and effective group id for the process.

**Raises** `Invalid_argument` on Windows

`val getgroups : unit -> int array`

Return the list of groups to which the user executing the process belongs.

On Windows: always returns `[1]`.

`val setgroups : int array -> unit`

`setgroups` groups sets the supplementary group IDs for the calling process. Appropriate privileges are required.

**Raises** `Invalid_argument` on Windows

`val initgroups : string -> int -> unit`

`initgroups` user group initializes the group access list by reading the group database `/etc/group` and using all groups of which `user` is a member. The additional group `group` is also added to the list.

**Raises** `Invalid_argument` on Windows

```hkl
type passwd_entry =
{
    pw_name : string ;
    pw_passwd : string ;
    pw_uid : int ;
    pw_gid : int ;
    pw_gecos : string ;
    pw_dir : string ;
    pw_shell : string ;
}
```

Structure of entries in the `passwd` database.

```hkl
type group_entry =
{
    gr_name : string ;
    gr_passwd : string ;
    gr_gid : int ;
    gr_mem : string array ;
}
```
```sql
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]. *)

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[29.61] 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[29.61] of use.

## 29.62 Module Uchar : Unicode characters.

Since: 4.03
Structure of entries in the `groups` database.

`val getlogin: unit -> string`

Return the login name of the user executing the process.

`val getpwnam: string -> passwd_entry`

Find an entry in `passwd` with the given name.

**Raises** `Not_found` if no such entry exists, or always on Windows.

`val getgrnam: string -> group_entry`

Find an entry in `group` with the given name.

**Raises** `Not_found` if no such entry exists, or always on Windows.

`val getpwuid: int -> passwd_entry`

Find an entry in `passwd` with the given user id.

**Raises** `Not_found` if no such entry exists, or always on Windows.

`val getgrgid: int -> group_entry`

Find an entry in `group` with the given group id.

**Raises** `Not_found` if no such entry exists, or always on Windows.

## Internet addresses

`type inet_addr`

The abstract type of Internet addresses.

`val inet_addr_of_string: string -> inet_addr`

Conversion from the printable representation of an Internet address to its internal representation. The argument string consists of 4 numbers separated by periods (XXX.YYY.ZZZ.TTT) for IPv4 addresses, and up to 8 numbers separated by colons for IPv6 addresses.

**Raises** `Failure` when given a string that does not match these formats.

`val string_of_inet_addr: inet_addr -> string`

Return the printable representation of the given Internet address. See `Unix.inet_addr_of_string[30.1]` for a description of the printable representation.

`val inet_addr_any: inet_addr`

A special IPv4 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses.

`val inet_addr_loopback: inet_addr`
type t

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+10FFFF.

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[29.62].

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[29.62].

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[29.62].

val to_int : t -> int

to_int u is u as an integer.

val is_char : t -> bool
A special IPv4 address representing the host machine (127.0.0.1).

`val inet6_addr_any : inet_addr`

A special IPv6 address, for use only with `bind`, representing all the Internet addresses that the host machine possesses.

`val inet6_addr_loopback : inet_addr`

A special IPv6 address representing the host machine (::1).

`val is_inet6_addr : inet_addr -> bool`

Whether the given `inet_addr` is an IPv6 address.

**Since: 4.12**

## Sockets

`type socket_domain =`

| PF_UNIX
Unix domain

| PF_INET
Internet domain (IPv4)

| PF_INET6
Internet domain (IPv6)

The type of socket domains. Not all platforms support IPv6 sockets (type `PF_INET6`).

On Windows: `PF_UNIX` supported since 4.14.0 on Windows 10 1803 and later.

`type socket_type =`

| SOCK_STREAM
Stream socket

| SOCK_DGRAM
Datagram socket

| SOCK_RAW
Raw socket

| SOCK
Sequenced packets socket

The type of socket kinds, specifying the semantics of communications. `SOCKliSEQPACKET` is included for completeness, but is rarely supported by the OS, and needs system calls that are not available in this library.

`type sockaddr =`

| ADDR_UNIX of string

| ADDR_INET of inet_addr * int
`is_char` u is true if and only if u is a latin1 OCaml character.

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` [29.62].

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

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

val seeded_hash : int -> t -> int
seeded_hash seed u A seeded hash function with the same output value as
Hashtbl.seeded_hash [29.26]. This function allows this module to be passed as an argument
to the functor Hashtbl.MakeSeeded [29.26].

**Since:** 5.3

val hash : t -> int
An unseeded hash function with the same output value as `Hashtbl.hash` [29.26]. This
function allows this module to be passed as an argument to the functor `Hashtbl.Make` [29.26].

**Before 5.3** The hashing algorithm was different. Use `Hashtbl.rebuild` for stored tables which used this hashing function

## 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 [29.62] otherwise.

val utf_decode_length : utf_decode -> int
The type of socket addresses. `ADDR_UNIX` *name* is a socket address in the Unix domain; *name* is a file name in the file system. `ADDR_INET`(*addr*, *port*) is a socket address in the Internet domain; *addr* is the Internet address of the machine, and *port* is the port number.

**val socket :**
`?cloexec:bool ->`
`socket_domain -> socket_type -> int -> file_descr`

Create a new socket in the given domain, and with the given kind. The third argument is the protocol type; 0 selects the default protocol for that kind of sockets. See `Unix.set_close_on_exec[30.1]` for documentation on the `cloexec` optional argument.

**val domain_of_sockaddr : sockaddr -> socket_domain**

Return the socket domain adequate for the given socket address.

**val socketpair :**
`?cloexec:bool ->`
`socket_domain ->`
`socket_type -> int -> file_descr * file_descr`

Create a pair of unnamed sockets, connected together. See `Unix.set_close_on_exec[30.1]` for documentation on the `cloexec` optional argument.

**val accept : ?cloexec:bool -> file_descr -> file_descr * sockaddr**

Accept connections on the given socket. The returned descriptor is a socket connected to the client; the returned address is the address of the connecting client. See `Unix.set_close_on_exec[30.1]` for documentation on the `cloexec` optional argument.

**val bind : file_descr -> sockaddr -> unit**

Bind a socket to an address.

**val connect : file_descr -> sockaddr -> unit**

Connect a socket to an address.

**val listen : file_descr -> int -> unit**

Set up a socket for receiving connection requests. The integer argument is the maximal number of pending requests.

**type shutdown_command =**
`| SHUTDOWN_RECEIVED`
  Close for receiving
`| SHUTDOWN_SEND`
  Close for sending
`| SHUTDOWN_ALL`
  Close both
`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` [29.62] as the decoded Unicode character.

`val utf_8_decode_length_ofByte : char -> int`

`utf_8_decode_length_ofByte` byte is the number of bytes, from 1 to `Uchar.max_utf_8_decode_length` [29.62], that a valid UTF-8 decode starting with byte `byte` would consume or 0 if `byte` cannot start a valid decode.

Since: 5.4

`val max_utf_8_decode_length : int`

`max_utf_8_decode_length` is 4, the maximal number of bytes a valid or invalid UTF-8 decode can consume.

Since: 5.4

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

## 29.63 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.
The type of commands for shutdown.

`val shutdown : file_descr -> shutdown_command -> unit`

Shutdown a socket connection. `SHUTDOWN_SEND` as second argument causes reads on the other end of the connection to return an end-of-file condition. `SHUTDOWN_RECEIVED` causes writes on the other end of the connection to return a closed pipe condition (`SIGPIPE` signal).

`val getsockname : file_descr -> sockaddr`

Return the address of the given socket.

`val getpeername : file_descr -> sockaddr`

Return the address of the host connected to the given socket.

`type msg_flag =`

`| MSG_OOB`

`| MSG_DONTROUTE`

`| MSG_PEEK`

The flags for Unix.recv[30.1], Unix.recvfrom[30.1], Unix.send[30.1] and Unix.sendto[30.1].

`val recv : file_descr -> bytes -> int -> int -> msg_flag list -> int`

Receive data from a connected socket.

`val recvfrom :`

`file_descr ->`

`bytes -> int -> int -> msg_flag list -> int * sockaddr`

Receive data from an unconnected socket.

`val send : file_descr -> bytes -> int -> int -> msg_flag list -> int`

Send data over a connected socket.

`val send_substring :`

`file_descr -> string -> int -> int -> msg_flag list -> int`

Same as send, but take the data from a string instead of a byte sequence.

**Since: 4.02**

`val sendto :`

`file_descr ->`

`bytes -> int -> int -> msg_flag list -> sockaddr -> int`

Send data over an unconnected socket.

`val sendto_substring :`

`file_descr ->`

`string -> int -> int -> msg_flag list -> sockaddr -> int`

Same as sendto, but take the data from a string instead of a byte sequence.

**Since: 4.02**
```hkl
val equal : t -> t -> bool
    equal u1 u2 is true.
```

```hkl
val compare : t -> t -> int
    compare u1 u2 is 0.
```

```hkl
val to_string : t -> string
    to_string b is "()".
```

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

### Low-level functions

```hkl
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:

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

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

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

```hkl
val length : 'a t -> int
```

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

```hkl
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[29.64] ar - 1.
## Socket options

type socket_bool_option =

| SO_DEBUG

Record debugging information

| SO_BROADCAST

Permit sending of broadcast messages

| SO_REUSEADDR

Allow reuse of local addresses for bind

| SO_KEEPALIVE

Keep connection active

| SO_DONTROUTE

Bypass the standard routing algorithms

| SO_OOBINLINE

Leave out-of-band data in line

| SO_ACCEPTCONN

Report whether socket listening is enabled

| TCP_NODELAY

Control the Nagle algorithm for TCP sockets

| IPV6_ONLY

Forbid binding an IPv6 socket to an IPv4 address

| SO_REUSEPORT

Allow reuse of address and port bindings

The socket options that can be consulted with Unix.getsockopt[30.1] and modified with Unix.setsockopt[30.1]. These options have a boolean (true/false) value.

type socket_int_option =

| SO_SNDBUF

Size of send buffer

| SO_RCVBUF

Size of received buffer

| SO_ERROR

Deprecated. Use Unix.getsockopt_error instead. Deprecated. Use Unix.getsockopt_error[30.1] instead.

| SO_TYPE

Report the socket type

| SO_RCVLOWAT
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[29.64] 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[29.64] 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[29.64] ar n can return None.

Raises Invalid_argument if n is not in the range 0 to Weak.length[29.64] 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.

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[29.26]
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[29.38]).

module type S =

sig
Minimum number of bytes to process for input operations

| **SO_SNDLOWAT**

Minimum number of bytes to process for output operations

The socket options that can be consulted with Unix.getsockopt_int[30.1] and modified
with Unix.setsockopt_int[30.1]. These options have an integer value.

type **socket_optint_option** =

| **SO_LINGER**

Whether to linger on closed connections that have data present, and for how long (in
seconds)

The socket options that can be consulted with Unix.getsockopt_optint[30.1] and modified
with Unix.setsockopt_optint[30.1]. These options have a value of type **int** option, with
None meaning "disabled".

type **socket_float_option** =

| **SO_RCVTIMEO**

Timeout for input operations

| **SO_SNDTIMEO**

Timeout for output operations

The socket options that can be consulted with Unix.getsockopt_float[30.1] and modified
with Unix.setsockopt_float[30.1]. These options have a floating-point value representing a
time in seconds. The value 0 means infinite timeout.

val **getsockopt**: **file_descr** -> **socket_bool_option** -> **bool**

Return the current status of a boolean-valued option in the given socket.

val **setsockopt**: **file_descr** -> **socket_bool_option** -> **bool** -> **unit**

Set or clear a boolean-valued option in the given socket.

val **getsockopt_int**: **file_descr** -> **socket_int_option** -> **int**

Same as Unix.getsockopt[30.1] for an integer-valued socket option.

val **setsockopt_int**: **file_descr** -> **socket_int_option** -> **int** -> **unit**

Same as Unix.setsockopt[30.1] for an integer-valued socket option.

val **getsockopt_optint**: **file_descr** -> **socket_optint_option** -> **int**

Same as Unix.getsockopt[30.1] for a socket option whose value is an **int** option.

val **setsockopt_optint** :

file_descr -> socket_optint_option -> int_option -> unit

Same as Unix.setsockopt[30.1] for a socket option whose value is an int option.

val **getsockopt_float**: **file_descr** -> **socket_float_option** -> **float**
### type data

The type of the elements stored in the table.

### type t

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

### val create : int -> t

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

### val clear : t -> unit

Remove all elements from the table.

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

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

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

### val find : t -> data -> data

`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
Same as Unix.getsockopt[30.1] for a socket option whose value is a floating-point number.

val setsockopt_float : file_descr -> socket_float_option -> float -> unit

Same as Unix.setsockopt[30.1] for a socket option whose value is a floating-point number.

val getsockopt_error : file_descr -> error_option

Return the error condition associated with the given socket, and clear it.

## High-level network connection functions

val open_connection : sockaddr -> in_channel * out_channel

Connect to a server at the given address. Return a pair of buffered channels connected to the server. Remember to call flush[27.2] on the output channel at the right times to ensure correct synchronization.

The two channels returned by open_connection share a descriptor to a socket. Therefore, when the connection is over, you should call close_out[27.2] on the output channel, which will also close the underlying socket. Do not call close_in[27.2] on the input channel; it will be collected by the GC eventually.

val shutdown_connection : in_channel -> unit

"Shut down" a connection established with Unix.open_connection[30.1]; that is, transmit an end-of-file condition to the server reading on the other side of the connection. This does not close the socket and the channels used by the connection. See Unix.open_connection[30.1] for how to close them once the connection is over.

val establish_server :
(in_channel -> out_channel -> unit) -> sockaddr -> unit

Establish a server on the given address. The function given as first argument is called for each connection with two buffered channels connected to the client. A new process is created for each connection. The function Unix.establish_server[30.1] never returns normally.

The two channels given to the function share a descriptor to a socket. The function does not need to close the channels, since this occurs automatically when the function returns. If the function prefers explicit closing, it should close the output channel using close_out[27.2] and leave the input channel unclosed, for reasons explained in Unix.in_channel_of_descr[30.1].

Raises Invalid_argument on Windows. Use threads instead.

## Host and protocol databases

type host_entry =
{
  h_name : string ;
  h_aliases : string array ;
  h_addrtype : socket_domain ;
  h_addr_list : inet_addr array ;
}
`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[29.64]`.

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.

## 29.65 `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.
Structure of entries in the hosts database.

```json
type protocol_entry =
{
    p_name : string ;
    p_alias : string array ;
    p_protocol : int ;
}
```

Structure of entries in the protocols database.

```json
type service_entry =
{
    s_name : string ;
    s_alias : string array ;
    s_port : int ;
    s_protocol : string ;
}
```

Structure of entries in the services database.

```typescript
val gethostname : unit -> string
  Return the name of the local host.
```

```typescript
val gethostbyname : string -> host_entry
  Find an entry in hosts with the given name.
  Raises Not_found if no such entry exists.
```

```typescript
val gethostbyaddr : inet_addr -> host_entry
  Find an entry in hosts with the given address.
  Raises Not_found if no such entry exists.
```

```typescript
val getprotobyname : string -> protocol_entry
  Find an entry in protocols with the given name.
  Raises Not_found if no such entry exists.
```

```typescript
val getprotobynumber : int -> protocol_entry
  Find an entry in protocols with the given protocol number.
  Raises Not_found if no such entry exists.
```

```typescript
val getservbyname : string -> string -> service_entry
  Find an entry in services with the given name.
  Raises Not_found if no such entry exists.
```

```typescript
val getservbyport : int -> string -> service_entry
  Find an entry in services with the given service number.
  Raises Not_found if no such entry exists.
```
<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>- - (prefix)</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>
```c
type addr_info =
{
    ai_family : socket_domain ;
        Socket domain

    ai_socktype : socket_type ;
        Socket type

    ai_protocol : int ;
        Socket protocol number

    ai_addr : sockaddr ;
        Address

    ai_canonname : string ;
        Canonical host name
}

Address information returned by Unix.getaddrinfo[30.1].
```

```c
type getaddrinfo_option =
{
    AIFamily of socket_domain
        Impose the given socket domain

    AI类型 of socket_type
        Impose the given socket type

    AI_PROTOCOL of int
        Impose the given protocol

    AI_NUMERICHOST
        Do not call name resolver, expect numeric IP address

    AI_CANONNAME
        Fill the ai_canonname field of the result

    AI_PASSIVE
        Set address to "any" address for use with Unix.bind[30.1]

    Options to Unix.getaddrinfo[30.1].
```

```c
val getaddrinfo :
    string -> string -> getaddrinfo_option list -> addr_info list

    getaddrinfo host service opts returns a list of Unix addressed records describing
    socket parameters and addresses suitable for communicating with the given host and service.
    The empty list is returned if the host or service names are unknown, or the constraints
    expressed in opts cannot be satisfied.
```

`host` is either a host name or the string representation of an IP address. `host` can be given as the empty string; in this case, the "any" address or the "loopback" address are used, depending whether `opts` contains `AI_PASSIVE`. `service` is either a service name or the string
Chapter 30

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

30.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[30.1] enables AST rewriting using open recursion. A typical mapper would
be based on Ast_mapper.default_mapper[30.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
representation of a port number. `service` can be given as the empty string; in this case, the port field of the returned addresses is set to 0. `opts` is a possibly empty list of options that allows the caller to force a particular socket domain (e.g. IPv6 only or IPv4 only) or a particular socket type (e.g. TCP only or UDP only).

```c
type name_info =
{
    ni_hostname : string ;
    Name or IP address of host

    ni_service : string ;
    Name of service or port number
}

Host and service information returned by Unix.getnameinfo[30.1].
```

```c
type getnameinfo_option =
{
    NI_NOFQDN
    Do not qualify local host names

    NI_NUMERICHOST
    Always return host as IP address

    NI_NAMEREQD
    Fail if host name cannot be determined

    NI_NUMERICSERV
    Always return service as port number

    NI_DGRAM
    Consider the service as UDP-based instead of the default TCP
    Options to Unix.getnameinfo[30.1].
```

```c
val getnameinfo : sockaddr -> getnameinfo_option list -> name_info
getnameinfo addr opts returns the host name and service name corresponding to the
socket address addr. opts is a possibly empty list of options that governs how these names
are obtained.

Raises Not_found if an error occurs.
```

## Terminal interface

The following functions implement the POSIX standard terminal interface. They provide control over asynchronous communication ports and pseudo-terminals. Refer to the termios man page for a complete description.

```c
type terminal_io =
{
    mutable c_ignbrk : bool ;
    Ignore the break condition.
```
```h
let test_mapper argv =
{
  default_mapper with
    expr = fun mapper expr ->
      match expr with
      | { pexp_desc = Pexp_extension ({ txt = "test" }, PStr [])} ->
        Ast_helper.Expimmer (Pconst_integer ("42", None))
      | other -> default_mapper_expr mapper other;
}
```

```h
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[30].

## A generic Parsetree mapper

```h
type mapper =
{
  attribute : mapper -> Parsetree.attribute -> Parsetree.attribute ;
  attributes : mapper -> Parsetree.attribute list -> Parsetree.attribute list ;
  binding_op : mapper -> Parsetree.bindinOp -> Parsetree.bindinOp ;
  case : mapper -> Parsetree.case -> Parsetree.case ;
  cases : mapper -> Parsetree.case list -> Parsetree.case list ;
  class_declaration : mapper ->
    Parsetree.class_declaration -> Parsetree.class_declaration ;
  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_signatur : mapper -> Parsetree.class_signatur -> Parsetree.class_signatur ;
  class_structure : mapper -> Parsetree.class_structure -> Parsetree.class_structure ;
  class_type : mapper -> Parsetree.class_type -> Parsetree.class_type ;
  class_type_declaration : mapper ->
    Parsetree.class_type_declaration -> Parsetree.class_type_declaration ;
  class_type_field : mapper -> Parsetree.class_type_field -> Parsetree.class_type_field ;
  constant : mapper -> Parsetree constant -> Parsetree constant ;
  constructor_declaration : mapper ->
    Parsetree constructor_declaration -> Parsetree constructor_declaration ;
  directive_argument : mapper ->
    Parsetree.directive_argument -> Parsetree.directive_argument ;
  expr : mapper -> Parsetree.expression -> Parsetree.expression ;
  extension : mapper -> Parsetree.extension -> Parsetree.extension ;
  extension_construct : mapper ->
    Parsetree.extension_construct -> Parsetree.extension_construct ;
```
mutable c_brkint : bool ;

Signal interrupt on break condition.

mutable c_ignpar : bool ;

Ignore characters with parity errors.

mutable c_parmrk : bool ;

Mark parity errors.

mutable c_inpck : bool ;

Enable parity check on input.

mutable c_istrip : bool ;

Strip 8th bit on input characters.

mutable c_inlcr : bool ;

Map NL to CR on input.

mutable c_igncr : bool ;

Ignore CR on input.

mutable c_icrnl : bool ;

Map CR to NL on input.

mutable c_ixon : bool ;

Recognize XON/XOFF characters on input.

mutable c_ixoff : bool ;

Emit XON/XOFF chars to control input flow.

mutable c_opost : bool ;

Enable output processing.

mutable c_obaud : int ;

Output baud rate (0 means close connection).

mutable c_ibaud : int ;

Input baud rate.

mutable c_csize : int ;

Number of bits per character (5-8).

mutable c_cstopb : int ;

Number of stop bits (1-2).

mutable c_cread : bool ;

Reception is enabled.

mutable c_parenb : bool ;

Enable parity generation and detection.
includeDeclaration : mapper ->
Parsetree.include declaration -> Parsetree.include declaration ;
include_description : mapper ->
Parsetree.include_description -> Parsetree.include_description ;
label_statement : mapper ->
Parsetree.label_statement -> Parsetree.label_statement ;
location : mapper -> Location.t -> Location.t ;
module binding : mapper -> Parsetree.module binding -> Parsetree.module
binding ;
module_statement : mapper ->
Parsetree.module_statement -> Parsetree.module_statement ;
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_statement : mapper ->
Parsetree.module_type_statement -> Parsetree.module_type_statement ;
open_statement : mapper -> Parsetree.open_statement -> Parsetree.open_statement ;
open_description : mapper -> Parsetree.open_description -> Parsetree.open_description ;
package_type : mapper -> Parsetreeotts package_type -> Parsetree package_type ;
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 ;
tLEVEL directive : mapper ->
Parsetree.tOplevel_directive -> Parsetree.tOplevel_directive ;
tOplevel_p挥ate : mapper -> Parsetree.tOplevel_p挥ate -> Parsetree.tOplevel_p挥ate ;
typ : mapper -> Parsetree.core_type -> Parsetree.core_type ;
type_statement : mapper -> Parsetree.type_statement -> Parsetree.type_statement ;
type_extensions : mapper -> Parsetree.type_extensions -> Parsetree.type_extensions ;
type_exception : mapper -> Parsetree.type_exception -> Parsetree.type_exception ;
type_type : mapper -> Parsetree.type_type -> Parsetree.type_type ;
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.

val default_mapper : mapper

A default mapper, which implements a "deep identity" mapping.
mutable c_parodd : bool ;
Specify odd parity instead of even.

mutable c_hupcl : bool ;
Hang up on last close.

mutable c_clocal : bool ;
Ignore modem status lines.

mutable c_isig : bool ;
Generate signal on INTR, QUIT, SUSP.

mutable c_icanon : bool ;
Enable canonical processing (line buffering and editing).

mutable c_noflsh : bool ;
Disable flush after INTR, QUIT, SUSP.

mutable c.echo : bool ;
Echo input characters.

mutable c.echoe : bool ;
Echo ERASE (to erase previous character).

mutable c_echok : bool ;
Echo KILL (to erase the current line).

mutable c_echonl : bool ;
Echo NL even if c.echo is not set.

mutable c_vintr : char ;
Interrupt character (usually ctrl-C).

mutable c_vquit : char ;
Quit character (usually ctrl-\).

mutable c_verase : char ;
Erase character (usually DEL or ctrl-H).

mutable c_vkill : char ;
Kill line character (usually ctrl-U).

mutable c_veof : char ;
End-of-file character (usually ctrl-D).

mutable c_veol : char ;
Alternate end-of-line char. (usually none).

mutable c_vmin : int ;
Minimum number of characters to read before the read request is satisfied.
## Apply mappers to compilation units

**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 command-line options are automatically synchronized between the calling tool and the ppx preprocessor: `Clflags.include_dirs[??]`, `Clflags hidden_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[30.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.
mutable c_vtime : int ;
Maximum read wait (in 0.1s units).

mutable c_vstart : char ;
Start character (usually ctrl-Q).

mutable c_vstop : char ;
Stop character (usually ctrl-S).

}

val tcgetattr : file_descr -> terminal_io

Return the status of the terminal referred to by the given file descriptor.

Raises Invalid_argument on Windows

typesetattr_when =
| TCSANOW
| TCSADRAIN
| TCSAFLUSH

val tcsetattr : file_descr ->setattr_when -> terminal_io -> unit

Set the status of the terminal referred to by the given file descriptor. The second argument indicates when the status change takes place: immediately (TCSANOW), when all pending output has been transmitted (TCSADRAIN), or after flushing all input that has been received but not read (TCSAFLUSH). TCSADRAIN is recommended when changing the output parameters; TCSAFLUSH, when changing the input parameters.

Raises Invalid_argument on Windows

val tcsendbreak : file_descr -> int -> unit

Send a break condition on the given file descriptor. The second argument is the duration of the break, in 0.1s units; 0 means standard duration (0.25s).

Raises Invalid_argument on Windows

val tcdrain : file_descr -> unit

Wait until all output written on the given file descriptor has been transmitted.

Raises Invalid_argument on Windows

type flush_queue =
| TCIFLUSH
| TCOFLUSH
| TCIOFLUSH

val tcflush : file_descr -> flush_queue -> unit

Discard data written on the given file descriptor but not yet transmitted, or data received but not yet read, depending on the second argument: TCIFLUSH flushes data received but not read, TCOFLUSH flushes data written but not transmitted, and TCIOFLUSH flushes both.

Raises Invalid_argument on Windows
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

## 30.2 Module Asttypes: Auxiliary AST types used by parsetree and typedtree.

**Warning:** this module is unstable and part of compiler-libs[30].

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
```
type flow_action =
| TCOOFF
| TCOON
| TCIOFF
| TCION
```

```
val tcflow : file_descr -> flow_action -> unit
```

Suspend or restart reception or transmission of data on the given file descriptor, depending on the second argument: `TCOOFF` suspends output, `TCOON` restarts output, `TCIOFF` transmits a `STOP` character to suspend input, and `TCION` transmits a `START` character to restart input.

Raises `Invalid_argument` on Windows

```
val setsid : unit -> int
```

Put the calling process in a new session and detach it from its controlling terminal.

Raises `Invalid_argument` on Windows

## 30.2 Module UnixLabels: labelized version of the interface

This module is identical to Unix (30.1), and only differs by the addition of labels. You may see these labels directly by looking at `unixLabels.mli`, or by using the `ocamlbrowser` tool.
```
| Recursive
type direction_flag =
| Upto
| Downto
```

```
type private_flag =
| Private
| Public
```

```
type mutable_flag =
| Immutable
| Mutable
```

```
type atomic_flag =
| Nonatomic
| Atomic
```

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

```
type injectivity =
| Injective
| NoInjectivity
```

```
val string_of_label : arg_label -> string
```
**Windows:**

The Cygwin port of OCaml fully implements all functions from the Unix module. The native Win32 ports implement a subset of them. Below is a list of the functions that are not implemented, or only partially implemented, by the Win32 ports. Functions not mentioned are fully implemented and behave as described previously in this chapter.
## 30.3 Module Location: Source code locations (ranges of positions), used in parsetree.

**Warning:** this module is unstable and part of compiler-libs[30].

```python
type t = Warnings.loc =
{
    loc_start: Lexingiltposition;
    loc_end: Lexingiltposition;
    loc_ghost: bool;
}
```

t represents a range of characters in the source code.

`loc_ghost=false` whenever the AST described by the location can be parsed from the location. In all other cases, `loc_ghost` must be true. Most locations produced by the parser have `loc_ghost=false`. When `loc_ghost=true`, the location is usually a best effort approximation.

This info is used by tools like merlin that want to relate source code with parsetrees or later asts. `ocamlprof` skips instrumentation of ghost nodes.

Example: in `let f x = x'`, we have:

* a structure item at location "let f x = x"

* a pattern "f" at location "f"

* an expression "fun x → x" at location "x = x" with `loc_ghost=true`

* a pattern "x" at location "x"

* an expression "x" at location "x" In this case, every node has `loc_ghost=false`, except the node "fun x → x", since `Parser.expression` (`Lexing.from_string "x = x"`) would fail to parse. By contrast, in `let f = fun x → x'`, every node has `loc_ghost=false`.

Line directives can modify the filenames and line numbers arbitrarily, which is orthogonal to `loc_ghost`, which describes the range of characters from `loc_start.pos_cnum` to `loc_end.pos_cnum` in the parsed string.

Note on the use of `Lexingiltposition` 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.

```python
val none : t
```

An arbitrary value of type `t`; describes an empty ghost range.

```python
val is_none : t -> bool
```

True for `Location.some`, false any other location

```python
val in_file : string -> t
```

Return an empty ghost range located in a given file.

```python
val init : Lexing.lexbuf -> string -> unit
```
<table><thead><tr><td>Functions</td><td>Comment</td></tr></thead><tbody><tr><td>fork</td><td>not implemented, use create_process or threads</td></tr><tr><td>wait</td><td>not implemented, use waitpid</td></tr><tr><td>waitpid</td><td>can only wait for a given PID, not any child process</td></tr><tr><td>getppid</td><td>not implemented (meaningless under Windows)</td></tr><tr><td>nice</td><td>not implemented</td></tr><tr><td>truncate, ftruncate</td><td>implemented (since 4.10.0)</td></tr><tr><td>link</td><td>implemented (since 3.02)</td></tr><tr><td>fchmod</td><td>not implemented</td></tr><tr><td>chown, fchown</td><td>not implemented (make no sense on a DOS file system)</td></tr><tr><td>umask</td><td>not implemented</td></tr><tr><td>access</td><td>execute permission X_OK cannot be tested, it just tests for read permission instead</td></tr><tr><td>chroot</td><td>not implemented</td></tr><tr><td>mkfifo</td><td>not implemented</td></tr><tr><td>symlink, readlink</td><td>implemented (since 4.03.0)</td></tr><tr><td>kill</td><td>partially implemented (since 4.00.0): only the sigkill signal is implemented</td></tr><tr><td>sigprocmask, sigpending, sigsuspend</td><td>not implemented (no inter-process signals on Windows)</td></tr><tr><td>pause</td><td>not implemented (no inter-process signals in Windows)</td></tr><tr><td>alarm</td><td>not implemented</td></tr><tr><td>times</td><td>partially implemented, will not report timings for child processes</td></tr><tr><td>getitimer, setitimer</td><td>not implemented</td></tr><tr><td>getuid, geteuid, getgid, getegid</td><td>always return 1</td></tr><tr><td>setuid, setgid, setgroups, initgroups</td><td>not implemented</td></tr><tr><td>getgroups</td><td>always returns [1] (since 2.00)</td></tr><tr><td>getpwnam, getpwuid</td><td>always raise Not_found</td></tr><tr><td>getgrnam, getgrgid</td><td>always raise Not_found</td></tr><tr><td>type socket_domain</td><td>PF_INET is fully supported; PF_INET6 is fully supported (since 4.01.0); PF_UNIX is supported since 4.14.0, but only works on Windows 10 1803 and later.</td></tr><tr><td>establish_server</td><td>not implemented; use threads</td></tr><tr><td>terminal functions (tc*)</td><td>not implemented</td></tr><tr><td>setsid</td><td>not implemented</td></tr></tbody></table>
Set the file name and line number of the `lexbuf` to be the start of the named file.

val curr : Lexing.lexbuf -> t

Get the location of the current token from the `lexbuf`.

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.

val rhs_interval : int -> int -> t

val get_pos_info : Lexingikt position -> string * int * int

file, line, char

type 'a loc =

{ txt : 'a ;
    loc : t ;
}

val mknoloc : 'a -> 'a loc

val mkloc : 'a -> t -> 'a loc

## Input info

val input_name : string ref

val inputisi : Lexing.ilexbuf option ref

val input_pnme : Buffer.t option ref

## TLEVEL-SPECIFIC FUNCTIONS

val echo_eof : unit -> unit

val reset : unit -> unit

## Rewriting path

val rewrite_absolute_path : string -> string

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

`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/]
* `.` Matches any character except newline.

* `*` (postfix) Matches the preceding expression zero, one or several times

* `+` (postfix) Matches the preceding expression one or several times

* `?` (postfix) Matches the preceding expression once or not at all

* `[..]` Character set. Ranges are denoted with `-`, as in `[a-z]`. An initial `^`, as in `[^0-9]`, complements the set. To include a `]` character in a set, make it the first character of the set. To include a `-` character in a set, make it the first or the last character of the set.

* `^` Matches at beginning of line: either at the beginning of the matched string, or just after a `\n` character.

* `$` Matches at end of line: either at the end of the matched string, or just before a `\n` character.

* `\|` (infix) Alternative between two expressions.

* `\(..\)` Grouping and naming of the enclosed expression.

* `\1` The text matched by the first `\(...\)` expression (`\2` for the second expression, and so on up to `\9`).

* `\b` Matches word boundaries.

* `\` Quotes special characters. The special characters are `$^\.\*+?[]`.

In regular expressions you will often use backslash characters; it's easier to use a quoted string literal `{|...|}` to avoid having to escape backslashes.

For example, the following expression:

```hml
let r = Str.regexp {|hello \([A-Za-z]+\)|} in
    Str.replace_first r {|\1|} "hello world"
```

returns the string `"world"`.

If you want a regular expression that matches a literal backslash character, you need to double it: `Str.regexp {|\\}|`.

You can use regular string literals `"..."` too, however you will have to escape backslashes.

The example above can be rewritten with a regular string literal as:

```hml
let r = Str.regexp "hello \\[A-Za-z]+\)" in
    Str.replace_first r "\\1" "hello world"
```

And the regular expression for matching a backslash becomes a quadruple backslash:

```
Str.regexp "\\\\".
```

`val regexp_case_foil : string -> regexp`

Same as `regexp`, but the compiled expression will match text in a case-insensitive way: uppercase and lowercase letters will be considered equivalent.

`val quote : string -> string`

`Str.quote s` returns a regexp string that matches exactly `s` and nothing else.