printer.ml 16.7 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
(* A pretty-printer for [IL]. *)

open IL
open Printf

module Make (X : sig

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

  val f: out_channel

  (* If [raw_stretch_action] is set, then we print the semantic actions
     as they are found into the original source code. *)
  val raw_stretch_action: bool

  (* This controls the way we print Objective Caml stretches (types and
     semantic actions). We either surround them with #line directives
     (for better error reports if the generated code is ill - typed) or
     don't (for better readability). The value is either [None] -- do
     not provide #line directives -- or [Some filename] -- do provide
     them. [filename] is the name of the file that is being written
     to. *)

  val locate_stretches: string option

end) = struct

(* ------------------------------------------------------------------------- *)
(* 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
53
  output_substring f whitespace 0 !indentation
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

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

(* This produces a #line directive. *)

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

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

72
let nothing _ =
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  ()

let space f =
  output_char f ' '

let comma f =
  output_string f ", "

let seminl f =
  output_char f ';';
  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. *)

112 113
(* A list with a separator in front of every element. *)

114 115 116 117 118 119
let rec list elem sep f = function
  | [] ->
      ()
  | e :: es ->
      fprintf f "%t%a%a" sep elem e (list elem sep) es

120 121 122 123 124 125 126 127 128 129
(* 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. *)

130
let typeparams p0 p1 f = function
131 132 133 134
  | [] ->
      ()
  | [ param ] ->
      fprintf f "%a " p0 param
135 136
  | _ :: _ as params ->
      fprintf f "(%a) " (seplist p1 comma) params
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317

(* ------------------------------------------------------------------------- *)
(* 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
	match k with
	| AllButFunTryMatch
	| AllButFunTryMatchSeq
	| AllButLetFunTryMatch
	| AllButLetFunTryMatchSeq
	| OnlyAppOrAtom
	| OnlyAtom ->
	    false
	| _ ->
	    true
      end
  | ELet ([], e) ->
      member e k
  | ELet ((PUnit, _) :: _, _) ->
      begin
	match k with
	| AllButSeq
	| AllButFunTryMatchSeq
	| AllButLetFunTryMatchSeq
	| AllButIfThenSeq
	| OnlyAppOrAtom
	| OnlyAtom ->
	    false
	| _ ->
	    true
      end
  | ELet (_ :: _, _) ->
      begin
	match k with
	| AllButLetFunTryMatch
	| AllButLetFunTryMatchSeq
	| OnlyAppOrAtom
	| OnlyAtom ->
	    false
	| _ ->
	    true
      end
  | EIfThen _ ->
      begin
	match k with
	| AllButIfThenSeq
	| OnlyAppOrAtom
	| OnlyAtom ->
	    false
	| _ ->
	    true
      end
  | EApp (_, _ :: _)
  | EData (_, _ :: _)
  | EMagic _
  | ERepr _
  | ERaise _ ->
      begin
	match k with
	| OnlyAtom ->
	    false
	| _ ->
	    true
      end
  | ERecordWrite _
  | EIfThenElse _ ->
      begin
	match k with
	| OnlyAppOrAtom
	| OnlyAtom ->
	    false
	| _ ->
	    true
      end
  | EVar _
  | ETextual _
  | EApp (_, [])
  | EData (_, [])
  | ETuple _
  | EAnnot _
  | ERecord _
  | ERecordAccess (_, _)
  | EIntConst _
  | EMaxInt
  | 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"
	id1 (list pat0 space) ps1 (indent 2 expr) e1 nl nl (exprlet k pes) e2
  | (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) ->
	if Settings.comment then
	  fprintf f "(* %s *)%t%a" c nl (exprk k) e
	else
	  exprk k f e
    | EPatComment (s, p, e) ->
	if Settings.comment then
	  fprintf f "(* %s%a *)%t%a" s pat p nl (exprk k) e
	else
	  exprk k f e
    | ELet (pes, e2) ->
	exprlet k pes f e2
    | ERecordWrite (e1, field, e2) ->
	fprintf f "%a.%s <- %a" atom e1 field (exprk (andNotSeq k)) e2
318
    | EMatch (_, []) ->
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
	assert false
    | EMatch (e, brs) ->
	fprintf f "match %a with%a" expr e (branches k) brs
    | ETry (_, []) ->
	assert false
    | ETry (e, brs) ->
	fprintf f "try%a%twith%a" (indent 2 expr) e nl (branches k) brs
    | EIfThen (e1, e2) ->
	fprintf f "if %a then%a" expr e1 (indent 2 (exprk (andNotSeq k))) e2
    | EIfThenElse (e0, e1, e2) ->
	fprintf f "if %a then%a%telse%a"
          expr e0 (indent 2 (exprk AllButIfThenSeq)) e1 nl (indent 2 (exprk (andNotSeq k))) e2
    | EFun (ps, e) ->
	fprintf f "fun%a ->%a" (list pat0 space) ps (indent 2 (exprk k)) e
    | EApp (EVar op, [ e1; e2 ])
      when op.[0] = '(' && op.[String.length op - 1] = ')' ->
	let op = String.sub op 1 (String.length op - 2) in
	fprintf f "%a %s %a" app e1 op app e2
    | EApp (e, args) ->
	fprintf f "%a%a" app e (list atom space) args
    | ERaise e ->
	fprintf f "raise %a" atom e
    | EMagic e ->
	fprintf f "Obj.magic %a" atom e
    | ERepr e ->
	fprintf f "Obj.repr %a" atom e
    | EData (d, []) ->
	var f d
    | EData (d, [ arg ]) ->
	fprintf f "%s %a" d atom arg
349 350
    | EData (d, (_ :: _ :: _ as args)) ->
	fprintf f "%s (%a)" d (seplist app comma) args
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    | EVar v ->
	var f v
    | ETextual action ->
	stretch (X.raw_stretch_action) f action
    | EUnit ->
	fprintf f "()"
    | EIntConst k ->
	if k >= 0 then
	  fprintf f "%d" k
	else
	  fprintf f "(%d)" k
    | EMaxInt ->
        fprintf f "max_int"
    | EStringConst s ->
	fprintf f "\"%s\"" (String.escaped s)
    | ETuple [] ->
	assert false
    | ETuple [ e ] ->
	atom f e
370 371
    | ETuple (_ :: _ :: _ as es) ->
	fprintf f "(%a)" (seplist app comma) es
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    | EAnnot (e, s) ->
	(* 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 *)
    | ERecordAccess (e, field) ->
	fprintf f "%a.%s" atom e field
    | ERecord fs ->
	fprintf f "{%a}" (indent 2 (list field nothing)) fs
    | EArray fs ->
	fprintf f "[|%a|]" (indent 2 (list array_field nothing)) fs
    | EArrayAccess (e, i) ->
	fprintf f "%a.(%a)" atom e expr i
  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
395
      output_substring f whitespace 0 !indentation
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
  | 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) =
  fprintf f "%s = %a%t" label app e seminl

and fpats f fps =
  list fpat nothing f fps

and fpat f = function
  | (_, PWildcard) ->
      () (* in a record pattern, fields can be omitted *)
  | (label, p) ->
      fprintf f "%s = %a%t" label pat p seminl

and array_field f e =
  fprintf f "%a%t" app e seminl

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
438 439
  | PTuple (_ :: _ :: _ as ps) ->
      fprintf f "(%a)" (seplist pat1 comma) ps
440 441 442 443 444 445 446 447 448 449
  | PAnnot (p, t) ->
      fprintf f "(%a : %a)" pat p typ t
  | PRecord fps ->
      fprintf f "{%a}" (indent 2 fpats) fps
  | p ->
      fprintf f "(%a)" pat p

and pat1 f = function
  | PData (d, [ arg ]) ->
      fprintf f "%s %a" d pat0 arg
450 451
  | PData (d, (_ :: _ :: _ as args)) ->
      fprintf f "%s (%a)" d (seplist pat1 comma) args
452 453 454 455 456 457 458 459
  | PTuple [ p ] ->
      pat1 f p
  | p ->
      pat0 f p

and pat2 f = function
  | POr [] ->
      assert false
460 461
  | POr (_ :: _ as ps) ->
      fprintf f "%a" (seplist pat2 bar) ps
462 463 464 465 466 467 468 469
  | PTuple [ p ] ->
      pat2 f p
  | p ->
      pat1 f p

and pat f p =
  pat2 f p

470 471 472 473 474
and typevar f = function
  | "_" ->
      fprintf f "_"
  | v ->
      fprintf f "'%s" v
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

and typ0 f = function
  | TypTextual (Stretch.Declared ocamltype) ->
      (* Parentheses are necessary to avoid confusion between 1 - ary
	 data constructor with n arguments and n - ary data constructor. *)
      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
494 495
  | TypTuple (_ :: _ as ts) ->
      seplist typ0 times f ts
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
  | 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. *)

