printer.ml 20.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
(******************************************************************************)
(*                                                                            *)
(*                                   Menhir                                   *)
(*                                                                            *)
(*                       François Pottier, Inria Paris                        *)
(*              Yann Régis-Gianas, PPS, Université Paris Diderot              *)
(*                                                                            *)
(*  Copyright Inria. All rights reserved. This file is distributed under the  *)
(*  terms of the GNU General Public License version 2, as described in the    *)
(*  file LICENSE.                                                             *)
(*                                                                            *)
(******************************************************************************)

14
15
16
17
(* A pretty-printer for [IL]. *)

open IL

18
19
20
21
22
23
24
25
26
module PreliminaryMake (X : sig

  (* We assume that the following types and functions are given. This
     allows us to work both with buffers of type [Buffer.t] and with
     output channels of type [out_channel]. *)

  type channel
  val fprintf: channel -> ('a, channel, unit) format -> 'a
  val output_substring: channel -> string -> int -> int -> unit
27
28
29

  (* This is the channel that is being written to. *)

30
  val f: channel
31

POTTIER Francois's avatar
POTTIER Francois committed
32
33
34
35
36
37
38
39
40
41
42
43
44
  (* [locate_stretches] controls the way we print OCaml stretches (types and
     semantic actions). If it is [Some filename], then we surround them with
     OCaml line number directives of the form # <line number> <filename>. If
     it is [None], then we don't. *)

  (* Providing line number directives allows the OCaml typechecker to report
     type errors in the .mly file, instead of in the generated .ml / .mli
     files. Line number directives also affect the dynamic semantics of any
     [assert] statements contained in semantic actions: when they are provided,
     the [Assert_failure] exception carries a location in the .mly file. As a
     general rule of thumb, line number directives should always be provided,
     except perhaps where we think that they decrease readability (e.g., in a
     generated .mli file). *)
45
46
47
48

  val locate_stretches: string option

end) = struct
49
50
51
52
53
54
55
56
57
58
open X

let output_char f c =
  fprintf f "%c" c

let output_string f s =
  fprintf f "%s" s

let flush f =
  fprintf f "%!"
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

(* ------------------------------------------------------------------------- *)
(* Dealing with newlines and indentation. *)

let maxindent =
  120

let whitespace =
  String.make maxindent ' '

let indentation =
  ref 0

let line =
  ref 1

(* [rawnl] is, in principle, the only place where writing a newline
   character to the output channel is permitted. This ensures that the
   line counter remains correct. But see also [stretch] and [typ0]. *)

let rawnl f =
  incr line;
  output_char f '\n'

let nl f =
  rawnl f;
POTTIER Francois's avatar
POTTIER Francois committed
85
  output_substring f whitespace 0 !indentation
86
87
88
89
90
91
92
93
94
95

let indent ofs producer f x =
  let old_indentation = !indentation in
  let new_indentation = old_indentation + ofs in
  if new_indentation <= maxindent then
    indentation := new_indentation;
  nl f;
  producer f x;
  indentation := old_indentation

POTTIER Francois's avatar
POTTIER Francois committed
96
(* This produces a line number directive. *)
97
98
99
100
101
102
103

let sharp f line file =
  fprintf f "%t# %d \"%s\"%t" rawnl line file rawnl

(* ------------------------------------------------------------------------- *)
(* Printers of atomic elements. *)

104
let nothing _ =
105
106
107
108
109
110
111
112
  ()

let space f =
  output_char f ' '

let comma f =
  output_string f ", "

POTTIER Francois's avatar
POTTIER Francois committed
113
114
115
let semi f =
  output_char f ';'

116
let seminl f =
POTTIER Francois's avatar
POTTIER Francois committed
117
  semi f;
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
  nl f

let times f =
  output_string f " * "

let letrec f =
  output_string f "let rec "

let letnonrec f =
  output_string f "let "

let keytyp f =
  output_string f "type "

let exc f =
  output_string f "exception "

let et f =
  output_string f "and "

let var f x =
  output_string f x

let bar f =
  output_string f " | "

(* ------------------------------------------------------------------------- *)
(* List printers. *)

147
148
(* A list with a separator in front of every element. *)

149
150
151
152
153
154
let rec list elem sep f = function
  | [] ->
      ()
  | e :: es ->
      fprintf f "%t%a%a" sep elem e (list elem sep) es

155
156
157
158
159
160
161
162
163
164
(* A list with a separator between elements. *)

let seplist elem sep f = function
  | [] ->
      ()
  | e :: es ->
      fprintf f "%a%a" elem e (list elem sep) es

(* OCaml type parameters. *)

165
let typeparams p0 p1 f = function
166
167
168
169
  | [] ->
      ()
  | [ param ] ->
      fprintf f "%a " p0 param
170
171
  | _ :: _ as params ->
      fprintf f "(%a) " (seplist p1 comma) params
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

(* ------------------------------------------------------------------------- *)
(* Expression printer. *)

(* We use symbolic constants that stand for subsets of the
   expression constructors. We do not use numeric levels
   to stand for subsets, because our subsets do not form
   a linear inclusion chain. *)

type subset =
  | All
  | AllButSeq
  | AllButFunTryMatch
  | AllButFunTryMatchSeq
  | AllButLetFunTryMatch
  | AllButLetFunTryMatchSeq
  | AllButIfThenSeq
  | OnlyAppOrAtom
  | OnlyAtom

(* This computes the intersection of a subset with the
   constraint "should not be a sequence". *)

let andNotSeq = function
  | All
  | AllButSeq ->
      AllButSeq
  | AllButFunTryMatch
  | AllButFunTryMatchSeq ->
      AllButFunTryMatchSeq
  | AllButLetFunTryMatch
  | AllButLetFunTryMatchSeq ->
      AllButLetFunTryMatchSeq
  | AllButIfThenSeq ->
      AllButIfThenSeq
  | OnlyAppOrAtom ->
      OnlyAppOrAtom
  | OnlyAtom ->
      OnlyAtom

(* This defines the semantics of subsets by relating
   expressions with subsets. *)

let rec member e k =
  match e with
  | EComment _
  | EPatComment _ ->
      true
  | EFun _
  | ETry _
  | EMatch _ ->
      begin
224
225
226
227
228
229
230
231
232
233
        match k with
        | AllButFunTryMatch
        | AllButFunTryMatchSeq
        | AllButLetFunTryMatch
        | AllButLetFunTryMatchSeq
        | OnlyAppOrAtom
        | OnlyAtom ->
            false
        | _ ->
            true
234
235
236
237
238
      end
  | ELet ([], e) ->
      member e k
  | ELet ((PUnit, _) :: _, _) ->
      begin
239
240
241
242
243
244
245
246
247
248
        match k with
        | AllButSeq
        | AllButFunTryMatchSeq
        | AllButLetFunTryMatchSeq
        | AllButIfThenSeq
        | OnlyAppOrAtom
        | OnlyAtom ->
            false
        | _ ->
            true
249
250
251
      end
  | ELet (_ :: _, _) ->
      begin
252
253
254
255
256
257
258
259
        match k with
        | AllButLetFunTryMatch
        | AllButLetFunTryMatchSeq
        | OnlyAppOrAtom
        | OnlyAtom ->
            false
        | _ ->
            true
260
261
262
      end
  | EIfThen _ ->
      begin
263
264
265
266
267
268
269
        match k with
        | AllButIfThenSeq
        | OnlyAppOrAtom
        | OnlyAtom ->
            false
        | _ ->
            true
270
271
272
273
274
275
276
      end
  | EApp (_, _ :: _)
  | EData (_, _ :: _)
  | EMagic _
  | ERepr _
  | ERaise _ ->
      begin
277
278
279
280
281
        match k with
        | OnlyAtom ->
            false
        | _ ->
            true
282
283
284
285
      end
  | ERecordWrite _
  | EIfThenElse _ ->
      begin
286
287
288
289
290
291
        match k with
        | OnlyAppOrAtom
        | OnlyAtom ->
            false
        | _ ->
            true
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
      end
  | EVar _
  | ETextual _
  | EApp (_, [])
  | EData (_, [])
  | ETuple _
  | EAnnot _
  | ERecord _
  | ERecordAccess (_, _)
  | EIntConst _
  | EStringConst _
  | EUnit
  | EArray _
  | EArrayAccess (_, _) ->
      true


let rec exprlet k pes f e2 =
  match pes with
  | [] ->
      exprk k f e2
  | (PUnit, e1) :: pes ->
      fprintf f "%a%t%a" (exprk AllButLetFunTryMatch) e1 seminl (exprlet k pes) e2
  | (PVar id1, EAnnot (e1, ts1)) :: pes ->
      (* TEMPORARY current ocaml does not support type schemes here; drop quantifiers, if any *)
      fprintf f "let %s : %a = %a in%t%a" id1 typ ts1.body (* scheme ts1 *) expr e1 nl (exprlet k pes) e2
  | (PVar id1, EFun (ps1, e1)) :: pes ->
      fprintf f "let %s%a = %a in%t%t%a"
320
        id1 (list pat0 space) ps1 (indent 2 expr) e1 nl nl (exprlet k pes) e2
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
  | (p1, (ELet _ as e1)) :: pes ->
      fprintf f "let %a =%a%tin%t%a" pat p1 (indent 2 expr) e1 nl nl (exprlet k pes) e2
  | (p1, e1) :: pes ->
      fprintf f "let %a = %a in%t%a" pat p1 expr e1 nl (exprlet k pes) e2

and atom f e =
  exprk OnlyAtom f e

and app f e =
  exprk OnlyAppOrAtom f e

and expr f e =
  exprk All f e

and exprk k f e =
  if member e k then
    match e with
    | EComment (c, e) ->
339
340
341
342
        if Settings.comment then
          fprintf f "(* %s *)%t%a" c nl (exprk k) e
        else
          exprk k f e
343
    | EPatComment (s, p, e) ->
344
345
346
347
        if Settings.comment then
          fprintf f "(* %s%a *)%t%a" s pat p nl (exprk k) e
        else
          exprk k f e
348
    | ELet (pes, e2) ->
349
        exprlet k pes f e2
350
    | ERecordWrite (e1, field, e2) ->
351
        fprintf f "%a.%s <- %a" atom e1 field (exprk (andNotSeq k)) e2
352
    | EMatch (_, []) ->
353
        assert false
354
    | EMatch (e, brs) ->
355
        fprintf f "match %a with%a" expr e (branches k) brs
356
    | ETry (_, []) ->
357
        assert false
358
    | ETry (e, brs) ->
359
        fprintf f "try%a%twith%a" (indent 2 expr) e nl (branches k) brs
360
    | EIfThen (e1, e2) ->
361
        fprintf f "if %a then%a" expr e1 (indent 2 (exprk (andNotSeq k))) e2
362
    | EIfThenElse (e0, e1, e2) ->
363
        fprintf f "if %a then%a%telse%a"
364
365
          expr e0 (indent 2 (exprk AllButIfThenSeq)) e1 nl (indent 2 (exprk (andNotSeq k))) e2
    | EFun (ps, e) ->
366
        fprintf f "fun%a ->%a" (list pat0 space) ps (indent 2 (exprk k)) e
367
368
    | EApp (EVar op, [ e1; e2 ])
      when op.[0] = '(' && op.[String.length op - 1] = ')' ->
369
370
        let op = String.sub op 1 (String.length op - 2) in
        fprintf f "%a %s %a" app e1 op app e2
371
    | EApp (e, args) ->
372
        fprintf f "%a%a" app e (list atom space) args
373
    | ERaise e ->
374
        fprintf f "raise %a" atom e
375
    | EMagic e ->
376
        fprintf f "Obj.magic %a" atom e
377
    | ERepr e ->
378
        fprintf f "Obj.repr %a" atom e
379
    | EData (d, []) ->
380
        var f d
381
    | EData (d, [ arg ]) ->
382
        fprintf f "%s %a" d atom arg
383
384
385
    | EData ("::", [ arg1; arg2 ]) ->
        (* Special case for infix cons. *)
        fprintf f "%a :: %a" atom arg1 atom arg2
386
    | EData (d, (_ :: _ :: _ as args)) ->
387
        fprintf f "%s (%a)" d (seplist app comma) args
388
    | EVar v ->
389
        var f v
390
    | ETextual action ->
391
        stretch false f action
392
    | EUnit ->
393
        fprintf f "()"
394
    | EIntConst k ->
395
396
397
398
        if k >= 0 then
          fprintf f "%d" k
        else
          fprintf f "(%d)" k
399
    | EStringConst s ->
400
        fprintf f "\"%s\"" (String.escaped s)
401
    | ETuple [] ->
402
        assert false
403
    | ETuple [ e ] ->
404
        atom f e
405
    | ETuple (_ :: _ :: _ as es) ->
406
        fprintf f "(%a)" (seplist app comma) es
407
    | EAnnot (e, s) ->
408
409
        (* TEMPORARY current ocaml does not support type schemes here; drop quantifiers, if any *)
        fprintf f "(%a : %a)" app e typ s.body (* should be scheme s *)
410
    | ERecordAccess (e, field) ->
411
        fprintf f "%a.%s" atom e field
412
    | ERecord fs ->
413
        fprintf f "{%a%t}" (indent 2 (seplist field nl)) fs nl
414
    | EArray fs ->
415
        fprintf f "[|%a%t|]" (indent 2 (seplist array_field nl)) fs nl
416
    | EArrayAccess (e, i) ->
417
        fprintf f "%a.(%a)" atom e expr i
418
419
420
421
422
423
424
425
426
427
428
429
  else
    fprintf f "(%a)" expr e

and stretch raw f stretch =
  let content = stretch.Stretch.stretch_content
  and raw_content = stretch.Stretch.stretch_raw_content in
  match X.locate_stretches with
  | Some basename ->
      sharp f stretch.Stretch.stretch_linenum stretch.Stretch.stretch_filename;
      output_string f content;
      line := !line + stretch.Stretch.stretch_linecount;
      sharp f (!line + 2) basename;
POTTIER Francois's avatar
POTTIER Francois committed
430
      output_substring f whitespace 0 !indentation
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
  | None ->
      output_string f (if raw then raw_content else content)

and branches k f = function
  | [] ->
      ()
  | [ br ] ->
      fprintf f "%t| %a" nl (branch k) br
  | br :: brs ->
      fprintf f "%t| %a%a" nl (branch AllButFunTryMatch) br (branches k) brs

and branch k f br =
  fprintf f "%a ->%a" pat br.branchpat (indent 4 (exprk k)) br.branchbody

and field f (label, e) =
POTTIER Francois's avatar
POTTIER Francois committed
446
  fprintf f "%s = %a%t" label app e semi
447

POTTIER Francois's avatar
POTTIER Francois committed
448
449
and fpat f (label, p) =
  fprintf f "%s = %a%t" label pat p semi
450
451

and array_field f e =
POTTIER Francois's avatar
POTTIER Francois committed
452
  fprintf f "%a%t" app e semi
453
454
455
456
457
458
459
460
461
462
463
464
465
466

and pat0 f = function
  | PUnit ->
      fprintf f "()"
  | PWildcard ->
      fprintf f "_"
  | PVar x ->
      var f x
  | PData (d, []) ->
      var f d
  | PTuple [] ->
      assert false
  | PTuple [ p ] ->
      pat0 f p
467
468
  | PTuple (_ :: _ :: _ as ps) ->
      fprintf f "(%a)" (seplist pat1 comma) ps
469
470
471
  | PAnnot (p, t) ->
      fprintf f "(%a : %a)" pat p typ t
  | PRecord fps ->
POTTIER Francois's avatar
POTTIER Francois committed
472
473
474
      (* In a record pattern, fields can be omitted. *)
      let fps = List.filter (function (_, PWildcard) -> false | _ -> true) fps in
      fprintf f "{%a%t}" (indent 2 (seplist fpat nl)) fps nl
475
476
477
478
479
480
  | p ->
      fprintf f "(%a)" pat p

and pat1 f = function
  | PData (d, [ arg ]) ->
      fprintf f "%s %a" d pat0 arg
481
482
  | PData (d, (_ :: _ :: _ as args)) ->
      fprintf f "%s (%a)" d (seplist pat1 comma) args
483
484
485
486
487
488
489
490
  | PTuple [ p ] ->
      pat1 f p
  | p ->
      pat0 f p

and pat2 f = function
  | POr [] ->
      assert false
491
  | POr (_ :: _ as ps) ->
POTTIER Francois's avatar
POTTIER Francois committed
492
      seplist pat2 bar f ps
493
494
495
496
497
498
499
500
  | PTuple [ p ] ->
      pat2 f p
  | p ->
      pat1 f p

and pat f p =
  pat2 f p

501
502
503
504
505
and typevar f = function
  | "_" ->
      fprintf f "_"
  | v ->
      fprintf f "'%s" v
506
507
508
509

and typ0 f = function
  | TypTextual (Stretch.Declared ocamltype) ->
      (* Parentheses are necessary to avoid confusion between 1 - ary
510
         data constructor with n arguments and n - ary data constructor. *)
511
512
513
514
515
516
517
518
519
520
521
522
523
524
      fprintf f "(%a)" (stretch true) ocamltype
  | TypTextual (Stretch.Inferred t) ->
      line := !line + LineCount.count 0 (Lexing.from_string t);
      fprintf f "(%s)" t
  | TypVar v ->
      typevar f v
  | TypApp (t, params) ->
      fprintf f "%a%s" (typeparams typ0 typ) params t
  | t ->
      fprintf f "(%a)" typ t

and typ1 f = function
  | TypTuple [] ->
      assert false
525
526
  | TypTuple (_ :: _ as ts) ->
      seplist typ0 times f ts
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
  | t ->
      typ0 f t

and typ2 f = function
  | TypArrow (t1, t2) ->
      fprintf f "%a -> %a" typ1 t1 typ2 t2
  | t ->
      typ1 f t

and typ f =
  typ2 f

and scheme f scheme =
  match scheme.quantifiers with
  | [] ->
      typ f scheme.body
  | qs ->
      fprintf f "%a. %a" (list typevar space) qs typ scheme.body

(* ------------------------------------------------------------------------- *)
(* Toplevel definition printer. *)

POTTIER Francois's avatar
POTTIER Francois committed
549
(* The tuple of the arguments of a data constructor. *)
550

POTTIER Francois's avatar
POTTIER Francois committed
551
552
553
554
555
556
let datavalparams f params =
  (* [typ1] because [type t = A of  int -> int ] is not allowed by OCaml *)
  (*                [type t = A of (int -> int)] is allowed *)
  seplist typ1 times f params

(* A data constructor definition. *)
557

POTTIER Francois's avatar
POTTIER Francois committed
558
559
560
561
562
563
564
565
566
567
568
569
let datadef typename f def =
  fprintf f "  | %s" def.dataname;
  match def.datavalparams, def.datatypeparams with
  | [], None ->
      (* | A *)
      ()
  | _ :: _, None ->
      (* | A of t * u *)
      fprintf f " of %a"
        datavalparams def.datavalparams
  | [], Some indices ->
      (* | A : (v, w) ty *)
POTTIER Francois's avatar
POTTIER Francois committed
570
      fprintf f " : %a%s"
POTTIER Francois's avatar
POTTIER Francois committed
571
572
573
        (typeparams typ0 typ) indices typename
  | _ :: _, Some indices ->
      (* | A : t * u -> (v, w) ty *)
POTTIER Francois's avatar
POTTIER Francois committed
574
      fprintf f " : %a -> %a%s"
POTTIER Francois's avatar
POTTIER Francois committed
575
576
        datavalparams def.datavalparams
        (typeparams typ0 typ) indices typename
577
578
579
580
581
582
583

let fielddef f def =
  fprintf f "  %s%s: %a"
    (if def.modifiable then "mutable " else "")
    def.fieldname
    scheme def.fieldtype

POTTIER Francois's avatar
POTTIER Francois committed
584
let typerhs typename f = function
585
586
  | TDefRecord [] ->
      assert false
POTTIER Francois's avatar
POTTIER Francois committed
587
588
  | TDefRecord (_ :: _ as fields) ->
      fprintf f " = {%t%a%t}" nl (seplist fielddef seminl) fields nl
589
590
591
  | TDefSum [] ->
      ()
  | TDefSum defs ->
POTTIER Francois's avatar
POTTIER Francois committed
592
      fprintf f " = %a" (list (datadef typename) nl) defs
593
594
595
596
597
598
599
600
601
602
  | TAbbrev t ->
      fprintf f " = %a" typ t

let typeconstraint f = function
  | None ->
      ()
  | Some (t1, t2) ->
      fprintf f "%tconstraint %a = %a" nl typ t1 typ t2

let typedef f def =
603
  fprintf f "%a%s%a%a"
604
605
    (typeparams typevar typevar) def.typeparams
    def.typename
POTTIER Francois's avatar
POTTIER Francois committed
606
    (typerhs def.typename) def.typerhs
607
608
609
610
611
    typeconstraint def.typeconstraint

let rec pdefs pdef sep1 sep2 f = function
  | [] ->
      ()
612
613
  | [ def ] ->
      fprintf f "%t%a" sep1 pdef def
614
  | def :: defs ->
615
616
617
618
619
      fprintf f "%t%a%t%t%a"
        sep1 pdef def
        (* Separate two successive items with two newlines. *)
        nl nl
        (pdefs pdef sep2 sep2) defs
620
621
622
623

let valdef f = function
  | { valpat = PVar id; valval = EAnnot (e, ts) } ->
      (* TEMPORARY current ocaml does not support type schemes here; drop quantifiers, if any *)
624
      fprintf f "%s : %a =%a" id typ ts.body (* scheme ts *) (indent 2 expr) e
625
  | { valpat = p; valval = e } ->
626
      fprintf f "%a =%a" pat p (indent 2 expr) e
627

628
629
let valdefs recursive =
  pdefs valdef (if recursive then letrec else letnonrec) et
630
631
632
633

let typedefs =
  pdefs typedef keytyp et

634
635
636
637
let excdef in_intf f def =
  match in_intf, def.exceq with
  | _, None
  | true, Some _ ->
638
      fprintf f "%s" def.excname
639
  | false, Some s ->
640
      fprintf f "%s = %s" def.excname s
641

642
643
let excdefs in_intf =
  pdefs (excdef in_intf) exc exc
644

POTTIER Francois's avatar
POTTIER Francois committed
645
let block format body f b =
646
647
648
  fprintf f format (fun f b ->
    indent 2 body f b;
    nl f
POTTIER Francois's avatar
POTTIER Francois committed
649
650
  ) b

651
652
653
654
655
(* Convention: each structure (or interface) item prints a newline before and
   after itself. *)

let rec structure_item f item =
  match item with
656
657
  | SIFunctor ([], s) ->
      structure f s
658
659
  | SIStretch stretches ->
      List.iter (stretch false f) stretches
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
  | _ ->
    nl f;
    begin match item with
    | SIFunctor (params, s) ->
        fprintf f "module Make%a%t= %a"
          (list (stretch false) nl) params
          nl
          structend s
    | SIExcDefs defs ->
        excdefs false f defs
    | SITypeDefs defs ->
        typedefs f defs
    | SIValDefs (recursive, defs) ->
        valdefs recursive f defs
    | SIStretch _ ->
        assert false (* already handled above *)
    | SIModuleDef (name, rhs) ->
        fprintf f "module %s = %a" name modexpr rhs
678
679
    | SIInclude e ->
        fprintf f "include %a" modexpr e
POTTIER Francois's avatar
POTTIER Francois committed
680
681
    | SIComment comment ->
        fprintf f "(* %s *)" comment
682
683
    end;
    nl f
684

685
686
687
and structend f s =
  block "struct%aend" structure f s

688
and structure f s =
689
  list structure_item nothing f s
690

691
and modexpr f = function
692
693
694
  | MVar x ->
      fprintf f "%s" x
  | MStruct s ->
695
      structend f s
696
697
698
699
  | MApp (e1, e2) ->
      fprintf f "%a (%a)" modexpr e1 modexpr e2

let valdecl f (x, ts) =
700
  fprintf f "val %s: %a" x typ ts.body
701
702
703
704
705
706
707
708
709
710

let with_kind f = function
  | WKNonDestructive ->
      output_string f "="
  | WKDestructive ->
      output_string f ":="

let rec module_type f = function
  | MTNamedModuleType s ->
      output_string f s
711
  | MTWithType (mt, params, name, wk, t) ->
712
713
      fprintf f "%a%a"
        module_type mt
714
        (indent 2 with_type) (params, name, wk, t)
715
  | MTSigEnd i ->
716
      sigend f i
717

718
719
720
and with_type f (params, name, wk, t) =
  fprintf f "with type %a %a %a"
    typ (TypApp (name, List.map (fun v -> TypVar v) params))
721
722
723
    with_kind wk
    typ t

724
725
and interface_item f item =
  match item with
726
727
  | IIFunctor ([], i) ->
      interface f i
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
  | _ ->
    nl f;
    begin match item with
    | IIFunctor (params, i) ->
        fprintf f "module Make%a%t: %a"
          (list (stretch false) nl) params nl
          sigend i
    | IIExcDecls defs ->
        excdefs true f defs
    | IITypeDecls defs ->
        typedefs f defs
    | IIValDecls decls ->
        pdefs valdecl nothing nothing f decls
    | IIInclude mt ->
        fprintf f "include %a" module_type mt
    | IIModule (name, mt) ->
        fprintf f "module %s : %a" name module_type mt
    | IIComment comment ->
        fprintf f "(* %s *)" comment
    end;
    nl f
749

750
751
752
and sigend f i =
  block "sig%aend" interface f i

753
754
and interface f i =
  list interface_item nothing f i
755

756
757
let program s =
  structure X.f s;
POTTIER Francois's avatar
POTTIER Francois committed
758
  flush X.f
759
760

let interface i =
POTTIER Francois's avatar
POTTIER Francois committed
761
762
  interface X.f i;
  flush X.f
763
764

let expr e =
POTTIER Francois's avatar
POTTIER Francois committed
765
766
  expr X.f e;
  flush X.f
767
768

end
769

770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
(* ------------------------------------------------------------------------- *)
(* Instantiation with output channels. *)

module Make (X : sig
  val f: out_channel
  val locate_stretches: string option
end) = struct
  include PreliminaryMake(struct
    type channel = out_channel
    include X
    let fprintf = Printf.fprintf
    let output_substring = output_substring
  end)
end

(* ------------------------------------------------------------------------- *)
(* Instantiation with buffers. *)

module MakeBuffered (X : sig
  val f: Buffer.t
  val locate_stretches: string option
end) = struct
  include PreliminaryMake(struct
    type channel = Buffer.t
    include X
    let fprintf = Printf.bprintf
    let output_substring = Buffer.add_substring
  end)
end

800
801
802
803
804
805
806
807
808
809
810
(* ------------------------------------------------------------------------- *)
(* Common instantiations. *)

let print_expr f e =
  let module P =
    Make (struct
      let f = f
      let locate_stretches = None
    end)
  in
  P.expr e
811
812
813
814
815
816
817
818
819
820
821

let string_of_expr e =
  let b = Buffer.create 512 in
  let module P =
    MakeBuffered (struct
      let f = b
      let locate_stretches = None
    end)
  in
  P.expr e;
  Buffer.contents b