123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301(* 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 defines the shallow abstract syntax for an error specification
file (.lrgrep). It includes types for representing locations, symbols, regular
expressions, semantic actions, and the overall structure of a lexer
definition. *)openUtils(** {1 The shallow abstract syntax} *)(** Kind of quantifier used in regular expressions. *)typequantifier_kind=|Longest(* aka "greedy" *)|Shortest(* aka "lazy" *)typeposition=Lexing.position(** This represents a piece of OCaml code, as appearing in semantic
actions, as well as in the header and trailer. *)typeocaml_code=position*string(** A grammar symbol (a terminal or a non-terminal) *)typesymbol=|Nameofstring(** Symbols are usually simple names, like 'a' or 'X'. *)|Applyofstring*symbollist(** Menhir supports higher-order non-terminals. In this case, a symbol is
the application of the higher-order non-terminal to some arguments.
E.g separated_list(sep, X) is represented as:
[Apply ("separated_list", [Name "sep"; Name "X"])] *)(** A wildcard symbol is either a symbol or '_'. *)typewild_symbol=symboloption(** Symbols used in filter globbing expressions to specify matching criteria. *)typefilter_symbol=|Skip|Findofwild_symbol|Dot(** [regular_desc] describes the different cases of the regular expression
syntax. *)typeregular_desc=|Atomofstringoption*wild_symbol*Usage.mark(** [Atom (capture, sym,_)] represents the base cases ([symbol] and [_]). *)|Alternativeofregular_exprlist(** A disjunction of multiple expressions.
[e1 | e2 | e3] is represented as [Alternative [e1; e2; e3]] *)|Repetitionof{expr:regular_expr;policy:quantifier_kind;}(** [Repetition e] represents [e*] and [e**] *)|Reduceof{capture:stringoption;mark:Usage.mark;expr:regular_expr;policy:quantifier_kind;}(** [Reduce {expr; _}] represents [[expr]] and [[[expr]]]. *)|Concatofregular_exprlist(** [Concat [e1; e2; ..]] is [e1; e2; ...] *)|Filteroffilter(** [Filter f] represents [/foo: bar...] *)(** [regular_expr] adds position information to [regular_desc] for error
reporting purposes. *)andregular_expr={desc:regular_desc;position:position;(** the position where this term ends *)}andfilter={lhs:wild_symboloption;rhs:(filter_symbol*position)list;}(** The semantic action associated to a pattern *)typeclause_action=|Totalofocaml_code(** ... { code }, normal semantic action **)|Partialofocaml_code(** ... partial { ... }, a semantic action that can
return [None] to continue matching *)|Unreachableofposition(** [... { . }] the pattern should never match *)(** A pattern is a combination of a regular expression and an optional list
of lookahead constraints. *)typepattern={expr:regular_expr;(** the pattern *)lookaheads:(symbol*position)list;(** restrict matching to these lookahead terminals, or [] for all terminals *)}(** A clause is a pair of a pattern and an action, representing one rule. *)typeclause={patterns:patternlist;action:clause_action;(** the semantic action *)}typeclause_group=clauselist(** A rule in .lrgrep file is represented by the [rule] type. *)typerule={name:string;(** Name of the rule *)error:bool*position;(** [error] is true if this entry only matches failing stacks.
Syntactically, an error entry has the form:
rule x ... = parse error
| ...
*)startsymbols:(string*position)list;(** The list of entrypoints to support, or [] for all entrypoints. *)args:stringlist;(** The list of OCaml arguments to abstract over,
e.g the [x y] in [rule foo x y = ...] *)clauses:clause_grouplist;(** The list of clauses to match *)}(** An .lrgrep file is an header containing some OCaml code, one or more entries,
and a trailer with some other OCaml code. *)typelexer_definition={header:ocaml_code;rules:rulelist;trailer:ocaml_code;}(** {1 Helper and cmoning functions} *)(** Convert a location to a Cmon record. *)letcmon_position{Lexing.pos_fname;pos_bol;pos_cnum;pos_lnum}=Cmon.(record["filename",stringpos_fname;"line",intpos_lnum;"column",int(pos_cnum-pos_bol);"offset",intpos_cnum;])(** Convert an OCaml code to a Cmon tuple. *)letcmon_ocamlcode(location,code)=Cmon.tuple[cmon_positionlocation;Cmon.stringcode;](** Convert a function and a position to a Cmon pair. *)letcmon_positionedf=Utils.Misc.cmon_pairfcmon_position(** Convert an option to a Cmon value. *)letcmon_optionf=function|None->Cmon.constant"None"|Somex->Cmon.constructor"Some"(fx)(** Convert a symbol to a Cmon value. *)letreccmon_symbol=function|Namesym->Cmon.constructor"Name"(Cmon.stringsym)|Apply(sym,args)->Cmon.construct"Apply"[Cmon.stringsym;Cmon.list(List.mapcmon_symbolargs);](** Convert a capture to a Cmon value. *)letcmon_capturecap=cmon_optionCmon.stringcap(** Convert a wildcard symbol to a Cmon value. *)letcmon_wild_symbolsym=cmon_optioncmon_symbolsym(** Convert a filter symbol to a Cmon value. *)letcmon_filter_symbol=function|Skip->Cmon.constant"Skip"|Dot->Cmon.constant"Dot"|Findsym->cmon_wild_symbolsymletcmon_quantifier_kind=function|Longest->Cmon.constant"Longest"|Shortest->Cmon.constant"Shortest"letcmon_usage_mark_=Cmon.constant"<Usage.mark>"letreccmon_regular_term=function|Atom(cap,sym,mark)->Cmon.construct"Atom"[cmon_capturecap;cmon_wild_symbolsym;cmon_usage_markmark]|Alternativeres->Cmon.constructor"Alternative"(Cmon.list_mapcmon_regular_expressionres)|Concatres->Cmon.constructor"Concat"(Cmon.list_mapcmon_regular_expressionres)|Repetition{policy;expr}->Cmon.crecord"Repetition"["expr",cmon_regular_expressionexpr;"policy",cmon_quantifier_kindpolicy;]|Reduce{capture;mark;policy;expr}->Cmon.crecord"Reduce"["capture",cmon_capturecapture;"mark",cmon_usage_markmark;"expr",cmon_regular_expressionexpr;"policy",cmon_quantifier_kindpolicy;]|Filter{lhs;rhs}->Cmon.crecord"Filter"["lhs",cmon_optioncmon_wild_symbollhs;"rhs",Cmon.list_map(cmon_positionedcmon_filter_symbol)rhs;](** Convert a regular expression to a Cmon value. *)andcmon_regular_expressionre=Cmon.record["desc",cmon_regular_termre.desc;"position",cmon_positionre.position;](** Convert a clause action to a Cmon value. *)letcmon_clause_action=function|Unreachablepos->Cmon.constructor"Unreachable"(cmon_positionpos)|Totalcode->Cmon.constructor"Total"(cmon_ocamlcodecode)|Partialcode->Cmon.constructor"Partial"(cmon_ocamlcodecode)(** Convert a pattern to a Cmon value. *)letcmon_pattern{expr;lookaheads}=Cmon.record["expr",cmon_regular_expressionexpr;"lookaheads",Cmon.list_map(cmon_positionedcmon_symbol)lookaheads;](** Convert a clause to a Cmon value. *)letcmon_clause{patterns;action}=Cmon.crecord"Clause"["patterns",Cmon.list_mapcmon_patternpatterns;"action",cmon_clause_actionaction;](** Convert a rule to a Cmon value. *)letcmon_rule{error;startsymbols;name;args;clauses}=Cmon.record["startsymbols",Cmon.list_map(cmon_positionedCmon.string)startsymbols;"error",cmon_positionedCmon.boolerror;"name",Cmon.stringname;"args",Cmon.list_mapCmon.stringargs;"clauses",Cmon.list_map(Cmon.list_mapcmon_clause)clauses;](** Convert a lexer definition to a Cmon value. *)letcmon_definition{header;rules;trailer}:Cmon.t=Cmon.record["header",cmon_ocamlcodeheader;"rules",Cmon.list(List.mapcmon_rulerules);"trailer",cmon_ocamlcodetrailer;](** The role of a captured value in a regular expression: captures only the
start or end location, captures the value (and its location) *)typecapture_kind=Start_loc|End_loc|Value(** Print position for error or warning messages *)letgnu_position(pos:Lexing.position)=ifpos=Lexing.dummy_posthen"lrgrep"elseifpos.pos_cnum>-1thenPrintf.sprintf"%s:%d.%d"pos.pos_fnamepos.pos_lnum(pos.pos_cnum-pos.pos_bol)elseifpos.pos_lnum>0thenPrintf.sprintf"%s:%d"pos.pos_fnamepos.pos_lnumelsepos.pos_fname(** Report a warning *)letwarn(pos:Lexing.position)fmt=Printf.eprintf"%s: warning: "(gnu_positionpos);Printf.kfprintf(funoc->output_charoc'\n';flushoc)stderrfmt(** Report an error *)leterror(pos:Lexing.position)fmt=Printf.eprintf"%s: error: "(gnu_positionpos);Printf.kfprintf(funoc->output_charoc'\n';flushoc;exit1)stderrfmtletnonfatal_error(pos:Lexing.position)fmt=Printf.eprintf"%s: error: "(gnu_positionpos);Printf.kfprintf(funoc->output_charoc'\n';flushoc)stderrfmt