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
  (* Extracts a chunk out of the source file. *)
18
19
20
21
22
23
24

  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
25
     offset in a [bytes] buffer. *)
26
27

  let overwrite content offset c1 c2 =
28
29
    assert (Bytes.get content offset = c1);
    Bytes.set content offset c2
30

31
  (* Check that only allowed indices are used in semantic actions. *)
POTTIER Francois's avatar
POTTIER Francois committed
32
  let check_producers_indices (producers : string option array) pkeywords =
33
34
35
36
37
38
39
    List.iter (fun pkeyword ->
      match Positions.value pkeyword with
      | Keyword.PPosition (Keyword.PRightDollar 0, Keyword.WhereEnd, _) ->
          (* As a special case, [$endpos($0)] is allowed. *)
          ()
      | Keyword.PDollar idx
      | Keyword.PPosition (Keyword.PRightDollar idx, _, _) ->
POTTIER Francois's avatar
POTTIER Francois committed
40
  	  if not (0 <= idx - 1 && idx - 1 < Array.length producers) then
41
42
43
	    Error.error [ Positions.position pkeyword ]
	      "$%d refers to a nonexistent symbol." idx
	  else
POTTIER Francois's avatar
POTTIER Francois committed
44
            producers.(idx - 1) |> Option.iter (fun x ->
45
46
47
48
49
	      Error.error [ Positions.position pkeyword ]
	        "please do not say: $%d. Instead, say: %s." idx x
            )
      | _ ->
         ()
50
51
    ) pkeywords

52
53
54
  (* In-place transformation of keywords. We turn our keywords into
     valid OCaml identifiers by replacing '$', '(', and ')' with '_'.
     Bloody. *)
