src/Tools/Code/code_printer.ML
author haftmann
Mon Jan 04 14:09:56 2010 +0100 (2010-01-04)
changeset 34244 03f8dcab55f3
parent 34178 a78b8d5b91cb
child 34247 d2803c7f6d52
permissions -rw-r--r--
code cache without copy; tuned
     1 (*  Title:      Tools/code/code_printer.ML
     2     Author:     Florian Haftmann, TU Muenchen
     3 
     4 Generic operations for pretty printing of target language code.
     5 *)
     6 
     7 signature CODE_PRINTER =
     8 sig
     9   type itype = Code_Thingol.itype
    10   type iterm = Code_Thingol.iterm
    11   type const = Code_Thingol.const
    12   type dict = Code_Thingol.dict
    13 
    14   val eqn_error: thm -> string -> 'a
    15 
    16   val @@ : 'a * 'a -> 'a list
    17   val @| : 'a list * 'a -> 'a list
    18   val str: string -> Pretty.T
    19   val concat: Pretty.T list -> Pretty.T
    20   val brackets: Pretty.T list -> Pretty.T
    21   val enclose: string -> string -> Pretty.T list -> Pretty.T
    22   val enum: string -> string -> string -> Pretty.T list -> Pretty.T
    23   val enum_default: string -> string -> string -> string -> Pretty.T list -> Pretty.T
    24   val semicolon: Pretty.T list -> Pretty.T
    25   val doublesemicolon: Pretty.T list -> Pretty.T
    26   val indent: int -> Pretty.T -> Pretty.T
    27   val string_of_pretty: int -> Pretty.T -> string
    28   val writeln_pretty: int -> Pretty.T -> unit
    29 
    30   val first_upper: string -> string
    31   val first_lower: string -> string
    32   type var_ctxt
    33   val make_vars: string list -> var_ctxt
    34   val intro_vars: string list -> var_ctxt -> var_ctxt
    35   val lookup_var: var_ctxt -> string -> string
    36   val intro_base_names: (string -> bool) -> (string -> string)
    37     -> string list -> var_ctxt -> var_ctxt
    38   val aux_params: var_ctxt -> iterm list list -> string list
    39 
    40   type literals
    41   val Literals: { literal_char: string -> string, literal_string: string -> string,
    42         literal_numeral: bool -> int -> string,
    43         literal_list: Pretty.T list -> Pretty.T, infix_cons: int * string }
    44     -> literals
    45   val literal_char: literals -> string -> string
    46   val literal_string: literals -> string -> string
    47   val literal_numeral: literals -> bool -> int -> string
    48   val literal_list: literals -> Pretty.T list -> Pretty.T
    49   val infix_cons: literals -> int * string
    50 
    51   type lrx
    52   val L: lrx
    53   val R: lrx
    54   val X: lrx
    55   type fixity
    56   val BR: fixity
    57   val NOBR: fixity
    58   val INFX: int * lrx -> fixity
    59   val APP: fixity
    60   val brackify: fixity -> Pretty.T list -> Pretty.T
    61   val brackify_infix: int * lrx -> fixity -> Pretty.T list -> Pretty.T
    62   val brackify_block: fixity -> Pretty.T -> Pretty.T list -> Pretty.T -> Pretty.T
    63 
    64   type tyco_syntax
    65   type simple_const_syntax
    66   type proto_const_syntax
    67   type const_syntax
    68   val parse_infix: ('a -> 'b) -> lrx * int -> string
    69     -> int * ((fixity -> 'b -> Pretty.T)
    70     -> fixity -> 'a list -> Pretty.T)
    71   val parse_syntax: ('a -> 'b) -> OuterParse.token list
    72     -> (int * ((fixity -> 'b -> Pretty.T)
    73     -> fixity -> 'a list -> Pretty.T)) option * OuterParse.token list
    74   val simple_const_syntax: simple_const_syntax -> proto_const_syntax
    75   val activate_const_syntax: theory -> literals
    76     -> proto_const_syntax -> Code_Thingol.naming -> const_syntax * Code_Thingol.naming
    77   val gen_print_app: (thm -> var_ctxt -> const * iterm list -> Pretty.T list)
    78     -> (thm -> var_ctxt -> fixity -> iterm -> Pretty.T)
    79     -> (string -> const_syntax option)
    80     -> thm -> var_ctxt -> fixity -> const * iterm list -> Pretty.T
    81   val gen_print_bind: (thm -> var_ctxt -> fixity -> iterm -> Pretty.T)
    82     -> thm -> fixity
    83     -> iterm -> var_ctxt -> Pretty.T * var_ctxt
    84 
    85   val mk_name_module: Name.context -> string option -> (string -> string option)
    86     -> 'a Graph.T -> string -> string
    87   val dest_name: string -> string * string
    88 end;
    89 
    90 structure Code_Printer : CODE_PRINTER =
    91 struct
    92 
    93 open Code_Thingol;
    94 
    95 fun eqn_error thm s = error (s ^ ",\nin equation " ^ Display.string_of_thm_without_context thm);
    96 
    97 (** assembling and printing text pieces **)
    98 
    99 infixr 5 @@;
   100 infixr 5 @|;
   101 fun x @@ y = [x, y];
   102 fun xs @| y = xs @ [y];
   103 val str = PrintMode.setmp [] Pretty.str;
   104 val concat = Pretty.block o Pretty.breaks;
   105 fun enclose l r = PrintMode.setmp [] (Pretty.enclose l r);
   106 val brackets = enclose "(" ")" o Pretty.breaks;
   107 fun enum sep l r = PrintMode.setmp [] (Pretty.enum sep l r);
   108 fun enum_default default sep l r [] = str default
   109   | enum_default default sep l r xs = enum sep l r xs;
   110 fun semicolon ps = Pretty.block [concat ps, str ";"];
   111 fun doublesemicolon ps = Pretty.block [concat ps, str ";;"];
   112 fun indent i = PrintMode.setmp [] (Pretty.indent i);
   113 
   114 fun string_of_pretty width p = PrintMode.setmp [] (Pretty.setmp_margin_CRITICAL width Pretty.string_of) p ^ "\n";
   115 fun writeln_pretty width p = PrintMode.setmp [] (Pretty.setmp_margin_CRITICAL width Pretty.writeln) p;
   116 
   117 
   118 (** names and variable name contexts **)
   119 
   120 type var_ctxt = string Symtab.table * Name.context;
   121 
   122 fun make_vars names = (fold (fn name => Symtab.update_new (name, name)) names Symtab.empty,
   123   Name.make_context names);
   124 
   125 fun intro_vars names (namemap, namectxt) =
   126   let
   127     val (names', namectxt') = Name.variants names namectxt;
   128     val namemap' = fold2 (curry Symtab.update) names names' namemap;
   129   in (namemap', namectxt') end;
   130 
   131 fun lookup_var (namemap, _) name = case Symtab.lookup namemap name
   132  of SOME name' => name'
   133   | NONE => error ("Invalid name in context: " ^ quote name);
   134 
   135 val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o explode;
   136 val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o explode;
   137 
   138 fun aux_params vars lhss =
   139   let
   140     fun fish_param _ (w as SOME _) = w
   141       | fish_param (IVar (SOME v)) NONE = SOME v
   142       | fish_param _ NONE = NONE;
   143     fun fillup_param _ (_, SOME v) = v
   144       | fillup_param x (i, NONE) = x ^ string_of_int i;
   145     val fished1 = fold (map2 fish_param) lhss (replicate (length (hd lhss)) NONE);
   146     val x = Name.variant (map_filter I fished1) "x";
   147     val fished2 = map_index (fillup_param x) fished1;
   148     val (fished3, _) = Name.variants fished2 Name.context;
   149     val vars' = intro_vars fished3 vars;
   150   in map (lookup_var vars') fished3 end;
   151 
   152 fun intro_base_names no_syntax deresolve names = names 
   153   |> map_filter (fn name => if no_syntax name then
   154       let val name' = deresolve name in
   155         if Long_Name.is_qualified name' then NONE else SOME name'
   156       end else NONE)
   157   |> intro_vars;
   158 
   159 
   160 (** pretty literals **)
   161 
   162 datatype literals = Literals of {
   163   literal_char: string -> string,
   164   literal_string: string -> string,
   165   literal_numeral: bool -> int -> string,
   166   literal_list: Pretty.T list -> Pretty.T,
   167   infix_cons: int * string
   168 };
   169 
   170 fun dest_Literals (Literals lits) = lits;
   171 
   172 val literal_char = #literal_char o dest_Literals;
   173 val literal_string = #literal_string o dest_Literals;
   174 val literal_numeral = #literal_numeral o dest_Literals;
   175 val literal_list = #literal_list o dest_Literals;
   176 val infix_cons = #infix_cons o dest_Literals;
   177 
   178 
   179 (** syntax printer **)
   180 
   181 (* binding priorities *)
   182 
   183 datatype lrx = L | R | X;
   184 
   185 datatype fixity =
   186     BR
   187   | NOBR
   188   | INFX of (int * lrx);
   189 
   190 val APP = INFX (~1, L);
   191 
   192 fun fixity_lrx L L = false
   193   | fixity_lrx R R = false
   194   | fixity_lrx _ _ = true;
   195 
   196 fun fixity NOBR _ = false
   197   | fixity _ NOBR = false
   198   | fixity (INFX (pr, lr)) (INFX (print_ctxt, lr_ctxt)) =
   199       pr < print_ctxt
   200       orelse pr = print_ctxt
   201         andalso fixity_lrx lr lr_ctxt
   202       orelse print_ctxt = ~1
   203   | fixity BR (INFX _) = false
   204   | fixity _ _ = true;
   205 
   206 fun gen_brackify _ [p] = p
   207   | gen_brackify true (ps as _::_) = enclose "(" ")" ps
   208   | gen_brackify false (ps as _::_) = Pretty.block ps;
   209 
   210 fun brackify fxy_ctxt =
   211   gen_brackify (fixity BR fxy_ctxt) o Pretty.breaks;
   212 
   213 fun brackify_infix infx fxy_ctxt =
   214   gen_brackify (fixity (INFX infx) fxy_ctxt) o Pretty.breaks;
   215 
   216 fun brackify_block fxy_ctxt p1 ps p2 =
   217   let val p = Pretty.block_enclose (p1, p2) ps
   218   in if fixity BR fxy_ctxt
   219     then enclose "(" ")" [p]
   220     else p
   221   end;
   222 
   223 
   224 (* generic syntax *)
   225 
   226 type tyco_syntax = int * ((fixity -> itype -> Pretty.T)
   227   -> fixity -> itype list -> Pretty.T);
   228 
   229 type simple_const_syntax = int * ((fixity -> iterm -> Pretty.T)
   230   -> fixity -> (iterm * itype) list -> Pretty.T);
   231 type proto_const_syntax = int * (string list * (literals -> string list
   232   -> (var_ctxt -> fixity -> iterm -> Pretty.T)
   233     -> thm -> var_ctxt -> fixity -> (iterm * itype) list -> Pretty.T));
   234 type const_syntax = int * ((var_ctxt -> fixity -> iterm -> Pretty.T)
   235   -> thm -> var_ctxt -> fixity -> (iterm * itype) list -> Pretty.T);
   236 
   237 fun simple_const_syntax syn =
   238   apsnd (fn f => ([], (fn _ => fn _ => fn print => fn _ => fn vars => f (print vars)))) syn;
   239 
   240 fun activate_const_syntax thy literals (n, (cs, f)) naming =
   241   fold_map (Code_Thingol.ensure_declared_const thy) cs naming
   242   |-> (fn cs' => pair (n, f literals cs'));
   243 
   244 fun gen_print_app print_app_expr print_term syntax_const thm vars fxy (app as ((c, (_, tys)), ts)) =
   245   case syntax_const c
   246    of NONE => brackify fxy (print_app_expr thm vars app)
   247     | SOME (k, print) =>
   248         let
   249           fun print' fxy ts = print (print_term thm) thm vars fxy (ts ~~ take k tys);
   250         in if k = length ts
   251           then print' fxy ts
   252         else if k < length ts
   253           then case chop k ts of (ts1, ts2) =>
   254             brackify fxy (print' APP ts1 :: map (print_term thm vars BR) ts2)
   255           else print_term thm vars fxy (Code_Thingol.eta_expand k app)
   256         end;
   257 
   258 fun gen_print_bind print_term thm (fxy : fixity) pat vars =
   259   let
   260     val vs = Code_Thingol.fold_varnames (insert (op =)) pat [];
   261     val vars' = intro_vars vs vars;
   262   in (print_term thm vars' fxy pat, vars') end;
   263 
   264 
   265 (* mixfix syntax *)
   266 
   267 datatype 'a mixfix =
   268     Arg of fixity
   269   | Pretty of Pretty.T;
   270 
   271 fun mk_mixfix prep_arg (fixity_this, mfx) =
   272   let
   273     fun is_arg (Arg _) = true
   274       | is_arg _ = false;
   275     val i = (length o filter is_arg) mfx;
   276     fun fillin _ [] [] =
   277           []
   278       | fillin print (Arg fxy :: mfx) (a :: args) =
   279           (print fxy o prep_arg) a :: fillin print mfx args
   280       | fillin print (Pretty p :: mfx) args =
   281           p :: fillin print mfx args;
   282   in
   283     (i, fn print => fn fixity_ctxt => fn args =>
   284       gen_brackify (fixity fixity_this fixity_ctxt) (fillin print mfx args))
   285   end;
   286 
   287 fun parse_infix prep_arg (x, i) s =
   288   let
   289     val l = case x of L => INFX (i, L) | _ => INFX (i, X);
   290     val r = case x of R => INFX (i, R) | _ => INFX (i, X);
   291   in
   292     mk_mixfix prep_arg (INFX (i, x),
   293       [Arg l, (Pretty o Pretty.brk) 1, (Pretty o str) s, (Pretty o Pretty.brk) 1, Arg r])
   294   end;
   295 
   296 fun parse_mixfix prep_arg s =
   297   let
   298     val sym_any = Scan.one Symbol.is_regular;
   299     val parse = Scan.optional ($$ "!" >> K true) false -- Scan.repeat (
   300          ($$ "(" -- $$ "_" -- $$ ")" >> K (Arg NOBR))
   301       || ($$ "_" >> K (Arg BR))
   302       || ($$ "/" |-- Scan.repeat ($$ " ") >> (Pretty o Pretty.brk o length))
   303       || (Scan.repeat1
   304            (   $$ "'" |-- sym_any
   305             || Scan.unless ($$ "_" || $$ "/" || $$ "(" |-- $$ "_" |-- $$ ")")
   306                  sym_any) >> (Pretty o str o implode)));
   307   in case Scan.finite Symbol.stopper parse (Symbol.explode s)
   308    of ((_, p as [_]), []) => mk_mixfix prep_arg (NOBR, p)
   309     | ((b, p as _ :: _ :: _), []) => mk_mixfix prep_arg (if b then NOBR else BR, p)
   310     | _ => Scan.!!
   311         (the_default ("malformed mixfix annotation: " ^ quote s) o snd) Scan.fail ()
   312   end;
   313 
   314 val (infixK, infixlK, infixrK) = ("infix", "infixl", "infixr");
   315 
   316 fun parse_syntax prep_arg xs =
   317   Scan.option ((
   318       ((OuterParse.$$$ infixK >> K X)
   319         || (OuterParse.$$$ infixlK >> K L)
   320         || (OuterParse.$$$ infixrK >> K R))
   321         -- OuterParse.nat >> parse_infix prep_arg
   322       || Scan.succeed (parse_mixfix prep_arg))
   323       -- OuterParse.string
   324       >> (fn (parse, s) => parse s)) xs;
   325 
   326 val _ = List.app OuterKeyword.keyword [infixK, infixlK, infixrK];
   327 
   328 
   329 (** module name spaces **)
   330 
   331 val dest_name =
   332   apfst Long_Name.implode o split_last o fst o split_last o Long_Name.explode;
   333 
   334 fun mk_name_module reserved module_prefix module_alias program =
   335   let
   336     fun mk_alias name = case module_alias name
   337      of SOME name' => name'
   338       | NONE => name
   339           |> Long_Name.explode
   340           |> map (fn name => (the_single o fst) (Name.variants [name] reserved))
   341           |> Long_Name.implode;
   342     fun mk_prefix name = case module_prefix
   343      of SOME module_prefix => Long_Name.append module_prefix name
   344       | NONE => name;
   345     val tab =
   346       Symtab.empty
   347       |> Graph.fold ((fn name => Symtab.default (name, (mk_alias #> mk_prefix) name))
   348            o fst o dest_name o fst)
   349              program
   350   in the o Symtab.lookup tab end;
   351 
   352 end; (*struct*)