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