lexer.mll 15.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{

  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
16

17
18
19
20
21
22
23
24
25
  (* 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;
    }

26
  (* Extracts a chunk out of the source file. *)
27
28
29
30
31
32
33

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

  (* Overwrites an old character with a new one at a specified
34
     offset in a [bytes] buffer. *)
35
36

  let overwrite content offset c1 c2 =
37
38
    assert (Bytes.get content offset = c1);
    Bytes.set content offset c2
39

40
41
42
  (* Check that only allowed indices are used in semantic actions. *)
  let check_producers_indices allowed_producers pkeywords =
    List.iter (function
43
    | { value = Keyword.PDollar idx; position } ->
44
	if idx - 1 >= Array.length allowed_producers then
45
46
	  Error.error [position]
	    "$%d refers to a nonexistent symbol." idx
47
	else begin match allowed_producers.(idx - 1) with
48
49
50
51
52
53
54
55
	| None ->
	    ()
	| Some x ->
	    Error.error [position]
	      "please do not say: $%d. Instead, say: %s." idx x
	end
    | _ ->
        ()
56
57
    ) pkeywords

58
59
60
  (* In-place transformation of keywords. We turn our keywords into
     valid OCaml identifiers by replacing '$', '(', and ')' with '_'.
     Bloody. *)
61

62
  let transform_keywords ofs1 (pkeywords : Keyword.parsed_keyword located list) (content : bytes) =
63
64
65
66
67
    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
68
69
      | Keyword.PDollar _
      | Keyword.PPosition (Keyword.PLeft, _, _) ->
70
	  ()
71
      | Keyword.PSyntaxError ->
72
73
74
	  (* $syntaxerror is replaced with
	     (raise _eRR) *)
          let source = "(raise _eRR)" in
75
          Bytes.blit_string source 0 content ofs (String.length source)
76
      | Keyword.PPosition (subject, where, _) ->
77
78
79
80
81
82
83
84
85
	  let ofslpar =
	    match where with
	    | Keyword.WhereStart ->
		ofs + 9
	    | Keyword.WhereEnd ->
		ofs + 7
	  in
	  overwrite content ofslpar '(' '_';
	  match subject with
86
	  | Keyword.PLeft ->
87
	      assert false
88
	  | Keyword.PRightDollar i ->
89
90
	      overwrite content (ofslpar + 1) '$' '_';
	      overwrite content (ofslpar + 2 + String.length (string_of_int i)) ')' '_'
91
	  | Keyword.PRightNamed id ->
92
	      overwrite content (ofslpar + 1 + String.length id) ')' '_'
93
94
95
96
97
98
99
100
101
    ) pkeywords

  (* In an OCaml header, there should be no keywords. This is just a sanity check. *)

  let no_keywords pkeywords =
    match pkeywords with
    | [] ->
        ()
    | { value = _; position = pos } :: _ ->
102
        Error.error [pos] "a Menhir keyword cannot be used in an OCaml header."
103
104
105
106
107
108
109
110

  (* Creates a stretch. *)

  let mk_stretch pos1 pos2 parenthesize pkeywords = 
    (* Read the specified chunk of the file. *)
    let ofs1 = pos1.pos_cnum
    and ofs2 = pos2.pos_cnum in
    let raw_content : string = chunk ofs1 ofs2 in
111
112
113
114
115
116
117
118
119
120
121
    (* Transform the keywords, if there are any. (This explicit test
       allows saving one string copy and keeping just one live copy.) *)
    let content : string =
      match pkeywords with
      | [] ->
          raw_content
      | _ :: _ ->
        let content : bytes = Bytes.of_string raw_content in
        transform_keywords ofs1 pkeywords content;
        Bytes.unsafe_to_string content
    in
