lexer.mll 13.3 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
{

  open Lexing
  open Parser
  open Positions

  (* This wrapper saves the current lexeme start, invokes its argument,
     and restores it. This allows transmitting better positions to the
     parser. *)

  let savestart lexbuf f =
    let startp = lexbuf.lex_start_p in
    let token = f lexbuf in
    lexbuf.lex_start_p <- startp;
    token
  
  (* Updates the line counter, which is used in some error messages. *)

  let update_loc lexbuf =
    let pos = lexbuf.lex_curr_p in
    lexbuf.lex_curr_p <- { pos with
      pos_lnum = pos.pos_lnum + 1;
      pos_bol = pos.pos_cnum;
    }

  (* Extracts a chunk out of the source file. *)    

  let chunk ofs1 ofs2 =
    let contents = Error.get_file_contents() in
    let len = ofs2 - ofs1 in
    String.sub contents ofs1 len

  (* Extracts a chunk out of the source file, delimited by
     one position and extending to the end of the file. *)

  let echunk ofs1 =
    let contents = Error.get_file_contents() in
    let len = String.length contents - ofs1 in
    String.sub contents ofs1 len

  (* Overwrites an old character with a new one at a specified
     offset in a string. *)

  let overwrite content offset c1 c2 =
    assert (content.[offset] = c1);
    content.[offset] <- c2

  (* Creates a stretch. *)

  let mk_stretch parenthesize pos1 pos2 pkeywords = 
    let ofs1 = pos1.pos_cnum
    and ofs2 = pos2.pos_cnum in
    let raw_content = chunk ofs1 ofs2 in
    let content = String.copy raw_content in
    (* Turn our keywords into valid Objective Caml identifiers
       by replacing '$', '(', and ')' with '_'. Bloody. *)
    List.iter (function { value = keyword; position = pos } ->
      let pos = start_of_position pos in
      let ofs = pos.pos_cnum - ofs1 in
      overwrite content ofs '$' '_';
      match keyword with
      | Keyword.Dollar _
      | Keyword.Position (Keyword.Left, _, _)
      | Keyword.PreviousError ->
	  ()
      | Keyword.SyntaxError ->
	  (* $syntaxerror is replaced with
	     (raise _eRR) *)
          let source = "(raise _eRR)" in
          String.blit source 0 content ofs (String.length source)
      | Keyword.Position (subject, where, _) ->
	  let ofslpar =
	    match where with
	    | Keyword.WhereStart ->
		ofs + 9
	    | Keyword.WhereEnd ->
		ofs + 7
	  in
	  overwrite content ofslpar '(' '_';
	  match subject with
	  | Keyword.Left ->
	      assert false
	  | Keyword.RightDollar i ->
	      overwrite content (ofslpar + 1) '$' '_';
	      overwrite content (ofslpar + 2 + String.length (string_of_int i)) ')' '_'
	  | Keyword.RightNamed id ->
	      overwrite content (ofslpar + 1 + String.length id) ')' '_'
    ) pkeywords;
    (* Add whitespace so that the column numbers match those of the source file.
       If requested, add parentheses so that the semantic action can be inserted
       into other code without ambiguity. *)
    let content =
      if parenthesize then
	  (String.make (pos1.pos_cnum - pos1.pos_bol - 1) ' ') ^ "(" ^ content ^ ")"
      else
	(String.make (pos1.pos_cnum - pos1.pos_bol) ' ') ^ content
    in
    {
      Stretch.stretch_filename = Error.get_filename();
      Stretch.stretch_linenum = pos1.pos_lnum;
      Stretch.stretch_linecount = pos2.pos_lnum - pos1.pos_lnum;
      Stretch.stretch_content = content;
      Stretch.stretch_raw_content = raw_content;
      Stretch.stretch_keywords = pkeywords
    } 

  (* Translates the family of position-related keywords to abstract
     syntax. *)

  let mk_keyword lexbuf w f n id =
    let where =
      match w with
      | Some _ ->
	  Keyword.WhereStart
      | None ->
	  Keyword.WhereEnd
    and flavor =
      match f with
      | Some _ ->
	  Keyword.FlavorPosition
      | None ->
	  Keyword.FlavorOffset
    and subject =
      match n, id with
      | Some n, None ->
	  Keyword.RightDollar (int_of_string n)
      | None, Some id ->
	  Keyword.RightNamed id
      | None, None ->
	  Keyword.Left
      | Some _, Some _ ->
          assert false
    in
    let keyword = Keyword.Position (subject, where, flavor) in
    with_cpos lexbuf keyword

  (* Objective Caml's reserved words. *)

  let reserved =
    let table = Hashtbl.create 149 in
    List.iter (fun word -> Hashtbl.add table word ()) [
      "and";
      "as";
      "assert";
      "begin";
      "class";
      "constraint";
      "do";
      "done";
      "downto";
      "else";
      "end";
      "exception";
      "external";
      "false";
      "for";
      "fun";
      "function";
      "functor";
      "if";
      "in";
      "include";
      "inherit";
      "initializer";
      "lazy";
      "let";
      "match";
      "method";
      "module";
      "mutable";
      "new";
      "object";
      "of";
      "open";
      "or";
      "parser";
      "private";
      "rec";
      "sig";
      "struct";
      "then";
      "to";
      "true";
      "try";
      "type";
      "val";
      "virtual";
      "when";
      "while";
      "with";
      "mod";
      "land";
      "lor";
      "lxor";
      "lsl";
      "lsr";
      "asr";
    ];
    table

  (* A short-hand. *)

  let error1 pos msg =
    Error.error (Positions.one pos) msg

}

let newline = ('\010' | '\013' | "\013\010")

let whitespace = [ ' ' '\t' ';' ]

let lowercase = ['a'-'z' '\223'-'\246' '\248'-'\255' '_']

let uppercase = ['A'-'Z' '\192'-'\214' '\216'-'\222']

let identchar = ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '0'-'9'] (* '\'' forbidden *)

