grammar.ml 37.6 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
open UnparameterizedSyntax
open Syntax
open Positions

(* ------------------------------------------------------------------------ *)
(* Precedence levels for tokens or pseudo-tokens alike. *)

module TokPrecedence = struct

  (* This set records, on a token by token basis, whether the token's
     precedence level is ever useful. This allows emitting warnings
     about useless precedence declarations. *)

  let ever_useful : StringSet.t ref =
    ref StringSet.empty

  let use id =
    ever_useful := StringSet.add id !ever_useful

  (* This function is invoked when someone wants to consult a token's
     precedence level. This does not yet mean that this level is
     useful, though. Indeed, if it is subsequently compared against
     [UndefinedPrecedence], it will not allow solving a conflict. So,
     in addition to the desired precedence level, we return a delayed
     computation which, when evaluated, records that this precedence
     level was useful. *)

  let levelip id properties =
    lazy (use id), properties.tk_priority

  let leveli id = 
    let properties =
      try
	StringMap.find id Front.grammar.tokens
      with Not_found ->
	assert false (* well-formedness check has been performed earlier *)
    in
    levelip id properties    

  (* This function is invoked after the automaton has been constructed.
     It warns about unused precedence levels. *)

  let diagnostics () =
    StringMap.iter (fun id properties ->
      if not (StringSet.mem id !ever_useful) then
	match properties.tk_priority with
	| UndefinedPrecedence ->
	    ()
	| PrecedenceLevel (_, _, pos1, pos2) ->
	    Error.grammar_warning (Positions.two pos1 pos2)
	      (Printf.sprintf "the precedence level assigned to %s is never useful." id)
    ) Front.grammar.tokens

end

(* ------------------------------------------------------------------------ *)
(* Nonterminals. *)

module Nonterminal = struct

  type t = int

  let n2i i = i

  let compare = (-)

  (* Determine how many nonterminals we have and build mappings
     both ways between names and indices. A new nonterminal is
     created for every start symbol. *)

  let new_start_nonterminals =
    StringSet.fold (fun symbol ss -> (symbol ^ "'") :: ss) Front.grammar.start_symbols []

  let original_nonterminals =
75
    nonterminals Front.grammar
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
  
  let start =
    List.length new_start_nonterminals

  let (n : int), (name : string array), (map : int StringMap.t) =
    Misc.index (new_start_nonterminals @ original_nonterminals)

  let () =
    Error.logG 1 (fun f ->
      Printf.fprintf f
	"Grammar has %d nonterminal symbols, among which %d start symbols.\n"
	(n - start) start
    )

  let is_start nt =
    nt < start

  let print normalize nt =
    if normalize then
      Misc.normalize name.(nt)
    else
      name.(nt)

  let lookup name =
    StringMap.find name map

  let positions nt =
    (StringMap.find (print false nt) Front.grammar.rules).positions

  let iter f =
    Misc.iteri n f

  let fold f accu =
    Misc.foldi n f accu

  let map f =
    Misc.mapi n f

  let iterx f =
    for nt = start to n - 1 do
      f nt
    done

  let foldx f accu =
    Misc.foldij start n f accu

  let ocamltype nt =
    assert (not (is_start nt));
    try
      Some (StringMap.find (print false nt) Front.grammar.types)
    with Not_found ->
      None

129
130
131
132
133
134
135
136
  let ocamltype_of_start_symbol nt =
    match ocamltype nt with
    | Some typ ->
        typ
    | None ->
        (* Every start symbol has a type. *)
        assert false

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
  let tabulate f =
    Array.get (Array.init n f)

end

(* Sets and maps over nonterminals, used only below. *)

module NonterminalMap = Patricia.Big

module NonterminalSet = Patricia.Big.Domain

(* ------------------------------------------------------------------------ *)
(* Terminals. *)