122
123
124
125
126
127
128
129
130
    (* 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
    (* After parsing, every occurrence [$i] is replaced by [_i] in
       semantic actions. *)
    let rewritten_pkeywords = Keyword.(
      let rewrite_index i =
	"_" ^ string_of_int i
      in
      let rewrite_subject = function
	| PLeft -> Left
	| PRightDollar i -> RightNamed (rewrite_index i)
	| PRightNamed n -> RightNamed n
      in
      Misc.map_opt (fun pk ->
	let position = Positions.position pk in
	match Positions.value pk with
        | PDollar _ -> None
	| PPosition (s, w, f) -> Some (Positions.with_pos position (Position (rewrite_subject s, w, f)))
	| PSyntaxError -> Some (Positions.with_pos position SyntaxError)
      ) pkeywords
    ) in
150
151
152
153
154
155
    {
      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;
156
      Stretch.stretch_keywords = rewritten_pkeywords
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    } 

  (* 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 ->
178
	  Keyword.PRightDollar (int_of_string n)
179
      | None, Some id ->
180
	  Keyword.PRightNamed id
181
      | None, None ->
182
	  Keyword.PLeft
183
184
185
      | Some _, Some _ ->
          assert false
    in
186
    let keyword = Keyword.PPosition (subject, where, flavor) in
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
    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

253
  (* Short-hands. *)
254

255
256
  let error1 pos =
    Error.error (Positions.one pos)
257

258
259
  let error2 lexbuf =
    Error.error (Positions.two lexbuf.lex_start_p lexbuf.lex_curr_p)
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
}

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 }
306
307
| "%on_error_reduce"
    { ON_ERROR_REDUCE }
308
| "%%"
309
    { (* The token [PERCENTPERCENT] carries a stretch that contains
310
         everything that follows %% in the input file. This string
311
312
313
314
315
316
317
318
319
         must be created lazily. The parser decides (based on the
         context) whether this stretch is needed. If it is indeed
         needed, then constructing this stretch drives the lexer
         to the end of the file. *)
      PERCENTPERCENT (lazy (
        let openingpos = lexeme_end_p lexbuf in
        let closingpos = finish lexbuf in
        mk_stretch openingpos closingpos false []
      )) }
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
| ":"
    { COLON }
| ","
    { COMMA }
| "="
    { EQUAL }
| "("
    { LPAREN }
| ")"
    { RPAREN }
| "|"
    { BAR }
| "?"
    { QUESTION }
| "*"
    { STAR }
| "+"
    { PLUS }
| (lowercase identchar *) as id
    { if Hashtbl.mem reserved id then
340
        error2 lexbuf "this is an Objective Caml reserved word."
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
      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
360
        let closingpos, pkeywords = action true openingpos [] lexbuf in
361
362
        no_keywords pkeywords;
        HEADER (mk_stretch openingpos closingpos false [])
363
364
365
366
367
      ) }
| "{"
    { savestart lexbuf (fun lexbuf ->
        let openingpos = lexeme_end_p lexbuf in
        let closingpos, pkeywords = action false openingpos [] lexbuf in
368
369
370
371
372
373
        ACTION (
	  fun allowed_producers_indices ->
	  let stretch = mk_stretch openingpos closingpos true pkeywords in
	  check_producers_indices allowed_producers_indices pkeywords;
	  Action.from_stretch stretch
	)
374
375
376
377
      ) }
| eof
    { EOF }
| _
378
    { error2 lexbuf "unexpected character(s)." }
379
380
381
382
383
384
385
386
387
388
389
390
391
392

(* 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
393
394
   appear as part of O'Caml function types and variant types, so we must
   recognize them and *not* treat them as a closing bracket. *)
395
396
397

and ocamltype openingpos = parse
| "->"
398
| "[>"
399
400
    { ocamltype openingpos lexbuf }
| '>'
401
    { OCAMLTYPE (Stretch.Declared (mk_stretch openingpos (lexeme_start_p lexbuf) true [])) }
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
| "(*"
    { 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)
435
    { let pkeyword = with_cpos lexbuf (Keyword.PDollar (int_of_string n)) in
436
437
438
439
440
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| poskeyword
    { let pkeyword = mk_keyword lexbuf w f n id in
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| previouserror
441
    { error2 lexbuf "$previouserror is no longer supported." }
442
| syntaxerror
443
    { let pkeyword = with_cpos lexbuf Keyword.PSyntaxError in
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
      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)
473
    { let pkeyword = with_cpos lexbuf (Keyword.PDollar (int_of_string n)) in
474
475
476
477
478
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| poskeyword
    { let pkeyword = mk_keyword lexbuf w f n id in
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| previouserror
479
    { error2 lexbuf "$previouserror is no longer supported." }
480
| syntaxerror
481
    { let pkeyword = with_cpos lexbuf Keyword.PSyntaxError in
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
      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'] "'"
| ""
   { () } 

550
551
552
553
554
555
556
557
558
559
560
561
(* Read until the end of the file. This is used after finding a %%
   that marks the end of the grammar specification. We update the
   current position as we go. This allows us to build a stretch
   for the trailer. *)

and finish = parse
| newline
    { update_loc lexbuf; finish lexbuf }
| eof
    { lexeme_start_p lexbuf }
| _
    { finish lexbuf }