let poskeyword = 
  '$'
  (("start" as w) | "end")
  (("pos" as f) | "ofs")
  ( '(' ( '$' (['0'-'9']+ as n) | ((lowercase identchar*) as id)) ')')?

let previouserror =
  "$previouserror"

let syntaxerror =
  "$syntaxerror"

rule main = parse
| "%token"
    { TOKEN }
| "%type"
    { TYPE }
| "%left"
    { LEFT }
| "%right"
    { RIGHT }
| "%nonassoc"
    { NONASSOC }
| "%start"
    { START }
| "%prec"
    { PREC }
| "%public"
    { PUBLIC }
| "%parameter"
    { PARAMETER }
| "%inline"
    { INLINE }
| "%%"
    { let ofs = lexeme_end lexbuf in
      PERCENTPERCENT (lazy (echunk ofs)) }
| ":"
    { COLON }
| ","
    { COMMA }
| "="
    { EQUAL }
| "("
    { LPAREN }
| ")"
    { RPAREN }
| "|"
    { BAR }
| "?"
    { QUESTION }
| "*"
    { STAR }
| "+"
    { PLUS }
| (lowercase identchar *) as id
    { if Hashtbl.mem reserved id then
	Error.errorp
	  (Positions.with_poss (lexeme_start_p lexbuf) (lexeme_end_p lexbuf) ())
	  "this is an Objective Caml reserved word."
      else
	LID (with_pos (cpos lexbuf) id)
    }
| (uppercase identchar *) as id
    { UID (with_pos (cpos lexbuf) id) }
| "//" [^ '\010' '\013']* newline (* skip C++ style comment *)
| newline
    { update_loc lexbuf; main lexbuf }
| whitespace+
    { main lexbuf }
| "/*"
    { comment (lexeme_start_p lexbuf) lexbuf; main lexbuf }
| "(*"
    { ocamlcomment (lexeme_start_p lexbuf) lexbuf; main lexbuf }
| "<"
    { savestart lexbuf (ocamltype (lexeme_end_p lexbuf)) }
| "%{"
    { savestart lexbuf (fun lexbuf ->
        let openingpos = lexeme_end_p lexbuf in
        let closingpos, _ = action true openingpos [] lexbuf in
	(* TEMPORARY if keyword list nonempty, issue an error *)
        HEADER (mk_stretch false openingpos closingpos [])
      ) }
| "{"
    { savestart lexbuf (fun lexbuf ->
        let openingpos = lexeme_end_p lexbuf in
        let closingpos, pkeywords = action false openingpos [] lexbuf in
	let stretch = mk_stretch true openingpos closingpos pkeywords in
        ACTION (Action.from_stretch stretch)
      ) }
(* TEMPORARY comprendre si la diffrence entre header et action est bien
             justifie et si certains choix comme le parenthsage et le
             traitement des keywords ne pourraient pas tre effectus
             plus loin. *)
| eof
    { EOF }
| _
    { error1 (lexeme_start_p lexbuf) "unexpected character(s)." }

(* Skip C style comments. *)

and comment openingpos = parse
| newline
    { update_loc lexbuf; comment openingpos lexbuf }
| "*/"
    { () }
| eof
    { error1 openingpos "unterminated comment." }
| _
    { comment openingpos lexbuf }

(* Collect an O'Caml type delimited by angle brackets. Angle brackets can
329 330
   appear as part of O'Caml function types and variant types, so we must
   recognize them and *not* treat them as a closing bracket. *)
331 332 333

and ocamltype openingpos = parse
| "->"
334
| "[>"
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    { ocamltype openingpos lexbuf }
| '>'
    { OCAMLTYPE (Stretch.Declared (mk_stretch true openingpos (lexeme_start_p lexbuf) [])) }
| "(*"
    { ocamlcomment (lexeme_start_p lexbuf) lexbuf; ocamltype openingpos lexbuf }
| newline
    { update_loc lexbuf; ocamltype openingpos lexbuf }
| eof
    { error1 openingpos "unterminated Objective Caml type." }
| _
    { ocamltype openingpos lexbuf }

