home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Caml Light 0.61 / Source / src / lib / genlex.mli < prev    next >
Encoding:
Text File  |  1993-09-24  |  2.2 KB  |  52 lines  |  [TEXT/MPS ]

  1. (* A generic lexical analyzer *)
  2.  
  3. (* This module implements a simple ``standard'' lexical analyzer, presented
  4.    as a function from character streams to token streams. It implements
  5.    roughly the lexical conventions of Caml, but is parameterized by the
  6.    set of keywords of your language. *)
  7.  
  8. #open "stream";;
  9.  
  10. type token =
  11.     Kwd of string
  12.   | Ident of string
  13.   | Int of int
  14.   | Float of float
  15.   | String of string
  16.   | Char of char;;
  17.         (* The type of tokens. The lexical classes are: [Int] and [Float]
  18.            for integer and floating-point numbers; [String] for
  19.            string literals, enclosed in double quotes; [Char] for
  20.            character literals, enclosed in backquotes; [Ident] for
  21.            identifiers (either sequences of letters, digits, underscores
  22.            and quotes, or sequences of ``operator characters'' such as
  23.            [+], [*], etc); and [Kwd] for keywords (either identifiers or
  24.            single ``special characters'' such as [(], [}], etc). *)
  25.            
  26. value make_lexer: string list -> (char stream -> token stream);;
  27.         (* Construct the lexer function. The first argument is the list of
  28.            keywords. An identifier [s] is returned as [Kwd s] if [s]
  29.            belongs to this list, and as [Ident s] otherwise.
  30.            A special character [s] is returned as [Kwd s] if [s]
  31.            belongs to this list, and cause a lexical error (exception
  32.            [Parse_error]) otherwise. Blanks and newlines are skipped.
  33.            Comments delimited by [(*] and [*)] are skipped as well,
  34.            and can be nested.
  35.  
  36.            Example: a lexer suitable for a desk calculator is obtained by
  37.            [
  38.            let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"]
  39.            ]
  40.            The associated parser would be a function from [token stream]
  41.            to, for instance, [int], and would have rules such as:
  42.            [
  43.            let parse_expr = function
  44.                   [< 'Int n >] -> n
  45.                 | [< 'Kwd "("; parse_expr n; 'Kwd ")" >] -> n
  46.                 | [< parse_expr n1; (parse_end n1) n2 >] -> n2
  47.            and parse_end n1 = function
  48.                   [< 'Kwd "+"; parse_expr n2 >] -> n1+n2
  49.                 | ...
  50.            ]
  51. *)
  52.