src/Tools/Code/code_printer.ML
author wenzelm
Sat Jul 23 16:37:17 2011 +0200 (2011-07-23)
changeset 43947 9b00f09f7721
parent 43326 47cf4bc789aa
child 44788 8b935f1b3cf8
permissions -rw-r--r--
defer evaluation of Scan.message, for improved performance in the frequent situation where failure is handled later (e.g. via ||);
     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 option -> 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 commas: Pretty.T list -> Pretty.T list
    23   val enum: string -> string -> string -> Pretty.T list -> Pretty.T
    24   val enum_default: string -> string -> string -> string -> Pretty.T list -> Pretty.T
    25   val semicolon: Pretty.T list -> Pretty.T
    26   val doublesemicolon: Pretty.T list -> Pretty.T
    27   val indent: int -> Pretty.T -> Pretty.T
    28   val markup_stmt: string -> Pretty.T -> Pretty.T
    29   val format: string list -> int -> Pretty.T -> string
    30 
    31   val first_upper: string -> string
    32   val first_lower: string -> string
    33   type var_ctxt
    34   val make_vars: string list -> var_ctxt
    35   val intro_vars: string list -> var_ctxt -> var_ctxt
    36   val lookup_var: var_ctxt -> string -> string
    37   val intro_base_names: (string -> bool) -> (string -> string)
    38     -> string list -> var_ctxt -> var_ctxt
    39   val aux_params: var_ctxt -> iterm list list -> string list
    40 
    41   type literals
    42   val Literals: { literal_char: string -> string, literal_string: string -> string,
    43         literal_numeral: int -> string,
    44         literal_positive_numeral: int -> string,
    45         literal_alternative_numeral: int -> string,
    46         literal_naive_numeral: int -> string,
    47         literal_list: Pretty.T list -> Pretty.T, infix_cons: int * string }
    48     -> literals
    49   val literal_char: literals -> string -> string
    50   val literal_string: literals -> string -> string
    51   val literal_numeral: literals -> int -> string
    52   val literal_positive_numeral: literals -> int -> string
    53   val literal_alternative_numeral: literals -> int -> string
    54   val literal_naive_numeral: literals -> int -> string
    55   val literal_list: literals -> Pretty.T list -> Pretty.T
    56   val infix_cons: literals -> int * string
    57 
    58   type lrx
    59   val L: lrx
    60   val R: lrx
    61   val X: lrx
    62   type fixity
    63   val BR: fixity
    64   val NOBR: fixity
    65   val INFX: int * lrx -> fixity
    66   val APP: fixity
    67   val brackify: fixity -> Pretty.T list -> Pretty.T
    68   val brackify_infix: int * lrx -> fixity -> Pretty.T * Pretty.T * Pretty.T -> Pretty.T
    69   val brackify_block: fixity -> Pretty.T -> Pretty.T list -> Pretty.T -> Pretty.T
    70   val applify: string -> string -> ('a -> Pretty.T) -> fixity -> Pretty.T -> 'a list -> Pretty.T
    71   val tuplify: (fixity -> 'a -> Pretty.T) -> fixity -> 'a list -> Pretty.T option
    72 
    73   type tyco_syntax
    74   type simple_const_syntax
    75   type complex_const_syntax
    76   type const_syntax
    77   type activated_complex_const_syntax
    78   datatype activated_const_syntax = Plain_const_syntax of int * string
    79     | Complex_const_syntax of activated_complex_const_syntax
    80   val requires_args: const_syntax -> int
    81   val parse_const_syntax: Token.T list -> const_syntax option * Token.T list
    82   val parse_tyco_syntax: Token.T list -> tyco_syntax option * Token.T list
    83   val plain_const_syntax: string -> const_syntax
    84   val simple_const_syntax: simple_const_syntax -> const_syntax
    85   val complex_const_syntax: complex_const_syntax -> const_syntax
    86   val activate_const_syntax: theory -> literals
    87     -> string -> const_syntax -> Code_Thingol.naming -> activated_const_syntax * Code_Thingol.naming
    88   val gen_print_app: (thm option -> var_ctxt -> const * iterm list -> Pretty.T list)
    89     -> (thm option -> var_ctxt -> fixity -> iterm -> Pretty.T)
    90     -> (string -> activated_const_syntax option)
    91     -> thm option -> var_ctxt -> fixity -> const * iterm list -> Pretty.T
    92   val gen_print_bind: (thm option -> var_ctxt -> fixity -> iterm -> Pretty.T)
    93     -> thm option -> fixity
    94     -> iterm -> var_ctxt -> Pretty.T * var_ctxt
    95 end;
    96 
    97 structure Code_Printer : CODE_PRINTER =
    98 struct
    99 
   100 open Code_Thingol;
   101 
   102 (** generic nonsense *)
   103 
   104 fun eqn_error (SOME thm) s =
   105       error (s ^ ",\nin equation " ^ Display.string_of_thm_without_context thm)
   106   | eqn_error NONE s = error s;
   107 
   108 val code_presentationN = "code_presentation";
   109 val stmt_nameN = "stmt_name";
   110 val _ = Markup.add_mode code_presentationN YXML.output_markup;
   111 
   112 
   113 (** assembling and printing text pieces **)
   114 
   115 infixr 5 @@;
   116 infixr 5 @|;
   117 fun x @@ y = [x, y];
   118 fun xs @| y = xs @ [y];
   119 val str = Print_Mode.setmp [] Pretty.str;
   120 val concat = Pretty.block o Pretty.breaks;
   121 val commas = Print_Mode.setmp [] Pretty.commas;
   122 fun enclose l r = Print_Mode.setmp [] (Pretty.enclose l r);
   123 val brackets = enclose "(" ")" o Pretty.breaks;
   124 fun enum sep l r = Print_Mode.setmp [] (Pretty.enum sep l r);
   125 fun enum_default default sep l r [] = str default
   126   | enum_default default sep l r xs = enum sep l r xs;
   127 fun semicolon ps = Pretty.block [concat ps, str ";"];
   128 fun doublesemicolon ps = Pretty.block [concat ps, str ";;"];
   129 fun indent i = Print_Mode.setmp [] (Pretty.indent i);
   130 
   131 fun markup_stmt name = Print_Mode.setmp [code_presentationN]
   132   (Pretty.mark (code_presentationN, [(stmt_nameN, name)]));
   133 
   134 fun filter_presentation [] tree =
   135       Buffer.empty
   136       |> fold XML.add_content tree
   137   | filter_presentation presentation_names tree =
   138       let
   139         fun is_selected (name, attrs) =
   140           name = code_presentationN
   141           andalso member (op =) presentation_names (the (Properties.get attrs stmt_nameN));
   142         fun add_content_with_space tree (is_first, buf) =
   143           buf
   144           |> not is_first ? Buffer.add "\n\n"
   145           |> XML.add_content tree
   146           |> pair false;
   147         fun filter (XML.Elem (name_attrs, xs)) =
   148               fold (if is_selected name_attrs then add_content_with_space else filter) xs
   149           | filter (XML.Text s) = I;
   150       in snd (fold filter tree (true, Buffer.empty)) end;
   151 
   152 fun format presentation_names width =
   153   Print_Mode.setmp [code_presentationN] (Pretty.string_of_margin width)
   154   #> YXML.parse_body
   155   #> filter_presentation presentation_names
   156   #> Buffer.add "\n"
   157   #> Buffer.content;
   158 
   159 
   160 (** names and variable name contexts **)
   161 
   162 type var_ctxt = string Symtab.table * Name.context;
   163 
   164 fun make_vars names = (fold (fn name => Symtab.update_new (name, name)) names Symtab.empty,
   165   Name.make_context names);
   166 
   167 fun intro_vars names (namemap, namectxt) =
   168   let
   169     val (names', namectxt') = fold_map Name.variant names namectxt;
   170     val namemap' = fold2 (curry Symtab.update) names names' namemap;
   171   in (namemap', namectxt') end;
   172 
   173 fun lookup_var (namemap, _) name =
   174   case Symtab.lookup namemap name of
   175     SOME name' => name'
   176   | NONE => error ("Invalid name in context: " ^ quote name);
   177 
   178 val first_upper = implode o nth_map 0 Symbol.to_ascii_upper o raw_explode;
   179 val first_lower = implode o nth_map 0 Symbol.to_ascii_lower o raw_explode;
   180 
   181 fun aux_params vars lhss =
   182   let
   183     fun fish_param _ (w as SOME _) = w
   184       | fish_param (IVar (SOME v)) NONE = SOME v
   185       | fish_param _ NONE = NONE;
   186     fun fillup_param _ (_, SOME v) = v
   187       | fillup_param x (i, NONE) = x ^ string_of_int i;
   188     val fished1 = fold (map2 fish_param) lhss (replicate (length (hd lhss)) NONE);
   189     val x = singleton (Name.variant_list (map_filter I fished1)) "x";
   190     val fished2 = map_index (fillup_param x) fished1;
   191     val (fished3, _) = fold_map Name.variant fished2 Name.context;
   192     val vars' = intro_vars fished3 vars;
   193   in map (lookup_var vars') fished3 end;
   194 
   195 fun intro_base_names no_syntax deresolve names = names
   196   |> map_filter (fn name => if no_syntax name then
   197       let val name' = deresolve name in
   198         if Long_Name.is_qualified name' then NONE else SOME name'
   199       end else NONE)
   200   |> intro_vars;
   201 
   202 
   203 (** pretty literals **)
   204 
   205 datatype literals = Literals of {
   206   literal_char: string -> string,
   207   literal_string: string -> string,
   208   literal_numeral: int -> string,
   209   literal_positive_numeral: int -> string,
   210   literal_alternative_numeral: int -> string,
   211   literal_naive_numeral: int -> string,
   212   literal_list: Pretty.T list -> Pretty.T,
   213   infix_cons: int * string
   214 };
   215 
   216 fun dest_Literals (Literals lits) = lits;
   217 
   218 val literal_char = #literal_char o dest_Literals;
   219 val literal_string = #literal_string o dest_Literals;
   220 val literal_numeral = #literal_numeral o dest_Literals;
   221 val literal_positive_numeral = #literal_positive_numeral o dest_Literals;
   222 val literal_alternative_numeral = #literal_alternative_numeral o dest_Literals;
   223 val literal_naive_numeral = #literal_naive_numeral o dest_Literals;
   224 val literal_list = #literal_list o dest_Literals;
   225 val infix_cons = #infix_cons o dest_Literals;
   226 
   227 
   228 (** syntax printer **)
   229 
   230 (* binding priorities *)
   231 
   232 datatype lrx = L | R | X;
   233 
   234 datatype fixity =
   235     BR
   236   | NOBR
   237   | INFX of (int * lrx);
   238 
   239 val APP = INFX (~1, L);
   240 
   241 fun fixity_lrx L L = false
   242   | fixity_lrx R R = false
   243   | fixity_lrx _ _ = true;
   244 
   245 fun fixity NOBR _ = false
   246   | fixity _ NOBR = false
   247   | fixity (INFX (pr, lr)) (INFX (print_ctxt, lr_ctxt)) =
   248       pr < print_ctxt
   249       orelse pr = print_ctxt
   250         andalso fixity_lrx lr lr_ctxt
   251       orelse print_ctxt = ~1
   252   | fixity BR (INFX _) = false
   253   | fixity _ _ = true;
   254 
   255 fun gen_brackify _ [p] = p
   256   | gen_brackify true (ps as _::_) = enclose "(" ")" ps
   257   | gen_brackify false (ps as _::_) = Pretty.block ps;
   258 
   259 fun brackify fxy_ctxt =
   260   gen_brackify (fixity BR fxy_ctxt) o Pretty.breaks;
   261 
   262 fun brackify_infix infx fxy_ctxt (l, m, r) =
   263   (if fixity (INFX infx) fxy_ctxt then enclose "(" ")" else Pretty.block)
   264     ([l, str " ", m, Pretty.brk 1, r]);
   265 
   266 fun brackify_block fxy_ctxt p1 ps p2 =
   267   let val p = Pretty.block_enclose (p1, p2) ps
   268   in if fixity BR fxy_ctxt
   269     then enclose "(" ")" [p]
   270     else p
   271   end;
   272 
   273 fun applify opn cls f fxy_ctxt p [] = p
   274   | applify opn cls f fxy_ctxt p ps =
   275       (if (fixity BR fxy_ctxt) then enclose "(" ")" else Pretty.block)
   276         (p @@ enum "," opn cls (map f ps));
   277 
   278 fun tuplify _ _ [] = NONE
   279   | tuplify print fxy [x] = SOME (print fxy x)
   280   | tuplify print _ xs = SOME (enum "," "(" ")" (map (print NOBR) xs));
   281 
   282 
   283 (* generic syntax *)
   284 
   285 type tyco_syntax = int * ((fixity -> itype -> Pretty.T)
   286   -> fixity -> itype list -> Pretty.T);
   287 
   288 type simple_const_syntax = int * ((fixity -> iterm -> Pretty.T)
   289   -> fixity -> (iterm * itype) list -> Pretty.T);
   290 
   291 type complex_const_syntax = int * (string list * (literals -> string list
   292   -> (var_ctxt -> fixity -> iterm -> Pretty.T)
   293     -> thm option -> var_ctxt -> fixity -> (iterm * itype) list -> Pretty.T));
   294 
   295 datatype const_syntax = plain_const_syntax of string
   296   | complex_const_syntax of complex_const_syntax;
   297 
   298 fun requires_args (plain_const_syntax _) = 0
   299   | requires_args (complex_const_syntax (k, _)) = k;
   300 
   301 fun simple_const_syntax syn =
   302   complex_const_syntax
   303     (apsnd (fn f => ([], (fn _ => fn _ => fn print => fn _ => fn vars => f (print vars)))) syn);
   304 
   305 type activated_complex_const_syntax = int * ((var_ctxt -> fixity -> iterm -> Pretty.T)
   306   -> thm option -> var_ctxt -> fixity -> (iterm * itype) list -> Pretty.T)
   307 
   308 datatype activated_const_syntax = Plain_const_syntax of int * string
   309   | Complex_const_syntax of activated_complex_const_syntax;
   310 
   311 fun activate_const_syntax thy literals c (plain_const_syntax s) naming =
   312       (Plain_const_syntax (Code.args_number thy c, s), naming)
   313   | activate_const_syntax thy literals c (complex_const_syntax (n, (cs, f))) naming =
   314       fold_map (Code_Thingol.ensure_declared_const thy) cs naming
   315       |-> (fn cs' => pair (Complex_const_syntax (n, f literals cs')));
   316 
   317 fun gen_print_app print_app_expr print_term const_syntax some_thm vars fxy
   318     (app as ((c, (_, function_typs)), ts)) =
   319   case const_syntax c of
   320     NONE => brackify fxy (print_app_expr some_thm vars app)
   321   | SOME (Plain_const_syntax (_, s)) =>
   322       brackify fxy (str s :: map (print_term some_thm vars BR) ts)
   323   | SOME (Complex_const_syntax (k, print)) =>
   324       let
   325         fun print' fxy ts =
   326           print (print_term some_thm) some_thm vars fxy (ts ~~ take k function_typs);
   327       in
   328         if k = length ts
   329         then print' fxy ts
   330         else if k < length ts
   331         then case chop k ts of (ts1, ts2) =>
   332           brackify fxy (print' APP ts1 :: map (print_term some_thm vars BR) ts2)
   333         else print_term some_thm vars fxy (Code_Thingol.eta_expand k app)
   334       end;
   335 
   336 fun gen_print_bind print_term thm (fxy : fixity) pat vars =
   337   let
   338     val vs = Code_Thingol.fold_varnames (insert (op =)) pat [];
   339     val vars' = intro_vars vs vars;
   340   in (print_term thm vars' fxy pat, vars') end;
   341 
   342 
   343 (* mixfix syntax *)
   344 
   345 datatype 'a mixfix =
   346     Arg of fixity
   347   | String of string
   348   | Break;
   349 
   350 fun mk_mixfix prep_arg (fixity_this, mfx) =
   351   let
   352     fun is_arg (Arg _) = true
   353       | is_arg _ = false;
   354     val i = (length o filter is_arg) mfx;
   355     fun fillin _ [] [] =
   356           []
   357       | fillin print (Arg fxy :: mfx) (a :: args) =
   358           (print fxy o prep_arg) a :: fillin print mfx args
   359       | fillin print (String s :: mfx) args =
   360           str s :: fillin print mfx args
   361       | fillin print (Break :: mfx) args =
   362           Pretty.brk 1 :: fillin print mfx args;
   363   in
   364     (i, fn print => fn fixity_ctxt => fn args =>
   365       gen_brackify (fixity fixity_this fixity_ctxt) (fillin print mfx args))
   366   end;
   367 
   368 fun parse_infix prep_arg (x, i) s =
   369   let
   370     val l = case x of L => INFX (i, L) | _ => INFX (i, X);
   371     val r = case x of R => INFX (i, R) | _ => INFX (i, X);
   372   in
   373     mk_mixfix prep_arg (INFX (i, x), [Arg l, String " ", String s, Break, Arg r])
   374   end;
   375 
   376 fun parse_mixfix mk_plain mk_complex prep_arg s =
   377   let
   378     val sym_any = Scan.one Symbol.is_regular;
   379     val parse = Scan.optional ($$ "!" >> K true) false -- Scan.repeat (
   380          ($$ "(" -- $$ "_" -- $$ ")" >> K (Arg NOBR))
   381       || ($$ "_" >> K (Arg BR))
   382       || ($$ "/" |-- Scan.repeat ($$ " ") >> (K Break))
   383       || (Scan.repeat1
   384            (   $$ "'" |-- sym_any
   385             || Scan.unless ($$ "_" || $$ "/" || $$ "(" |-- $$ "_" |-- $$ ")")
   386                  sym_any) >> (String o implode)));
   387     fun err s (_, NONE) = (fn () => "malformed mixfix annotation: " ^ quote s)
   388       | err _ (_, SOME msg) = msg;
   389   in
   390     case Scan.finite Symbol.stopper parse (Symbol.explode s) of
   391       ((false, [String s]), []) => mk_plain s
   392     | ((_, p as [_]), []) => mk_complex (mk_mixfix prep_arg (NOBR, p))
   393     | ((b, p as _ :: _ :: _), []) => mk_complex (mk_mixfix prep_arg (if b then NOBR else BR, p))
   394     | _ => Scan.!! (err s) Scan.fail ()
   395   end;
   396 
   397 val (infixK, infixlK, infixrK) = ("infix", "infixl", "infixr");
   398 
   399 fun parse_syntax mk_plain mk_complex prep_arg =
   400   Scan.option (
   401       ((Parse.$$$ infixK >> K X)
   402         || (Parse.$$$ infixlK >> K L)
   403         || (Parse.$$$ infixrK >> K R))
   404         -- Parse.nat -- Parse.string
   405         >> (fn ((x, i), s) => mk_complex (parse_infix prep_arg (x, i) s))
   406       || Parse.string >> (fn s => (parse_mixfix mk_plain mk_complex prep_arg s)));
   407 
   408 val _ = List.app Keyword.keyword [infixK, infixlK, infixrK];
   409 
   410 fun parse_tyco_syntax x = parse_syntax (fn s => (0, (K o K o K o str) s)) I I x;
   411 
   412 val parse_const_syntax = parse_syntax plain_const_syntax simple_const_syntax fst;
   413 
   414 end; (*struct*)