55

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

  (* 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
105
106
107
108
109
110
111
    (* 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
      | _ :: _ ->
POTTIER Francois's avatar
POTTIER Francois committed
112
113
114
          let content : bytes = Bytes.of_string raw_content in
          transform_keywords ofs1 pkeywords content;
          Bytes.unsafe_to_string content
115
    in
116
117
118
119
120
    (* 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
POTTIER Francois's avatar
POTTIER Francois committed
121
	(String.make (pos1.pos_cnum - pos1.pos_bol - 1) ' ') ^ "(" ^ content ^ ")"
122
123
124
      else
	(String.make (pos1.pos_cnum - pos1.pos_bol) ' ') ^ content
    in
125
126
127
128
129
130
131
132
    (* 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
133
        | PRightDollar 0 -> Before
134
	| PRightDollar i -> RightNamed (rewrite_index i)
POTTIER Francois's avatar
POTTIER Francois committed
135
	| PRightNamed n  -> RightNamed n
136
137
138
139
140
141
142
143
144
      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
145
146
147
148
149
150
    {
      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;
151
      Stretch.stretch_keywords = rewritten_pkeywords
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    } 

  (* 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 ->
173
	  Keyword.PRightDollar (int_of_string n)
174
      | None, Some id ->
175
	  Keyword.PRightNamed id
176
      | None, None ->
177
	  Keyword.PLeft
178
179
180
      | Some _, Some _ ->
          assert false
    in
181
    let keyword = Keyword.PPosition (subject, where, flavor) in
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
    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

248
  (* Short-hands. *)
249

250
251
  let error1 pos =
    Error.error (Positions.one pos)
252

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

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 }
301
302
| "%on_error_reduce"
    { ON_ERROR_REDUCE }
303
| "%%"
304
    { (* The token [PERCENTPERCENT] carries a stretch that contains
305
         everything that follows %% in the input file. This string
306
307
308
309
310
311
312
313
314
         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 []
      )) }
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
| ":"
    { COLON }
| ","
    { COMMA }
| "="
    { EQUAL }
| "("
    { LPAREN }
| ")"
    { RPAREN }
| "|"
    { BAR }
| "?"
    { QUESTION }
| "*"
    { STAR }
| "+"
    { PLUS }
| (lowercase identchar *) as id
    { if Hashtbl.mem reserved id then
335
        error2 lexbuf "this is an Objective Caml reserved word."
336
337
338
339
340
341
342
      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
343
    { new_line lexbuf; main lexbuf }
344
345
346
347
348
349
350
351
352
353
354
| 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
355
        let closingpos, pkeywords = action true openingpos [] lexbuf in
356
357
        no_keywords pkeywords;
        HEADER (mk_stretch openingpos closingpos false [])
358
359
360
361
362
      ) }
| "{"
    { savestart lexbuf (fun lexbuf ->
        let openingpos = lexeme_end_p lexbuf in
        let closingpos, pkeywords = action false openingpos [] lexbuf in
363
        ACTION (
POTTIER Francois's avatar
POTTIER Francois committed
364
	  fun (producers : string option array) ->
365
	  let stretch = mk_stretch openingpos closingpos true pkeywords in
POTTIER Francois's avatar
POTTIER Francois committed
366
	  check_producers_indices producers pkeywords;
367
368
	  Action.from_stretch stretch
	)
369
370
371
372
      ) }
| eof
    { EOF }
| _
373
    { error2 lexbuf "unexpected character(s)." }
374
375
376
377
378

(* Skip C style comments. *)

and comment openingpos = parse
| newline
379
    { new_line lexbuf; comment openingpos lexbuf }
380
381
382
383
384
385
386
387
| "*/"
    { () }
| eof
    { error1 openingpos "unterminated comment." }
| _
    { comment openingpos lexbuf }

(* Collect an O'Caml type delimited by angle brackets. Angle brackets can
388
389
   appear as part of O'Caml function types and variant types, so we must
   recognize them and *not* treat them as a closing bracket. *)
390
391
392

and ocamltype openingpos = parse
| "->"
393
| "[>"
394
395
    { ocamltype openingpos lexbuf }
| '>'
396
    { OCAMLTYPE (Stretch.Declared (mk_stretch openingpos (lexeme_start_p lexbuf) true [])) }
397
398
399
| "(*"
    { ocamlcomment (lexeme_start_p lexbuf) lexbuf; ocamltype openingpos lexbuf }
| newline
400
    { new_line lexbuf; ocamltype openingpos lexbuf }
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
| 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)
430
    { let pkeyword = with_cpos lexbuf (Keyword.PDollar (int_of_string n)) in
431
432
433
434
435
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| poskeyword
    { let pkeyword = mk_keyword lexbuf w f n id in
      action percent openingpos (pkeyword :: pkeywords) lexbuf }
| previouserror
436
    { error2 lexbuf "$previouserror is no longer supported." }
437
| syntaxerror
438
    { let pkeyword = with_cpos lexbuf Keyword.PSyntaxError in
439
440
441
442
443
444
445
446
447
448
449
      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
450
    { new_line lexbuf;
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
      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)
468
    { let pkeyword = with_cpos lexbuf (Keyword.PDollar (int_of_string n)) in
469
470
471
472
473
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| poskeyword
    { let pkeyword = mk_keyword lexbuf w f n id in
      parentheses openingpos (pkeyword :: pkeywords) lexbuf }
| previouserror
474
    { error2 lexbuf "$previouserror is no longer supported." }
475
| syntaxerror
476
    { let pkeyword = with_cpos lexbuf Keyword.PSyntaxError in
477
478
479
480
481
482
483
484
      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
485
    { new_line lexbuf; parentheses openingpos pkeywords lexbuf }
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
| '}'
| 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
508
    { new_line lexbuf; ocamlcomment openingpos lexbuf }
509
510
511
512
513
514
515
516
517
518
519
520
| eof
    { error1 openingpos "unterminated Objective Caml comment." }
| _
    { ocamlcomment openingpos lexbuf }

(* Skip O'Caml strings. *)

and string openingpos = parse
| '"' 
   { () }
| '\\' newline
| newline
521
   { new_line lexbuf; string openingpos lexbuf }
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
| '\\' _
   (* 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 "'"
537
   { new_line lexbuf }
538
539
540
541
542
543
544
| [^ '\\' '\''] "'"
| '\\' _ "'"
| '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] "'"
| '\\' 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'"
| ""
   { () } 

545
546
547
548
549
550
551
(* 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
552
    { new_line lexbuf; finish lexbuf }
553
554
555
556
| eof
    { lexeme_start_p lexbuf }
| _
    { finish lexbuf }