codePieces.ml 6.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
(* This module defines many internal naming conventions for use by the
   two code generators, [CodeBackend] and [TableBackend]. It also offers
   a few code generation facilities. *)

open IL
open CodeBits
open Grammar

(* ------------------------------------------------------------------------ *)

(* Naming conventions. *)

(* The type variable associated with a nonterminal [nt]. *)

let ntvar nt =
  Infer.ntvar (Nonterminal.print true nt)

(* The variable that holds the environment. This is a parameter to all
   functions. We do not make it a global variable because we wish to
   preserve re-entrancy. *)

let env =
   prefix "env"

(* A variable used to hold a semantic value. *)

let semv =
  "_v"

(* A variable used to hold a stack. *)

let stack =
  prefix "stack"

(* A variable used to hold a state. *)

let state =
  prefix "s"

(* A variable used to hold a token. *)

let token =
  "_tok"

(* Variables used to hold start and end positions. Do not change these
   names! They are chosen to coincide with the $startpos and $endpos
   keywords, which the lexer rewrites to _startpos and _endpos, so
   that binding these variables before executing a semantic action is
   meaningful. *)

51 52 53 54 55
(* These names should agree with the printing function [Keyword.posvar]. *)

let beforeendp =
  "_endpos__0_"

56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
let startp =
  "_startpos"

let endp =
  "_endpos"

(* ------------------------------------------------------------------------ *)

(* Types for semantic values. *)

(* [semvtypent nt] is the type of the semantic value associated
   with nonterminal [nt]. *)

let semvtypent nt =
  match Nonterminal.ocamltype nt with
  | None ->

POTTIER Francois's avatar
Typo.  
POTTIER Francois committed
73
      (* [nt] has unknown type. If we have run [Infer], then this
74 75
         can't happen. However, running type inference is only an
         option, so we still have to deal with that case. *)
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

      TypVar (ntvar nt)

  | Some ocamltype ->

      (* [nt] has known type. *)

      TypTextual ocamltype

(* [semvtypetok tok] is the type of the semantic value associated with
   token [tok]. There is no such type if the token does not have a
   semantic value. *)

let semvtypetok tok =
  match Terminal.ocamltype tok with
  | None ->

      (* Token has unit type and is omitted in stack cell. *)

      []

  | Some ocamltype ->

      (* Token has known type. *)

      [ TypTextual ocamltype ]

(* [semvtype symbol] is the type of the semantic value associated with
   [symbol]. *)

let semvtype = function
  | Symbol.T tok ->
      semvtypetok tok
  | Symbol.N nt ->
      [ semvtypent nt ]

(* [symvalt] returns the empty list if the symbol at hand carries no
   semantic value and the singleton list [[f t]] if it carries a
   semantic value of type [t]. *)

let symvalt symbol f =
  match semvtype symbol with
  | [] ->
      []
  | [ t ] ->
      [ f t ]
  | _ ->
      assert false

(* [symval symbol x] returns either the empty list or the singleton
   list [[x]], depending on whether [symbol] carries a semantic
   value. *)

let symval symbol x =
  match semvtype symbol with
  | [] ->
      []
133
  | [ _t ] ->
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
      [ x ]
  | _ ->
      assert false

(* [tokval] is a version of [symval], specialized for terminal symbols. *)

let tokval tok x =
  symval (Symbol.T tok) x

(* ------------------------------------------------------------------------ *)

(* Patterns for tokens. *)

(* [tokpat tok] is a pattern that matches the token [tok], without binding
   its semantic value. *)

let tokpat tok =
151
  PData (TokenType.tokendata (Terminal.print tok), tokval tok PWildcard)
152 153 154 155 156

(* [tokpatv tok] is a pattern that matches the token [tok], and binds
   its semantic value, if it has one, to the variable [semv]. *)

let tokpatv tok =
157
  PData (TokenType.tokendata (Terminal.print tok), tokval tok (PVar semv))
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

(* [tokspat toks] is a pattern that matches any token in the set [toks],
   without binding its semantic value. *)

let tokspat toks =
  POr (
    TerminalSet.fold (fun tok pats ->
      tokpat tok :: pats
    ) toks []
  )

(* [destructuretokendef name codomain bindsemv branch] generates the
   definition of a function that destructures tokens. [name] is the
   name of the function that is generated. [codomain] is its return
   type. [bindsemv] tells whether the variable [semv] should be
   bound. [branch] is applied to each (non-pseudo) terminal and must
   produce code for each branch. *)

let destructuretokendef name codomain bindsemv branch = {
  valpublic = false;
  valpat = PVar name;
  valval =
    EAnnot (
      EFun ([ PVar token ],
182 183 184 185 186 187 188 189 190
        EMatch (EVar token,
          Terminal.fold (fun tok branches ->
            if Terminal.pseudo tok then
              branches
            else
              { branchpat = (if bindsemv then tokpatv else tokpat) tok;
                branchbody = branch tok } :: branches
          ) []
        )
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
      ),
      type2scheme (arrow TokenType.ttoken codomain)
    )
}

(* ------------------------------------------------------------------------ *)

(* A global variable holds the exception [Error]. *)

(* We preallocate the [Error] exception and store it into a global
   variable. This allows saving code at the sites where the exception
   is raised. Don't change the conventional name [_eRR], it is shared
   with the lexer, which replaces occurrences of the [$syntaxerror]
   keyword with [(raise _eRR)]. *)

let parse_error =
  "_eRR"

let errorval =
  EVar parse_error

212 213 214
let basics =
  "Basics"

215 216 217
let excvaldef = {
  valpublic = false;
  valpat = PVar parse_error;
218 219 220
  valval = EData (basics ^ "." ^ Interface.excname, [])
    (* 2016/06/23 We now use the qualified name [Basics.Error], instead of
       just [Error], so as to avoid OCaml's warning 41. *)
POTTIER Francois's avatar
POTTIER Francois committed
221
}
222

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
(* ------------------------------------------------------------------------ *)

(* Define the internal sub-module [Basics], which contains the definitions
   of the exception [Error] and of the type [token]. Then, include this
   sub-module. This is used both in the code and table back-ends. *)

let mbasics grammar = [

  SIModuleDef (basics, MStruct (
    SIExcDefs [ Interface.excdef ] ::
    interface_to_structure (
      TokenType.tokentypedef grammar
    )
  ));

  SIInclude (MVar basics);

  SIValDefs (false, [ excvaldef ]);

]