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