module Terminal = struct

  type t = int

  let t2i i = i

  let compare = (-)

  let equal (tok1 : t) (tok2 : t) =
    tok1 = tok2

  (* Determine how many terminals we have and build mappings
     both ways between names and indices. A new terminal "#"
     is created. A new terminal "error" is created. The fact
     that the integer code assigned to the "#" pseudo-terminal
     is the last one is exploited in the table-based back-end.
     (The right-most row of the action table is not created.)

     Pseudo-tokens (used in %prec declarations, but never
     declared using %token) are filtered out. *)

POTTIER Francois's avatar
POTTIER Francois committed
172
173
174
  (* In principle, the number of the [error] token is irrelevant.
     It is currently 0, but we do not rely on that. *)

175
  let (n : int), (name : string array), (map : int StringMap.t) =
176
    let tokens = tokens Front.grammar in
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    match tokens with
    | [] ->
	Error.error [] "no tokens have been declared."
    | _ ->
	Misc.index ("error" :: tokens @ [ "#" ])

  let print tok =
    name.(tok)

  let lookup name =
    StringMap.find name map

  let sharp =
    lookup "#"

  let error =
    lookup "error"

  let pseudo tok =
    (tok = sharp) || (tok = error)

POTTIER Francois's avatar
POTTIER Francois committed
198
199
200
  let real t =
    error <> t && t <> sharp

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
  let token_properties = 
    let not_so_dummy_properties = (* applicable to [error] and [#] *)
      {
	tk_filename      = "__primitives__";
	tk_priority      = UndefinedPrecedence;
	tk_associativity = UndefinedAssoc;
	tk_ocamltype     = None;
	tk_is_declared   = true;
	tk_position      = Positions.dummy;
      }
    in
    Array.init n (fun tok ->
      try 
	 StringMap.find name.(tok) Front.grammar.tokens 
       with Not_found ->
	 assert (tok = sharp || tok = error);
	 not_so_dummy_properties
    )

  let () =
    Error.logG 1 (fun f ->
      Printf.fprintf f "Grammar has %d terminal symbols.\n" (n - 2)
    )

  let precedence_level tok = 
    TokPrecedence.levelip (print tok) token_properties.(tok)

  let associativity tok =
    token_properties.(tok).tk_associativity

  let ocamltype tok =
    token_properties.(tok).tk_ocamltype

  let iter f =
    Misc.iteri n f

  let fold f accu =
    Misc.foldi n f accu

  let map f =
    Misc.mapi n f

243
244
  let () =
    assert (sharp = n - 1)
245
  let mapx f =
246
    Misc.mapi sharp f
247

POTTIER Francois's avatar
POTTIER Francois committed
248
249
250
251
252
253
254
  let () =
    assert (error = 0)
  let iter_real f =
    for i = 1 to n-2 do
      f i
    done

255
  (* If a token named [EOF] exists, then it is assumed to represent
256
     ocamllex's [eof] pattern. *)
257
258
259
260
261
262
263

  let eof =
    try
      Some (lookup "EOF")
    with Not_found ->
      None

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
  (* The sub-module [Word] offers an implementation of words (that is,
     sequences) of terminal symbols. It is used by [LRijkstra]. We
     make it a functor, because it has internal state (a hash table)
     and a side effect (failure if there are more than 256 terminal
     symbols). *)

  module Word (X : sig end) = struct

    (* We could use lists, or perhaps the sequences offered by the module
       [Seq], which support constant time concatenation. However, we need a
       much more compact representation: [LRijkstra] stores tens of millions
       of such words. We use strings, because they are very compact (8 bits
       per symbol), and on top of that, we use a hash-consing facility. In
       practice, hash-consing allows us to save 1000x in space. *)

    (* A drawback of this approach is that it works only if the number of
       terminal symbols is at most 256. For the moment, this is good enough.
       [LRijkstra] already has difficulty at 100 terminal symbols or so. *)

    let () =
284
      assert (n <= 256)
285

286
    let (intern : string -> string), verbose =
287
288
289
290
291
292
293
294
295
296
297
298
299
      Misc.new_intern 1023

    type word =
      string

    let epsilon =
      ""

    (* TEMPORARY tabulate? *)
    let singleton t =
      intern (String.make 1 (Char.chr t))

    let append w1 w2 =
300
301
302
303
304
305
      if String.length w1 = 0 then
        w2
      else if String.length w2 = 0 then
        w1
      else
        intern (w1 ^ w2)
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

    let length =
      String.length

    let first w z =
      if length w > 0 then
        Char.code w.[0]
      else
        z

    let rec elements i n w =
      if i = n then
        []
      else
        Char.code w.[i] :: elements (i + 1) n w

    let elements w =
      elements 0 (String.length w) w

    let print w =
      let b = Buffer.create 128 in
      String.iter (fun c ->
        Printf.bprintf b "%s " (print (Char.code c));
      ) w;
      Buffer.contents b

POTTIER Francois's avatar
POTTIER Francois committed
332
333
334
    (* [Pervasives.compare] implements a lexicographic ordering on strings. *)
    let compare = Pervasives.compare

335
336
  end

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
end

(* Sets of terminals are used intensively in the LR(1) construction,
   so it is important that they be as efficient as possible. *)

module TerminalSet = struct

  include CompressedBitSet 

  let print toks =
    let _, accu =
      fold (fun tok (first, accu) ->
	false,
	if first then
          accu ^ (Terminal.print tok)
	else
	  accu ^ " " ^ (Terminal.print tok)
    ) toks (true, "") in
    accu

  let universe =
    remove Terminal.sharp (
      remove Terminal.error (
        Terminal.fold add empty
      )
    )

364
365
366
367
368
369
370
371
372
373
374
375
  (* The following definitions are used in the computation of FIRST sets
     below. They are not exported outside of this file. *)

  type property =
    t

  let bottom =
    empty

  let is_maximal _ =
    false

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
488
489
490
491
492
493
end

(* Maps over terminals. *)

module TerminalMap = Patricia.Big

(* ------------------------------------------------------------------------ *)
(* Symbols. *)

module Symbol = struct

  type t =
    | N of Nonterminal.t
    | T of Terminal.t

  let compare sym1 sym2 =
    match sym1, sym2 with
    | N nt1, N nt2 ->
	Nonterminal.compare nt1 nt2
    | T tok1, T tok2 ->
	Terminal.compare tok1 tok2
    | N _, T _ ->
	1
    | T _, N _ ->
	-1

  let equal sym1 sym2 =
    compare sym1 sym2 = 0

  let rec lequal syms1 syms2 =
    match syms1, syms2 with
    | [], [] ->
	true
    | sym1 :: syms1, sym2 :: syms2 ->
	equal sym1 sym2 && lequal syms1 syms2
    | _ :: _, []
    | [], _ :: _ ->
	false

  let print = function
    | N nt ->
	Nonterminal.print false nt
    | T tok ->
	Terminal.print tok

  let nonterminal = function
    | T _ ->
	false
    | N _ ->
	true

  (* Printing an array of symbols. [offset] is the start offset -- we
     print everything to its right. [dot] is the dot offset -- we
     print a dot at this offset, if we find it. *)

  let printaod offset dot symbols =
    let buffer = Buffer.create 512 in
    let length = Array.length symbols in
    for i = offset to length do
      if i = dot then
	Buffer.add_string buffer ". ";
      if i < length then begin
	Buffer.add_string buffer (print symbols.(i));
	Buffer.add_char buffer ' '
      end
    done;
    Buffer.contents buffer

  let printao offset symbols =
    printaod offset (-1) symbols

  let printa symbols =
    printao 0 symbols

  let printl symbols =
    printa (Array.of_list symbols)

  let lookup name =
    try
      T (Terminal.lookup name)
    with Not_found ->
      try
	N (Nonterminal.lookup name)
      with Not_found ->
	assert false (* well-formedness check has been performed earlier *)

end

(* Sets of symbols. *)

module SymbolSet = Set.Make(Symbol)

(* Maps over symbols. *)

module SymbolMap = struct

  include Map.Make(Symbol)

  let domain m =
    fold (fun symbol _ accu ->
      symbol :: accu
    ) m []

  let purelynonterminal m =
    fold (fun symbol _ accu ->
      accu && Symbol.nonterminal symbol
    ) m true

end

(* ------------------------------------------------------------------------ *)
(* Productions. *)

module Production = struct

  type index =
      int

494
495
496
  let compare =
    (-)

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
550
551
552
553
554
555
556
557
  (* Create an array of productions. Record which productions are
     associated with every nonterminal. A new production S' -> S
     is created for every start symbol S. It is known as a
     start production. *)

  let n : int =
    let n = StringMap.fold (fun _ { branches = branches } n ->
      n + List.length branches
    ) Front.grammar.rules 0 in
    Error.logG 1 (fun f -> Printf.fprintf f "Grammar has %d productions.\n" n);
    n + StringSet.cardinal Front.grammar.start_symbols

  let p2i prod =
    prod

  let i2p prod =
    assert (prod >= 0 && prod < n);
    prod

  let table : (Nonterminal.t * Symbol.t array) array =
    Array.make n (-1, [||])

  let identifiers : identifier array array =
    Array.make n [||]

  let actions : action option array =
    Array.make n None

  let ntprods : (int * int) array =
    Array.make Nonterminal.n (-1, -1)

  let positions : Positions.t list array =
    Array.make n []

  let (start : int),
      (startprods : index NonterminalMap.t) =
    StringSet.fold (fun nonterminal (k, startprods) ->
      let nt = Nonterminal.lookup nonterminal
      and nt' = Nonterminal.lookup (nonterminal ^ "'") in
      table.(k) <- (nt', [| Symbol.N nt |]);
      identifiers.(k) <- [| "_1" |];
      ntprods.(nt') <- (k, k+1);
      positions.(k) <- Nonterminal.positions nt;
      k+1,
      NonterminalMap.add nt k startprods
    ) Front.grammar.start_symbols (0, NonterminalMap.empty)

  let prec_decl : symbol located option array = 
    Array.make n None

  let reduce_precedence : precedence_level array = 
    Array.make n UndefinedPrecedence

  let (_ : int) = StringMap.fold (fun nonterminal { branches = branches } k ->
    let nt = Nonterminal.lookup nonterminal in
    let k' = List.fold_left (fun k branch ->
      let action = branch.action
      and sprec = branch.branch_shift_precedence 
      and rprec = branch.branch_reduce_precedence in	
      let symbols = Array.of_list branch.producers in
      table.(k) <- (nt, Array.map (fun (v, _) -> Symbol.lookup v) symbols);
558
      identifiers.(k) <- Array.map snd symbols;
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
      actions.(k) <- Some action;
      reduce_precedence.(k) <- rprec;
      prec_decl.(k) <- sprec;
      positions.(k) <- [ branch.branch_position ];
      k+1
    ) k branches in
    ntprods.(nt) <- (k, k');
    k'
  ) Front.grammar.rules start

  (* Iteration over the productions associated with a specific
     nonterminal. *)

  let iternt nt f =
    let k, k' = ntprods.(nt) in
    for prod = k to k' - 1 do
      f prod
    done

  let foldnt (nt : Nonterminal.t) (accu : 'a) (f : index -> 'a -> 'a) : 'a =
    let k, k' = ntprods.(nt) in
    let rec loop accu prod =
      if prod < k' then
	loop (f prod accu) (prod + 1)
      else
	accu
    in
    loop accu k

588
589
  (* This funny variant is lazy. If at some point [f] does not demand its
     second argument, then iteration stops. *)
590
  let foldnt_lazy (nt : Nonterminal.t) (f : index -> (unit -> 'a) -> 'a) (seed : 'a) : 'a =
591
592
593
    let k, k' = ntprods.(nt) in
    let rec loop prod seed =
      if prod < k' then
594
        f prod (fun () -> loop (prod + 1) seed)
595
596
597
598
599
      else
        seed
    in
    loop k seed

600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
  (* Accessors. *)

  let def prod =
    table.(prod)

  let nt prod =
    let nt, _ = table.(prod) in
    nt

  let rhs prod =
    let _, rhs = table.(prod) in
    rhs

  let length prod =
    Array.length (rhs prod)

  let identifiers prod =
    identifiers.(prod)

  let is_start prod =
    prod < start

  let classify prod =
    if is_start prod then
      match (rhs prod).(0) with
      | Symbol.N nt ->
	  Some nt
      | Symbol.T _ ->
	  assert false
    else
      None

  let action prod =
    match actions.(prod) with
    | Some action ->
	action
    | None ->
	(* Start productions have no action. *)
	assert (is_start prod);
	assert false

  let positions prod =
    positions.(prod)

  let startsymbol2startprod nt =
    try
      NonterminalMap.find nt startprods
    with Not_found ->
      assert false (* [nt] is not a start symbol *)

  (* Iteration. *)

  let iter f =
    Misc.iteri n f

  let fold f accu =
    Misc.foldi n f accu

  let map f =
    Misc.mapi n f

POTTIER Francois's avatar
POTTIER Francois committed
661
662
663
  let amap f =
    Array.init n f

664
665
666
667
668
669
670
671
  let iterx f =
    for prod = start to n - 1 do
      f prod
    done

  let foldx f accu =
    Misc.foldij start n f accu

672
673
674
  let mapx f =
    Misc.mapij start n f

675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
  (* Printing a production. *)

  let print prod =
    assert (not (is_start prod));
    let nt, rhs = table.(prod) in
    Printf.sprintf "%s -> %s" (Nonterminal.print false nt) (Symbol.printao 0 rhs)

  (* Tabulation. *)

  let tabulate f =
    Misc.tabulate n f

  let tabulateb f =
    Misc.tabulateb n f

  (* This array allows recording, on a production by production basis,
     whether the production's shift precedence is ever useful. This
     allows emitting warnings about useless %prec declarations. *)

  let prec_decl_ever_useful =
    Array.make n false

  let consult_prec_decl prod =
    lazy (prec_decl_ever_useful.(prod) <- true),
    prec_decl.(prod)

  let diagnostics () =
    iterx (fun prod ->
      if not prec_decl_ever_useful.(prod) then
	match prec_decl.(prod) with
	| None ->
	    ()
	| Some id ->
	    Error.grammar_warning [Positions.position id] "this %prec declaration is never useful."
    )

  (* Determining the precedence level of a production. If no %prec
     declaration was explicitly supplied, it is the precedence level
     of the rightmost terminal symbol in the production's right-hand
     side. *)

  type production_level =
    | PNone
    | PRightmostToken of Terminal.t
    | PPrecDecl of symbol

  let rightmost_terminal prod =
    Array.fold_left (fun accu symbol ->
      match symbol with
      | Symbol.T tok ->
	  PRightmostToken tok
      | Symbol.N _ ->
	  accu
    ) PNone (rhs prod)

  let combine e1 e2 =
    lazy (Lazy.force e1; Lazy.force e2)

  let shift_precedence prod =
    let fact1, prec_decl = consult_prec_decl prod in
    let oterminal =
      match prec_decl with
      | None ->
	  rightmost_terminal prod
      | Some { value = terminal } ->
	  PPrecDecl terminal
    in
    match oterminal with
    | PNone ->
	fact1, UndefinedPrecedence
    | PRightmostToken tok ->
	let fact2, level = Terminal.precedence_level tok in
	combine fact1 fact2, level
    | PPrecDecl id ->
	let fact2, level = TokPrecedence.leveli id  in
	combine fact1 fact2, level

end

(* ------------------------------------------------------------------------ *)
(* Maps over productions. *)

module ProductionMap = struct

  include Patricia.Big

  (* Iteration over the start productions only. *)

  let start f =
    Misc.foldi Production.start (fun prod m ->
      add prod (f prod) m
    ) empty

end

(* ------------------------------------------------------------------------ *)
771
772
773
(* If requested, build and print the forward reference graph of the grammar.
   There is an edge of a nonterminal symbol [nt1] to every nonterminal symbol
   [nt2] that occurs in the definition of [nt1]. *)
774
775

let () =
776
  if Settings.graph then begin
777

778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
    (* Allocate. *)

    let forward : NonterminalSet.t array =
      Array.make Nonterminal.n NonterminalSet.empty
    in

    (* Populate. *)

    Array.iter (fun (nt1, rhs) ->
      Array.iter (function
        | Symbol.T _ ->
            ()
        | Symbol.N nt2 ->
            forward.(nt1) <- NonterminalSet.add nt2 forward.(nt1)
      ) rhs
    ) Production.table;

    (* Print. *)
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813

    let module P = Dot.Print (struct
      type vertex = Nonterminal.t
      let name nt =
	Printf.sprintf "nt%d" nt
      let successors (f : ?style:Dot.style -> label:string -> vertex -> unit) nt =
	NonterminalSet.iter (fun successor ->
	  f ~label:"" successor
	) forward.(nt)
      let iter (f : ?style:Dot.style -> label:string -> vertex -> unit) =
	Nonterminal.iter (fun nt ->
	  f ~label:(Nonterminal.print false nt) nt
	)
    end) in
    let f = open_out (Settings.base ^ ".dot") in
    P.print f;
    close_out f

814
815
  end

816
817
818
819
(* ------------------------------------------------------------------------ *)
(* Support for analyses of the grammar, expressed as fixed point computations.
   We exploit the generic fixed point algorithm in [Fix]. *)

POTTIER Francois's avatar
POTTIER Francois committed
820
821
822
823
824
(* We perform memoization only at nonterminal symbols. We assume that the
   analysis of a symbol is the analysis of its definition (as opposed to,
   say, a computation that depends on the occurrences of this symbol in
   the grammar). *)

825
826
827
828
829
830
831
832
833
834
835
836
837
838
module GenericAnalysis
  (P : Fix.PROPERTY)
  (S : sig
    open P

    (* An analysis is specified by the following functions. *)

    (* [terminal] maps a terminal symbol to a property. *)
    val terminal: Terminal.t -> property
    
    (* [disjunction] abstracts a binary alternative. That is, when we analyze
       an alternative between several productions, we compute a property for
       each of them independently, then we combine these properties using
       [disjunction]. *)
839
    val disjunction: property -> (unit -> property) -> property
840
841
842
843
844
845
846
847
848

    (* [P.bottom] should be a neutral element for [disjunction]. We use it in
       the analysis of an alternative with zero branches. *)

    (* [conjunction] abstracts a binary sequence. That is, when we analyze a
       sequence, we compute a property for each member independently, then we
       combine these properties using [conjunction]. In general, conjunction
       needs access to the first member of the sequence (a symbol), not just
       to its analysis (a property). *)
849
    val conjunction: Symbol.t -> property -> (unit -> property) -> property
850
851
852
853
854
855
856
857
858
859
860
861

    (* [epsilon] abstracts the empty sequence. It should be a neutral element
       for [conjunction]. *)
    val epsilon: property

  end)
: sig
  open P

  (* The results of the analysis take the following form. *)

  (* To every nonterminal symbol, we associate a property. *)
POTTIER Francois's avatar
POTTIER Francois committed
862
863
864
865
  val nonterminal: Nonterminal.t -> property

  (* To every symbol, we associate a property. *)
  val symbol: Symbol.t -> property
866
867
868
869
870
871
872
873
874
875

  (* To every suffix of every production, we associate a property.
     The offset [i], which determines the beginning of the suffix,
     must be contained between [0] and [n], inclusive, where [n]
     is the length of the production. *)
  val production: Production.index -> int -> property

end = struct
  open P

POTTIER Francois's avatar
POTTIER Francois committed
876
877
878
879
880
  (* The following analysis functions are parameterized over [get], which allows
     making a recursive call to the analysis at a nonterminal symbol. [get] maps
     a nonterminal symbol to a property. *)

  (* Analysis of a symbol. *)
881

POTTIER Francois's avatar
POTTIER Francois committed
882
883
884
885
886
887
888
889
890
  let symbol sym get : property =
    match sym with
    | Symbol.T tok ->
        S.terminal tok
    | Symbol.N nt ->
        (* Recursive call to the analysis, via [get]. *)
        get nt    

  (* Analysis of (a suffix of) a production [prod], starting at index [i]. *)
891

POTTIER Francois's avatar
POTTIER Francois committed
892
  let production prod i get : property =
893
894
895
896
897
898
899
900
901
902
    let rhs = Production.rhs prod in
    let n = Array.length rhs in
    (* Conjunction over all symbols in the right-hand side. This can be viewed
       as a version of [Array.fold_right], which does not necessarily begin at
       index [0]. Note that, because [conjunction] is lazy, it is possible
       to stop early. *)
    let rec loop i =
      if i = n then
        S.epsilon
      else
POTTIER Francois's avatar
POTTIER Francois committed
903
904
905
        let sym = rhs.(i) in
        S.conjunction sym
          (symbol sym get)
906
          (fun () -> loop (i+1))
907
908
909
910
911
912
913
    in
    loop i

  (* The analysis is the least fixed point of the following function, which
     analyzes a nonterminal symbol by looking up and analyzing its definition
     as a disjunction of conjunctions of symbols. *)

POTTIER Francois's avatar
POTTIER Francois committed
914
  let nonterminal nt get : property =
915
916
917
918
919
920
921
922
923
924
925
926
    (* Disjunction over all productions for this nonterminal symbol. *)
    Production.foldnt_lazy nt (fun prod rest ->
      S.disjunction
        (production prod 0 get)
        rest
    ) P.bottom

  (* The least fixed point is taken as follows. Note that it is computed
     on demand, as [lfp] is called by the user. *)

  module F =
    Fix.Make
927
      (Maps.ArrayAsImperativeMaps(Nonterminal))
928
929
      (P)

POTTIER Francois's avatar
POTTIER Francois committed
930
931
932
933
  let nonterminal =
    F.lfp nonterminal

  (* The auxiliary functions can be published too. *)
934

POTTIER Francois's avatar
POTTIER Francois committed
935
936
  let symbol sym =
    symbol sym nonterminal
937

POTTIER Francois's avatar
POTTIER Francois committed
938
939
  let production prod i =
    production prod i nonterminal
940
941
942

end

943
944
945
946
947
948
(* ------------------------------------------------------------------------ *)
(* The computation of FOLLOW sets does not follow the above model. Instead, we
   need to explicitly compute a system of equations over sets of terminal
   symbols (in a first pass), then solve the constraints (in a second
   pass). *)

949
(* An equation's right-hand side is a set expression. *)
950

951
952
953
954
type expr =
| EVar of Nonterminal.t
| EConstant of TerminalSet.t
| EUnion of expr * expr
955
956

(* A system of equations is represented as an array, which maps nonterminal
957
   symbols to expressions. *)
958
959

type equations =
960
  expr array
961
962
963
964
965

(* This solver computes the least solution of a set of equations. *)

let solve (eqs : equations) : Nonterminal.t -> TerminalSet.t =

966
967
968
  let rec expr e get =
    match e with
    | EVar nt ->
969
        get nt
970
    | EConstant c ->
971
        c
972
973
    | EUnion (e1, e2) ->
        TerminalSet.union (expr e1 get) (expr e2 get)
974
975
976
  in

  let nonterminal nt get =
977
    expr eqs.(nt) get
978
979
980
981
  in

  let module F =
    Fix.Make
982
      (Maps.ArrayAsImperativeMaps(Nonterminal))
983
984
985
986
987
      (TerminalSet)
  in
  
  F.lfp nonterminal

988
989
990
991
992
993
994
(* ------------------------------------------------------------------------ *)
(* Compute which nonterminals are nonempty, that is, recognize a
   nonempty language. Also, compute which nonterminals are
   nullable. The two computations are almost identical. The only
   difference is in the base case: a single terminal symbol is not
   nullable, but is nonempty. *)

995
996
997
998
999
1000
module NONEMPTY =
  GenericAnalysis
    (Boolean)
    (struct
      (* A terminal symbol is nonempty. *)
      let terminal _ = true
For faster browsing, not all history is shown. View entire blame