123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778(* MIT License
Copyright (c) 2025 Frédéric Bour
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*)(** This module provides a simple framework for outputting text with line
tracking and location printing, useful for compilers and interpreters that
need to generate code or output messages with precise location information. *)typet={filename:string;(* The name of the file being processed *)mutableline:int;(* Current line number in the output *)output:string->unit;(* Function to output a string *)mutablereloc:bool;(* Flag indicating if relocation info should be printed next *)mutablelast_is_nl:bool;(* Flag indicating if the last output character was a newline *)}(* Output a string, updating line count and newline status *)letoutputt=function|""->()|str->letnl=ref0inletlast=String.lengthstr-1infori=0tolastdoifstr.[i]='\n'thenincrnl;done;t.line<-t.line+!nl;t.last_is_nl<-str.[last]='\n';t.outputstr(* Create a new code printer *)letcreate~filename?(line=1)output={filename;line;output;reloc=false;last_is_nl=true}(* Print relocation information for a given file and line *)letprint_loc_dirtfilenameline=outputt(Printf.sprintf"# %d %S\n"(line+1)filename)(* Print relocation information for a given location *)letprint_loct(pos:Lexing.position)=print_loc_dirtpos.pos_fname(pos.pos_lnum-1);outputt(String.make(pos.pos_cnum-pos.pos_bol)' ')(* Print a message, optionally with relocation information *)letprint?loctmsg=matchlocwith|None->ift.relocthen(ifnott.last_is_nlthenoutputt"\n";print_loc_dirtt.filenamet.line;t.reloc<-false;);outputtmsg|Someloc->ifnott.last_is_nlthenoutputt"\n";print_loctloc;t.reloc<-true;outputtmsg(* Print a formatted message, optionally with relocation information *)letfmt?loctfmt=Printf.ksprintf(print?loct)fmt