let datavalparams f = function
  | [] ->
      ()
  | valparam :: valparams ->
522 523 524
      (* [typ1] because [type t = A of  int -> int ] is not allowed by OCaml *)
      (*                [type t = A of (int -> int)] is allowed *)
      fprintf f " of %a%a" typ1 valparam (list typ1 times) valparams
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 558 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 588

let datatypeparams f = function
  | None ->
      ()
  | Some typs ->
      fprintf f "(* %a*)" (list typ space) typs (* TEMPORARY not great *)

let datadef f def =
  fprintf f "  | %s%a%a" def.dataname datavalparams def.datavalparams datatypeparams def.datatypeparams

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

let typerhs f = function
  | TDefRecord [] ->
      assert false
  | TDefRecord (field :: fields) ->
      fprintf f " = {%t%a%a%t}" nl fielddef field (list fielddef seminl) fields nl
  | TDefSum [] ->
      ()
  | TDefSum defs ->
      fprintf f " = %a" (list datadef nl) defs
  | 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 =
  fprintf f "%a%s%a%a%t%t"
    (typeparams typevar typevar) def.typeparams
    def.typename
    typerhs def.typerhs
    typeconstraint def.typeconstraint
    nl nl

let rec pdefs pdef sep1 sep2 f = function
  | [] ->
      ()
  | def :: defs ->
      fprintf f "%t%a%a" sep1 pdef def (pdefs pdef sep2 sep2) defs

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

