Location(3)
Location(3) β OCaml library π¦
okay so bestie, this is Location(3) from the OCaml library β it's all about source code locations, aka ranges of positions, used in parsetree. We're in part 1 and this page is long, so buckle up. β¨
πΈ NAME πΈ
Location β Source code locations (ranges of positions), used in parsetree.
π§ Module π§
Module Location
π Documentation π
Module Location
: sig end
Source code locations (ranges of positions), used in parsetree.
Warning: this module is unstable and part of Compiler_libs .
type t = Warnings.loc = {
loc_start : Lexing.position ;
loc_end : Lexing.position ;
loc_ghost : bool ;
}
So t is literally 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 time: in let f x = x, we have:
-astructure item at location"let f x = x"-apattern"f"at location"f"-anexpression"fun x -> x"at location"x = x"withloc_ghost=true-apattern"x"at location"x"-anexpression"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 Lexing.position 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.
val none : tβ An arbitrary value of typet; describes an empty ghost range.val is_none : t -> boolβ True forLocation.none, false any other location.val in_file : string -> tβ Return an empty ghost range located in a given file.val init : Lexing.lexbuf -> string -> unitβ 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 thelexbuf.val symbol_rloc : unit -> tval symbol_gloc : unit -> tval rhs_loc : int -> tβrhs_loc nreturns the location of the symbol at positionn, starting at 1, in the current parser rule.val rhs_interval : int -> int -> tval get_pos_info : Lexing.position -> string * int * intβ file, line, char
type 'a loc = {
txt : 'a ;
loc : t ;
}
val mknoloc : 'a -> 'a locval mkloc : 'a -> t -> 'a locval map : ('a -> 'b) -> 'a loc -> 'b loc
π Input info π
val input_name : string refval input_lexbuf : Lexing.lexbuf option refval input_phrase_buffer : Buffer.t option ref
π Toplevel-specific functions π
val echo_eof : unit -> unitval reset : unit -> unit
π¦ Rewriting path π¦
val rewrite_absolute_path : string -> stringβrewrite_absolute_path pathrewritespathto honor theBUILD_PATH_PREFIX_MAPvariable if it is set. It does not check whetherpathis absolute or not. The result is as follows:-IfBUILD_PATH_PREFIX_MAPis not set, just returnpath.-otherwise, rewrite using the mapping (and if there are no matching prefixes that will just returnpath).
See the BUILD_PATH_PREFIX_MAP spec.
val rewrite_find_first_existing : string -> string optionβrewrite_find_first_existing pathuses aBUILD_PATH_PREFIX_MAPmapping 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_MAPis not set andpathdoes not exists, or-nosource prefixes ofpathin the mapping were found,
Some target, meanstargetexists and either-BUILD_PATH_PREFIX_MAPis not set andtarget = path, ortargetis the first file (in priority order) thatpathmapped to that exists in the file system.
-Not_foundraised, means some source prefixes in the map were found that matchedpath, 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.
val rewrite_find_all_existing_dirs : string -> string listβrewrite_find_all_existing_dirs diraccumulates a list of existing directories,dirs, that are the result of mapping a potentially abstract directory,dir, over all the mapping pairs in theBUILD_PATH_PREFIX_MAPenvironment variable, if any. The listdirswill be in priority order (head as highest priority).
The possible results are:
[], means eitherBUILD_PATH_PREFIX_MAPis not set anddiris not an existing directory, or-ifset, then there were no matching prefixes ofdir.
Some dirs, meansdirsare the directories found. EitherBUILD_PATH_PREFIX_MAPis not set anddirs = [dir], or-itwas set anddirsare the mapped existing directories.
-Not_foundraised, means some source prefixes in the map were found that matcheddir, 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.
val absolute_path : string -> stringβabsolute_path pathfirst makes an absolute path,sfrompath, prepending the current working directory ifpathwas relative. Thensis rewritten usingrewrite_absolute_path. Finally the result is normalized by eliminating instances of'.'or'..'.
π«Ά Printing locations π«Ά
val show_filename : string -> stringβ In-absnamemode, return the absolute path for this filename. Otherwise, returns the filename unchanged.val print_filename : Format.formatter -> string -> unitval print_loc : Format.formatter -> t -> unitval print_locs : Format.formatter -> t list -> unitval separate_new_message : Format.formatter -> unitmodule Doc : sig end
π Toplevel-specific location highlighting π
val highlight_terminfo : Lexing.lexbuf -> Format.formatter -> t list -> unit
π₯ Reporting errors and warnings π₯
π The type of reports and report printers π
type msg = Format_doc.t loc
val msg : ?loc:t -> ('a, Format_doc.formatter, unit, msg) format4 -> 'a
type report_kind =
| Report_error
| Report_warning of string
| Report_warning_as_error of string
| Report_alert of string
| Report_alert_as_error of string
type report = {
kind : report_kind ;
main : msg ;
sub : msg list ;
footnote : Format_doc.t option ;
}
type report_printer = {
pp : report_printer -> Format.formatter -> report -> unit ;
pp_report_kind : report_printer -> report -> Format.formatter -> report_kind -> unit ;
pp_main_loc : report_printer -> report -> Format.formatter -> t -> unit ;
pp_main_txt : report_printer -> report -> Format.formatter -> Format_doc.t -> unit ;
pp_submsgs : report_printer -> report -> Format.formatter -> msg list -> unit ;
pp_submsg : report_printer -> report -> Format.formatter -> msg -> unit ;
pp_submsg_loc : report_printer -> report -> Format.formatter -> t -> unit ;
pp_submsg_txt : report_printer -> report -> Format.formatter -> Format_doc.t -> unit ;
}
A printer for report s, defined using open-recursion. The goal is to make it easy to define new printers by reusing code from existing ones.
π Report printers used in the compiler π
val batch_mode_printer : report_printerval terminfo_toplevel_printer : Lexing.lexbuf -> report_printerval best_toplevel_printer : unit -> report_printerβ Detects the terminal capabilities and selects an adequate printer.
π Printing a report π
val print_report : Format.formatter -> report -> unitβ Display an error or warning report.val report_printer : (unit -> report_printer) refβ Hook for redefining the printer of reports.
The hook is a unit -> report_printer and not simply a report_printer : this is useful so that it can detect the type of the output (a file, a terminal, ...) and select a printer accordingly.
val default_report_printer : unit -> report_printerβ Original report printer for use in hooks.
π Reporting warnings π
π Converting a Warnings.t into a report π
val report_warning : t -> Warnings.t -> report optionβreport_warning loc wproduces a report for the given warningw, orNoneif the warning is not to be printed.val warning_reporter : (t -> Warnings.t -> report option) refβ Hook for intercepting warnings.val default_warning_reporter : t -> Warnings.t -> report optionβ Original warning reporter for use in hooks.
πΈ Printing warnings πΈ
val formatter_for_warnings : Format.formatter refval print_warning : t -> Format.formatter -> Warnings.t -> unitβ Prints a warning. This is simply the composition ofreport_warningandprint_report.val prerr_warning : t -> Warnings.t -> unitβ Same asprint_warning, but uses!formatter_for_warningsas output formatter.
π Reporting alerts π
π§ Converting an Alert.t into a report π§
val report_alert : t -> Warnings.alert -> report optionβreport_alert loc wproduces a report for the given alertw, orNoneif the alert is not to be printed.val alert_reporter : (t -> Warnings.alert -> report option) refβ Hook for intercepting alerts.val default_alert_reporter : t -> Warnings.alert -> report optionβ Original alert reporter for use in hooks.
π Printing alerts π
val print_alert : t -> Format.formatter -> Warnings.alert -> unitβ Prints an alert. This is simply the composition ofreport_alertandprint_report.val prerr_alert : t -> Warnings.alert -> unitβ Same asprint_alert, but uses!formatter_for_warningsas output formatter.val deprecated : ?def:t -> ?use:t -> t -> string -> unitβ Prints a deprecation alert.val alert : ?def:t -> ?use:t -> kind:string -> t -> string -> unitβ Prints an arbitrary alert.val auto_include_alert : string -> unitβ Prints an alert that-I +libhas been automatically added to the load path.val deprecated_script_alert : string -> unitβdeprecated_script_alert commandprints an alert that commandfoohas been deprecated in favour of command./foo.
π Reporting errors π
type error = report
An error is a report which report_kind must be Report_error .
type delayed_msg = unit -> Format_doc.t option
val error : ?loc:t -> ?sub:msg list -> ?footnote:delayed_msg -> string -> error
val errorf : ?loc:t -> ?sub:msg list -> ?footnote:delayed_msg -> ('a, Format_doc.formatter, unit, error) format4 -> 'a
val aligned_error_hint : ?loc:t -> ?sub:msg list ->
?footnote:delayed_msg -> ('a, Format_doc.formatter, unit, Format_doc.t
option -> error) format4 -> 'a
Okay so aligned_error_hint ?loc ?sub ?footnote fmt ... is the aligned-hint girlie β¨ β the potential aligned_hint message gets aligned with the main error message before itβs added to the list of submessages. Thatβs the whole job. Slay.
val error_of_printer : ?loc:t -> ?sub:msg list -> ?footnote:delayed_msg
-> (Format_doc.formatter -> 'a -> unit) -> 'a -> error
Signature only, no extra lore in the original β but look at that ?loc, ?sub, ?footnote trio, okay? π
val error_of_printer_file : (Format_doc.formatter -> 'a -> unit) -> 'a
-> error
Also signature-only, bestie. Short and iconic.
π Automatically reporting errors for raised exceptions π
val register_error_of_exn : (exn -> error option) -> unit
Each compiler module which defines a custom type of exception which can surface as a user-visible error should register a "printer" for this exception using register_error_of_exn. The result of the printer is an error value containing a location, a message, and optionally sub-messages (each of them being located as well).
val error_of_exn : exn -> [ `Already_displayed | `Ok of error ] option
exception Error of error
Raising Error e signals an error e; the exception will be caught and the error will be printed. Periodt. π₯
exception Already_displayed_error
Raising Already_displayed_error signals an error which has already been printed. The exception will be caught, but nothing will be printed. So likeβ¦ the message already had its moment, okay? π
val raise_errorf : ?loc:t -> ?sub:msg list -> ?footnote:delayed_msg ->
('a, Format_doc.formatter, unit, 'b) format4 -> 'a
val report_exception : Format.formatter -> exn -> unit
Reraise the exception if it is unknown. No cap. π«Ά
Brought to you by OCamldoc, dated 2026-06-22, chillinβ in Location(3) β mwah π
π¦ where this page comes from
- arch rolling: ocaml 5.5.0-1 Β· LGPL2.1 AND custom: QPL-1.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms