---
name: "Misc"
section: "3o"
platform: "linux"
package: "ocaml"
version: "5.5.0-1"
release: "Arch Linux 2026-11-01"
platforms: ["linux"]
url: "https://new.carta.tech/Misc"
---

# Misc(3o)

Miscellaneous useful types and functions

## NAME

Misc - Miscellaneous useful types and functions

## Module

Module   Misc

## Documentation

Module **Misc**\
  :  **sig end**

Miscellaneous useful types and functions

Warning: this module is unstable and part of **Compiler\_libs** .

### Reporting fatal errors

*val fatal\_error* :  **string -\> 'a**

Raise the  **Fatal\_error** exception with the given string.

*val fatal\_errorf* :  **('a, Format.formatter, unit, 'b) format4 -\> 'a**

Format the arguments according to the given format string and raise  **Fatal\_error** with the resulting string.

*exception Fatal\_error*

### Exceptions and finalization

*val try\_finally* :  **?always:(unit -\> unit) -\> ?exceptionally:(unit -\> unit) -\> (unit -\> 'a) -\> 'a**

**try\_finally work ~always ~exceptionally** is designed to run code in  **work** that may fail with an exception, and has two kind of cleanup routines:  **always** , that must be run after any execution of the function (typically, freeing system resources), and **exceptionally** , that should be run only if  **work** or  **always** failed with an exception (typically, undoing user-visible state changes that would only make sense if the function completes correctly). For example:

```
      let objfile = outputprefix ^ ".cmo" in
      let oc = open_out_bin objfile in
      Misc.try_finally
        (fun () ->
           bytecode
           ++ Timings.(accumulate_time (Generate sourcefile))
               (Emitcode.to_file oc modulename objfile);
           Warnings.check_fatal ())
        ~always:(fun () -> close_out oc)
        ~exceptionally:(fun _exn -> remove_file objfile);

```

If  **exceptionally** fail with an exception, it is propagated as usual.

If  **always** or  **exceptionally** use exceptions internally for control-flow but do not raise, then  **try\_finally** is careful to preserve any exception backtrace coming from  **work** or  **always** for easier debugging.

*val reraise\_preserving\_backtrace* :  **exn -\> (unit -\> unit) -\> 'a**

**reraise\_preserving\_backtrace e f** is (f (); raise e) except that the current backtrace is preserved, even if  **f** uses exceptions internally.

### List operations

*val map\_end* :  **('a -\> 'b) -\> 'a list -\> 'b list -\> 'b list**

**map\_end f l t** is  **map f l @ t** , just more efficient.

*val rev\_map\_end* :  **('a -\> 'b) -\> 'a list -\> 'b list -\> 'b list**

**map\_end f l t** is  **map f (rev l) @ t** , just more efficient.

*val map\_left\_right* :  **('a -\> 'b) -\> 'a list -\> 'b list**

Like  **List.map** , with guaranteed left-to-right evaluation order

*val for\_all2* :  **('a -\> 'b -\> bool) -\> 'a list -\> 'b list -\> bool**

Same as  **List.for\_all** but for a binary predicate. In addition, this  **for\_all2** never fails: given two lists with different lengths, it returns false.

*val replicate\_list* :  **'a -\> int -\> 'a list**

**replicate\_list elem n** is the list with  **n** elements all identical to  **elem** .

*val list\_remove* :  **'a -\> 'a list -\> 'a list**

**list\_remove x l** returns a copy of  **l** with the first element equal to  **x** removed.

*val split\_last* :  **'a list -\> 'a list \* 'a**

Return the last element and the other elements of the given list.

*val repeated\_label* :  **(string option \* 'a) list -\> string option**

Detects a repeated label - for use with labeled tuples.

### Hash table operations

*val create\_hashtable* :  **int -\> ('a \* 'b) list -\> ('a, 'b) Hashtbl.t**

Create a hashtable with the given initial size and fills it with the given bindings.

### Extensions to the standard library

*module Stdlib :* **sig end**

### Operations on files and file paths

*val find\_in\_path* :  **string list -\> string -\> string**

Search a file in a list of directories.

*val find\_in\_path\_rel* :  **string list -\> string -\> string**

Search a relative file in a list of directories.

*val normalized\_unit\_filename* :  **string -\> (string, string) Result.t**

Normalize file name  **Foo.ml** to  **foo.ml** , using NFC and case-folding. Return  **Error** if the input is not a valid utf-8 byte sequence

*val find\_in\_path\_normalized* :  **string list -\> string -\> string**

Same as  **Misc.find\_in\_path\_rel** , but search also for normalized unit filename, i.e. if name is  **Foo.ml** , allow  **/path/Foo.ml** and  **/path/foo.ml** to match.

*val remove\_file* :  **string -\> unit**

Delete the given file if it exists and is a regular file. Does nothing for other kinds of files. Never raises an error.

*val expand\_directory* :  **string -\> string -\> string**

**expand\_directory alt file** eventually expands a  **+** at the beginning of file into  **alt** (an alternate root directory)

*val split\_path\_contents* :  **?sep:char -\> string -\> string list**

**split\_path\_contents ?sep s** interprets  **s** as the value of a "PATH"-like variable and returns the corresponding list of directories.  **s** is split using the platform-specific delimiter, or **~sep** if it is passed.

Returns the empty list if  **s** is empty.

*val copy\_file* :  **in\_channel -\> out\_channel -\> unit**

**copy\_file ic oc** reads the contents of file  **ic** and copies them to  **oc** . It stops when encountering EOF on  **ic** .

*val copy\_file\_chunk* :  **in\_channel -\> out\_channel -\> int -\> unit**

**copy\_file\_chunk ic oc n** reads  **n** bytes from  **ic** and copies them to  **oc** . It raises  **End\_of\_file** when encountering EOF on  **ic** .

*val string\_of\_file* :  **in\_channel -\> string**

**string\_of\_file ic** reads the contents of file  **ic** and copies them to a string. It stops when encountering EOF on  **ic** .

*val output\_to\_file\_via\_temporary* :  **?mode:open\_flag list -\>** **string -\> (string -\> out\_channel -\> 'a) -\> 'a**

Produce output in temporary file, then rename it (as atomically as possible) to the desired output file name. **output\_to\_file\_via\_temporary filename fn** opens a temporary file which is passed to  **fn** (name + output channel).  When  **fn** returns, the channel is closed and the temporary file is renamed to **filename** .

*val protect\_writing\_to\_file* :  **filename:string -\> f:(out\_channel -\> 'a) -\> 'a**

Open the given  **filename** for writing (in binary mode), pass the  **out\_channel** to the given function, then close the channel. If the function raises an exception then  **filename** will be removed.

*val concat\_null\_terminated* :  **string list -\> string**

**concat\_null\_terminated \[x1;x2; ... xn\]** is **x1 ^ "\\000" ^ x2 ^ "\\000" ^ ... ^ xn ^ "\\000"**

*val split\_null\_terminated* :  **string -\> string list**

**split\_null\_terminated s** is similar **String.split\_on\_char '\\000'** but ignores the trailing separator, if any

*val chop\_extensions* :  **string -\> string**

Return the given file name without its extensions. The extensions is the longest suffix starting with a period and not including a directory separator,  **.xyz.uvw** for instance.

Return the given name if it does not contain an extension.

### Integer operations

*val log2* :  **int -\> int**

**log2 n** returns  **s** such that  **n = 1 lsl s** if  **n** is a power of 2

*val align* :  **int -\> int -\> int**

**align n a** rounds  **n** upwards to a multiple of  **a** (a power of 2).

*val no\_overflow\_add* :  **int -\> int -\> bool**

**no\_overflow\_add n1 n2** returns  **true** if the computation of **n1 + n2** does not overflow.

*val no\_overflow\_sub* :  **int -\> int -\> bool**

**no\_overflow\_sub n1 n2** returns  **true** if the computation of **n1 - n2** does not overflow.

*val no\_overflow\_mul* :  **int -\> int -\> bool**

**no\_overflow\_mul n1 n2** returns  **true** if the computation of **n1 \* n2** does not overflow.

*val no\_overflow\_lsl* :  **int -\> int -\> bool**

**no\_overflow\_lsl n k** returns  **true** if the computation of **n lsl k** does not overflow.

*val letter\_of\_int* :  **int -\> string**

*module Int\_literal\_converter :* **sig end**

*val find\_first\_mono* :  **(int -\> bool) -\> int**

**find\_first\_mono p** takes an integer predicate  **p : int -\> bool** that we assume: 1. is monotonic on natural numbers: if  **a \<= b** then  **p a** implies  **p b** , 2. is satisfied for some natural numbers in range  **0; max\_int** (this is equivalent to:  **p max\_int = true** ).

**find\_first\_mono p** is the smallest natural number N that satisfies  **p** , computed in O(log(N)) calls to  **p** .

Our implementation supports two cases where the preconditions on  **p** are not respected:

\-If  **p** is always  **false** , we silently return  **max\_int** instead of looping or crashing.

\-If  **p** is non-monotonic but eventually true, we return some satisfying value.

### String operations

*val search\_substring* :  **string -\> string -\> int -\> int**

**search\_substring pat str start** returns the position of the first occurrence of string  **pat** in string  **str** .  Search starts at offset  **start** in  **str** .  Raise  **Not\_found** if  **pat** does not occur.

*val replace\_substring* :  **before:string -\> after:string -\> string -\> string**

**replace\_substring ~before ~after str** replaces all occurrences of  **before** with  **after** in  **str** and returns the resulting string.

*val rev\_split\_words* :  **string -\> string list**

**rev\_split\_words s** splits  **s** in blank-separated words, and returns the list of words in reverse order.

*val cut\_at* :  **string -\> char -\> string \* string**

**String.cut\_at s c** returns a pair containing the sub-string before the first occurrence of  **c** in  **s** , and the sub-string after the first occurrence of  **c** in  **s** . **let (before, after) = String.cut\_at s c in**\
     **before ^ String.make 1 c ^ after** is the identity if  **s** contains  **c** .

Raise  **Not\_found** if the character does not appear in the string

**Since** 4.01

*val ordinal\_suffix* :  **int -\> string**

**ordinal\_suffix n** is the appropriate suffix to append to the numeral  **n** as an ordinal number:  **1** -\>  **"st"** ,  **2** -\>  **"nd"** ,  **3** -\>  **"rd"** , **4** -\>  **"th"** , and so on.  Handles larger numbers (e.g.,  **42** -\>  **"nd"** ) and the numbers 11--13 (which all get  **"th"** ) correctly.

*val normalise\_eol* :  **string -\> string**

**normalise\_eol s** returns a fresh copy of  **s** with any '\\r' characters removed. Intended for pre-processing text which will subsequently be printed on a channel which performs EOL transformations (i.e. Windows)

*val delete\_eol\_spaces* :  **string -\> string**

**delete\_eol\_spaces s** returns a fresh copy of  **s** with any end of line spaces removed. Intended to normalize the output of the toplevel for tests.

### Operations on references

*type ref\_and\_value* =\
  \| R **:** **'a ref \* 'a** **-\>** **ref\_and\_value**

*val protect\_refs* :  **ref\_and\_value list -\> (unit -\> 'a) -\> 'a**

**protect\_refs l f** temporarily sets  **r** to  **v** for each  **R (r, v)** in  **l** while executing  **f** . The previous contents of the references is restored even if  **f** raises an exception, without altering the exception backtrace.

*val get\_ref* :  **'a list ref -\> 'a list**

**get\_ref lr** returns the content of the list reference  **lr** and reset its content to the empty list.

*val set\_or\_ignore* :  **('a -\> 'b option) -\> 'b option ref -\> 'a -\> unit**

**set\_or\_ignore f opt x** sets  **opt** to  **f x** if it returns  **Some \_** , or leaves it unmodified if it returns  **None** .

### Operations on triples and quadruples

*val fst3* :  **'a \* 'b \* 'c -\> 'a**

*val snd3* :  **'a \* 'b \* 'c -\> 'b**

*val thd3* :  **'a \* 'b \* 'c -\> 'c**

*val fst4* :  **'a \* 'b \* 'c \* 'd -\> 'a**

*val snd4* :  **'a \* 'b \* 'c \* 'd -\> 'b**

*val thd4* :  **'a \* 'b \* 'c \* 'd -\> 'c**

*val for4* :  **'a \* 'b \* 'c \* 'd -\> 'd**

### Spell checking and \`\`did you mean'' suggestions

*val edit\_distance* :  **string -\> string -\> int -\> int option**

**edit\_distance a b cutoff** computes the edit distance between strings  **a** and  **b** . To help efficiency, it uses a cutoff: if the distance  **d** is smaller than  **cutoff** , it returns  **Some d** , else **None** .

The distance algorithm currently used is Damerau-Levenshtein: it computes the number of insertion, deletion, substitution of letters, or swapping of adjacent letters to go from one word to the other. The particular algorithm may change in the future.

*val spellcheck* :  **string list -\> string -\> string list**

**spellcheck env name** takes a list of names  **env** that exist in the current environment and an erroneous  **name** , and returns a list of suggestions taken from  **env** , that are close enough to **name** that it may be a typo for one of them.

*val align\_hint* :  **prefix:string -\>** **main:Format\_doc.t -\> hint:Format\_doc.t -\> Format\_doc.t \* Format\_doc.t**

**aligned\_hint main hint** vertically aligns a  **main** message and a hint message. The vertical alignment is controlled by the use of  **@{\<ralign\> ...**\
     **@}** boxes: the start of one box, in either the hint or the main message, will be shifted on the left to ensure that the end of the two boxes are vertically aligned, taking in account a pre-existing  **prefix** before the main message. For instance,

```
let main, sub =
  align_hint
    ~prefix:"Error: "
    (doc_printf "@{<ralign>The value @}%a is not an instance variable"
      Style.inline_code "foobar"
    )
    (doc_printf
      "@{<ralign>Did you mean @}%a" Style.inline_code "foobaz"
    ) in
   printf "Error: %a%a" pp_doc main pp_doc sub
```

produces the following text:

```
Error:   The value "foobaz" is not an instance variable
Hint: Did you mean "foobar"?
```

where the main message has been shifted to the left to align  **"foobaz"** and **"foobar"** .

*val align\_error\_hint* :  **main:Format\_doc.t -\> hint:Format\_doc.t -\> Format\_doc.t \* Format\_doc.t**

Same as  **align\_hint ~prefix:"Error: "**

*val aligned\_hint* :  **prefix:string -\>** **Format\_doc.formatter -\>** **('a, Format\_doc.formatter, unit, Format\_doc.t option -\> unit) format4 -\>** **'a**

**aligned\_hint ~prefix fmt ... hint** align the potential hint with the main error message generated by the format string  **fmt** before printing the two message.

*val did\_you\_mean* :  **?pp:string Format\_doc.printer -\> string list -\> Format\_doc.t option**

**did\_you\_mean ~pp choices** hints that the user may have meant one of the option in  **choices** .

Each choice is printed with the  **pp** function, or  **Style.inline\_code** if **pp** = **None** .

*module Color :* **sig end**

### Color support detection

### Styling handling for terminal output

*module Style :* **sig end**

*module Error\_style :* **sig end**

### Formatted output

*val print\_if* :  **Format.formatter -\>** **bool ref -\> (Format.formatter -\> 'a -\> unit) -\> 'a -\> 'a**

**print\_if ppf flag fmt x** prints  **x** with  **fmt** on  **ppf** if  **b** is true.

*val print\_see\_manual* :  **int list Format\_doc.printer**

See manual section

### Displaying configuration variables

*val show\_config\_and\_exit* :  **unit -\> unit**

Display the values of all compiler configuration variables from module **Config** , then exit the program with code 0.

*val show\_config\_variable\_and\_exit* :  **string -\> unit**

Display the value of the given configuration variable, then exit the program with code 0.

### Handling of build maps

Build maps cause the compiler to normalize file names embedded in object files, thus leading to more reproducible builds.

*val get\_build\_path\_prefix\_map* :  **unit -\> Build\_path\_prefix\_map.map option**

Returns the map encoded in the  **BUILD\_PATH\_PREFIX\_MAP** environment variable.

*val invert\_build\_path\_prefix\_map* :  **string -\> string list**

Returns the potential paths (in priority order) from which the given path can originate from before rewrite using **BUILD\_PATH\_PREFIX\_MAP** environment variable.

*val debug\_prefix\_map\_flags* :  **unit -\> string list**

Returns the list of  **--debug-prefix-map** flags to be passed to the assembler, built from the  **BUILD\_PATH\_PREFIX\_MAP** environment variable.

### Handling of magic numbers

*module Magic\_number :* **sig end**

### Minimal support for Unicode characters in identifiers

Characters allowed in identifiers are, currently:

\-ASCII letters A-Z a-z

\-Latin-1 letters (U+00C0 - U+00FF except U+00D7 and U+00F7)

\-Character sequences which normalize to the above character under NFC

\-digits 0-9, underscore, single quote

*module Utf8\_lexeme :* **sig end**

*module RuntimeID :* **sig end**

### Miscellaneous type aliases

*type filepath* =  **string**

*type modname* =  **string**

*type crcs* =  **(modname \* Digest.BLAKE128.t option) list**

*type alerts* =  **string Stdlib.String.Map.t**