(* Collect O'Caml code delimited by curly brackets. Any occurrences of
   the special ``$i'' identifiers are recorded in the accumulating
   parameter [pkeywords]. Nested curly brackets must be properly
   counted. Nested parentheses are also kept track of, so as to better
   report errors when they are not balanced. *)

and action percent openingpos pkeywords = parse
| '{'
    { let _, pkeywords = action false (lexeme_end_p lexbuf) pkeywords lexbuf in
      action percent openingpos pkeywords lexbuf }
| ("}" | "%}") as delimiter
    { match percent, delimiter with
      | true, "%}"
      | false, "}" ->
	  (* This is the delimiter we were instructed to look for. *)
	  lexeme_start_p lexbuf, pkeywords
      | _, _ ->
	  (* This is not it. *)
	  error1 openingpos "unbalanced opening brace."
    }
| '('
    { let _, pkeywords = parentheses (lexeme_end_p lexbuf) pkeywords lexbuf in
      action percent openingpos pkeywords lexbuf }
| '$' (['0'-'9']+ as n)
    { let pkeyword = with_cpos lexbuf (Keyword.Dollar (int_of_string n)) in
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| poskeyword
    { let pkeyword = mk_keyword lexbuf w f n id in
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| previouserror
    { let pkeyword = with_cpos lexbuf Keyword.PreviousError in
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| syntaxerror
    { let pkeyword = with_cpos lexbuf Keyword.SyntaxError in
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| '"'
    { string (lexeme_start_p lexbuf) lexbuf;
      action percent openingpos pkeywords lexbuf }
| "'"
    { char lexbuf;
      action percent openingpos pkeywords lexbuf }
| "(*"
    { ocamlcomment (lexeme_start_p lexbuf) lexbuf;
      action percent openingpos pkeywords lexbuf }
| newline
    { update_loc lexbuf;
      action percent openingpos pkeywords lexbuf }
| ')'
| eof
    { error1 openingpos "unbalanced opening brace." }
| _
    { action percent openingpos pkeywords lexbuf }

and parentheses openingpos pkeywords = parse
| '('
    { let _, pkeywords = parentheses (lexeme_end_p lexbuf) pkeywords lexbuf in
      parentheses openingpos pkeywords lexbuf }
| ')'
    { lexeme_start_p lexbuf, pkeywords }
| '{'
    { let _, pkeywords = action false (lexeme_end_p lexbuf) pkeywords lexbuf in
      parentheses openingpos pkeywords lexbuf }
| '$' (['0'-'9']+ as n)
    { let pkeyword = with_cpos lexbuf (Keyword.Dollar (int_of_string n)) in
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| poskeyword
    { let pkeyword = mk_keyword lexbuf w f n id in
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| previouserror
    { let pkeyword = with_cpos lexbuf Keyword.PreviousError in
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| syntaxerror
    { let pkeyword = with_cpos lexbuf Keyword.SyntaxError in
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| '"'
    { string (lexeme_start_p lexbuf) lexbuf; parentheses openingpos pkeywords lexbuf }
| "'"
    { char lexbuf; parentheses openingpos pkeywords lexbuf }
| "(*"
    { ocamlcomment (lexeme_start_p lexbuf) lexbuf; parentheses openingpos pkeywords lexbuf }
| newline
    { update_loc lexbuf; parentheses openingpos pkeywords lexbuf }
| '}'
| eof
    { error1 openingpos "unbalanced opening parenthesis." }
| _
    { parentheses openingpos pkeywords lexbuf }

(* Skip O'Caml comments. Comments can be nested and can contain
   strings or characters, which must be correctly analyzed. (A string
   could contain begin-of-comment or end-of-comment sequences, which
   must be ignored; a character could contain a begin-of-string
   sequence.) *)

and ocamlcomment openingpos = parse
| "*)"
    { () }
| "(*"
    { ocamlcomment (lexeme_start_p lexbuf) lexbuf; ocamlcomment openingpos lexbuf }
| '"'
    { string (lexeme_start_p lexbuf) lexbuf; ocamlcomment openingpos lexbuf }
| "'"
    { char lexbuf; ocamlcomment openingpos lexbuf }
| newline
    { update_loc lexbuf; ocamlcomment openingpos lexbuf }
| eof
    { error1 openingpos "unterminated Objective Caml comment." }
| _
    { ocamlcomment openingpos lexbuf }

(* Skip O'Caml strings. *)

and string openingpos = parse
| '"' 
   { () }
| '\\' newline
| newline
   { update_loc lexbuf; string openingpos lexbuf }
| '\\' _
   (* Upon finding a backslash, skip the character that follows,
      unless it is a newline. Pretty crude, but should work. *)
   { string openingpos lexbuf }
| eof 
   { error1 openingpos "unterminated Objective Caml string." }
| _
   { string openingpos lexbuf }

(* Skip O'Caml characters. A lone quote character is legal inside
   a comment, so if we don't recognize the matching closing quote,
   we simply abandon. *)

and char = parse
| '\\'? newline "'"
   { update_loc lexbuf }
| [^ '\\' '\''] "'"
| '\\' _ "'"
| '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
| '\\' 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'"
| ""
   { () }