let valdefs =
  pdefs valdef letrec et

let nonrecvaldefs =
  pdefs valdef letnonrec letnonrec

let typedefs =
  pdefs typedef keytyp et

589 590
(* unused for now:

591 592 593 594 595 596 597 598 599
let directive f = function
  | DirOpen s ->
      fprintf f "open %s%t%t" s nl nl
  | DirInclude s ->
      fprintf f "include %s%t%t" s nl nl

let directives =
  pdefs directive nothing nothing

600 601
*)

602 603 604 605
let excdef in_intf f def =
  match in_intf, def.exceq with
  | _, None
  | true, Some _ ->
606
      fprintf f "%s%t%t" def.excname nl nl
607
  | false, Some s ->
608 609
      fprintf f "%s = %s%t%t" def.excname s nl nl

610 611
let excdefs in_intf =
  pdefs (excdef in_intf) exc exc
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

let functorparams intf body b f params =
  match params with
  | [] ->
      fprintf f "%a%!" body b
  | _ ->
      fprintf f "module Make%a%t%s%t%a%t%tend%t%!"
	(list (stretch false) nl) params
	nl (if intf then ": sig" else "= struct") nl
	(indent 2 body) b
	nl nl nl

let structure f p =
  fprintf f "struct%aend" (
    indent 2 (fun f p ->
      fprintf f "%t%a%a%a"
	nl
629
	(excdefs false) p.struct_excdefs
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
	typedefs p.struct_typedefs
	nonrecvaldefs p.struct_nonrecvaldefs
    )
  ) p

let rec modexpr f = function
  | MVar x ->
      fprintf f "%s" x
  | MStruct s ->
      structure f s
  | MApp (e1, e2) ->
      fprintf f "%a (%a)" modexpr e1 modexpr e2

let moduledef f d =
  fprintf f "module %s = %a%t%t" d.modulename modexpr d.modulerhs nl nl

let program f p =
  fprintf f "%a%a"
648
    (excdefs false) p.excdefs
649 650 651 652 653 654 655 656 657
    typedefs p.typedefs;
  List.iter (stretch false f) p.prologue;
  fprintf f "%a%a%a"
    nonrecvaldefs p.nonrecvaldefs
    (list moduledef nothing) p.moduledefs
    valdefs p.valdefs;
  List.iter (output_string f) p.postlogue

let valdecl f (x, ts) =
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
  fprintf f "val %s: %a%t%t" x typ ts.body nl nl

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
  | MTWithType (mt, name, wk, t) ->
      fprintf f "%a%a"
        module_type mt
        (indent 2 with_type) (name, wk, t)
  | MTSigEnd i ->
      fprintf f "sig%aend" (
        indent 2 (fun f i ->
          fprintf f "%t%a"
            nl
            interface i
        )
      ) i

and with_type f (name, wk, t) =
  fprintf f "with type %s %a %a"
    name
    with_kind wk
    typ t

and interface_item f = function
689 690 691 692 693 694 695
  | IIFunctor (params, i) ->
      functorparams true interface i f params
  | IIExcDecls defs ->
      excdefs true f defs
  | IITypeDecls defs ->
      typedefs f defs
  | IIValDecls decls ->
696 697 698 699 700
      pdefs valdecl nothing nothing f decls
  | IIInclude mt ->
      fprintf f "include %a%t%t" module_type mt nl nl
  | IIModule (name, mt) ->
      fprintf f "module %s : %a%t%t" name module_type mt nl nl
701 702
  | IIComment comment ->
      fprintf f "(* %s *)%t" comment nl
703 704 705

and interface f i =
  list interface_item nothing f i
706 707 708 709 710

let program p =
  functorparams false program p X.f p.paramdefs

let interface i =
711
  interface X.f i
712 713 714 715 716

let expr e =
  expr X.f e

end