Module Misc
: sigend
Miscellaneous useful types and functions
Warning: this module is unstable and part of Compiler_libs .
Reportingfatalerrorsvalfatal_error : string->'a
Raise the Fatal_error exception with the given string.
valfatal_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.
exceptionFatal_errorExceptionsandfinalizationvaltry_finally : ?always:(unit->unit)->?exceptionally:(unit->unit)->(unit->'a)->'atry_finallywork~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:
letobjfile=outputprefix^".cmo"inletoc=open_out_binobjfileinMisc.try_finally(fun()->bytecode++Timings.(accumulate_time(Generatesourcefile))(Emitcode.to_fileocmodulenameobjfile);Warnings.check_fatal())~always:(fun()->close_outoc)~exceptionally:(fun_exn->remove_fileobjfile);
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.
valreraise_preserving_backtrace : exn->(unit->unit)->'areraise_preserving_backtraceef is (f (); raise e) except that the current backtrace is preserved, even
if f uses exceptions internally.
Listoperationsvalmap_end : ('a->'b)->'alist->'blist->'blistmap_endflt is mapfl@t , just more efficient.
valrev_map_end : ('a->'b)->'alist->'blist->'blistmap_endflt is mapf(revl)@t , just more efficient.
valmap_left_right : ('a->'b)->'alist->'blist
Like List.map , with guaranteed left-to-right evaluation order
valfor_all2 : ('a->'b->bool)->'alist->'blist->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.
valreplicate_list : 'a->int->'alistreplicate_listelemn is the list with n elements all identical to elem .
vallist_remove : 'a->'alist->'alistlist_removexl returns a copy of l with the first element equal to x removed.
valsplit_last : 'alist->'alist*'a
Return the last element and the other elements of the given list.
Hashtableoperationsvalcreate_hashtable : int->('a*'b)list->('a,'b)Hashtbl.t
Create a hashtable with the given initial size and fills it with the given bindings.
ExtensionstothestandardlibrarymoduleStdlib:sigendOperationsonfilesandfilepathsvalfind_in_path : stringlist->string->string
Search a file in a list of directories.
valfind_in_path_rel : stringlist->string->string
Search a relative file in a list of directories.
valnormalized_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
valfind_in_path_normalized : stringlist->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.
valremove_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.
valexpand_directory : string->string->stringexpand_directoryaltfile eventually expands a + at the beginning of file into alt (an alternate root
directory)
valsplit_path_contents : ?sep:char->string->stringlistsplit_path_contents?seps 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.
valcopy_file : in_channel->out_channel->unitcopy_fileicoc reads the contents of file ic and copies them to oc . It stops when encountering EOF on
ic .
valcopy_file_chunk : in_channel->out_channel->int->unitcopy_file_chunkicocn reads n bytes from ic and copies them to oc . It raises End_of_file when
encountering EOF on ic .
valstring_of_file : in_channel->stringstring_of_fileic reads the contents of file ic and copies them to a string. It stops when encountering
EOF on ic .
valoutput_to_file_via_temporary : ?mode:open_flaglist->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_temporaryfilenamefn 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 .
valprotect_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.
valconcat_null_terminated : stringlist->stringconcat_null_terminated[x1;x2;...xn] is x1^"\000"^x2^"\000"^...^xn^"\000"valsplit_null_terminated : string->stringlistsplit_null_terminateds is similar String.split_on_char'\000' but ignores the trailing separator, if any
valchop_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.
Integeroperationsvallog2 : int->intlog2n returns s such that n=1lsls if n is a power of 2
valalign : int->int->intalignna rounds n upwards to a multiple of a (a power of 2).
valno_overflow_add : int->int->boolno_overflow_addn1n2 returns true if the computation of n1+n2 does not overflow.
valno_overflow_sub : int->int->boolno_overflow_subn1n2 returns true if the computation of n1-n2 does not overflow.
valno_overflow_mul : int->int->boolno_overflow_muln1n2 returns true if the computation of n1*n2 does not overflow.
valno_overflow_lsl : int->int->boolno_overflow_lslnk returns true if the computation of nlslk does not overflow.
valletter_of_int : int->stringmoduleInt_literal_converter:sigendvalfind_first_mono : (int->bool)->intfind_first_monop takes an integer predicate p:int->bool that we assume: 1. is monotonic on natural
numbers: if a<=b then pa implies pb , 2. is satisfied for some natural numbers in range 0;max_int
(this is equivalent to: pmax_int=true ).
find_first_monop 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.
Stringoperationsvalsearch_substring : string->string->int->intsearch_substringpatstrstart 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.
valreplace_substring : before:string->after:string->string->stringreplace_substring~before~afterstr replaces all occurrences of before with after in str and returns the
resulting string.
valrev_split_words : string->stringlistrev_split_wordss splits s in blank-separated words, and returns the list of words in reverse order.
valcut_at : string->char->string*stringString.cut_atsc 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_atscinbefore^String.make1c^after is the identity if s contains c .
Raise Not_found if the character does not appear in the string
Since 4.01
valordinal_suffix : int->stringordinal_suffixn 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.
valnormalise_eol : string->stringnormalise_eols 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)
valdelete_eol_spaces : string->stringdelete_eol_spacess returns a fresh copy of s with any end of line spaces removed. Intended to normalize
the output of the toplevel for tests.
Operationsonreferencestyperef_and_value =
| R :'aref*'a->ref_and_valuevalprotect_refs : ref_and_valuelist->(unit->'a)->'aprotect_refslf 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.
valget_ref : 'alistref->'alistget_reflr returns the content of the list reference lr and reset its content to the empty list.
valset_or_ignore : ('a->'boption)->'boptionref->'a->unitset_or_ignorefoptx sets opt to fx if it returns Some_ , or leaves it unmodified if it returns None .
Operationsontriplesandquadruplesvalfst3 : 'a*'b*'c->'avalsnd3 : 'a*'b*'c->'bvalthd3 : 'a*'b*'c->'cvalfst4 : 'a*'b*'c*'d->'avalsnd4 : 'a*'b*'c*'d->'bvalthd4 : 'a*'b*'c*'d->'cvalfor4 : 'a*'b*'c*'d->'dSpellcheckingand``didyoumean''suggestionsvaledit_distance : string->string->int->intoptionedit_distanceabcutoff 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 Somed , 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.
valspellcheck : stringlist->string->stringlistspellcheckenvname 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.
valdid_you_mean : Format_doc.formatter->(unit->stringlist)->unitdid_you_meanppfget_choices hints that the user may have meant one of the option returned by calling
get_choices . It does nothing if the returned list is empty.
The unit->... thunking is meant to delay any potentially-slow computation (typically computing
edit-distance with many things from the current environment) to when the hint message is to be printed.
You should print an understandable error message before calling did_you_mean , so that users get a clear
notification of the failure even if producing the hint is slow.
moduleColor:sigendColorsupportdetectionStylinghandlingforterminaloutputmoduleStyle:sigendmoduleError_style:sigendFormattedoutputvalprint_if : Format.formatter->boolref->(Format.formatter->'a->unit)->'a->'aprint_ifppfflagfmtx prints x with fmt on ppf if b is true.
valprint_see_manual : intlistFormat_doc.printer
See manual section
Displayingconfigurationvariablesvalshow_config_and_exit : unit->unit
Display the values of all compiler configuration variables from module Config , then exit the program
with code 0.
valshow_config_variable_and_exit : string->unit
Display the value of the given configuration variable, then exit the program with code 0.
Handlingofbuildmaps
Build maps cause the compiler to normalize file names embedded in object files, thus leading to more
reproducible builds.
valget_build_path_prefix_map : unit->Build_path_prefix_map.mapoption
Returns the map encoded in the BUILD_PATH_PREFIX_MAP environment variable.
valdebug_prefix_map_flags : unit->stringlist
Returns the list of --debug-prefix-map flags to be passed to the assembler, built from the
BUILD_PATH_PREFIX_MAP environment variable.
HandlingofmagicnumbersmoduleMagic_number:sigendMinimalsupportforUnicodecharactersinidentifiers
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
moduleUtf8_lexeme:sigendMiscellaneoustypealiasestypefilepath = stringtypemodname = stringtypecrcs = (modname*Digest.toption)listtypealerts = stringStdlib.String.Map.t
OCamldoc 2025-06-12 Misc(3o)