Genlex(3)

πŸ’– NAME πŸ’–

Genlex(3) from the OCaml library is literally your generic lexical analyzer bestie β€” the whole vibe is A generic lexical analyzer. Periodt. πŸ’…


🧚 Module 🧚

Module Genlex


πŸ“š Documentation πŸ“š

Module Genlex : sig end

Okay so this module is a generic lexical analyzer β€” like, a simple β€œstandard” one, presented as a function from character streams to token streams. It implements roughly the lexical conventions of OCaml, but it’s parameterized by the set of keywords of your language. Slay. ✨

Example time, bestie: a lexer suitable for a desk calculator is obtained by

let lexer = make_lexer ["+"; "-"; "*"; "/"; "let"; "="; "("; ")"]

The associated parser would be a function from token stream to, for instance, int, and would have rules such as:

let rec parse_expr = parser
  | [< n1 = parse_atom; n2 = parse_remainder n1 >] -> n2
and parse_atom = parser
  | [< 'Int n >] -> n
  | [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n
and parse_remainder n1 = parser
  | [< 'Kwd "+"; n2 = parse_expr >] -> n1 + n2
  | [< >] -> n1
🫢 Heads up, bestie: one should notice that the use of the parser keyword and associated notation for streams are only available through camlp4 extensions. This means that one has to preprocess its sources e. g. by using the "-pp" command-line switch of the compilers. Iykyk. 😭

πŸŽ€ The token type πŸŽ€

type token =
 | Kwd of string
 | Ident of string
 | Int of int
 | Float of float
 | String of string
 | Char of char

That’s the type of tokens. The lexical classes are:

  • Int and Float β€” for integer and floating-point numbers.
  • String β€” for string literals, enclosed in double quotes.
  • Char β€” for character literals, enclosed in single quotes.
  • Ident β€” for identifiers (either sequences of letters, digits, underscores and quotes, or sequences of β€œoperator characters” such as +, *, etc).
  • Kwd β€” for keywords (either identifiers or single β€œspecial characters” such as (, }, etc).

πŸ’… make_lexer πŸ’…

val make_lexer : string list -> char Stream.t -> token Stream.t

Construct the lexer function. The first argument is the list of keywords. An identifier s is returned as Kwd s if s belongs to this list, and as Ident s otherwise. A special character s is returned as Kwd s if s belongs to this list, and cause a lexical error (exception Stream.Error with the offending lexeme as its parameter) otherwise.

Blanks and newlines are skipped. Comments delimited by (* and *) are skipped as well, and can be nested. A Stream.Failure exception is raised if end of stream is unexpectedly reached. No cap. πŸ’€


mwah πŸ’‹ β€” this page’s footer says OCamldoc, dated 2026-09-24, and it’s the Genlex(3) manual page. Byeee 🫢

πŸ“¦ where this page comes from
  • alpine 3.24: ocaml-doc 4.14.4-r0 Β· LGPL-2.1-or-later WITH OCaml-LGPL-linking-exception
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms