src/HOL/Tools/list_code.ML
author haftmann
Wed May 06 19:09:31 2009 +0200 (2009-05-06)
changeset 31055 2cf6efca6c71
child 37242 97097e589715
permissions -rw-r--r--
proper structures for list and string code generation stuff
haftmann@31055
     1
(* Author: Florian Haftmann, TU Muenchen
haftmann@31055
     2
haftmann@31055
     3
Code generation for list literals.
haftmann@31055
     4
*)
haftmann@31055
     5
haftmann@31055
     6
signature LIST_CODE =
haftmann@31055
     7
sig
haftmann@31055
     8
  val implode_list: string -> string -> Code_Thingol.iterm -> Code_Thingol.iterm list option
haftmann@31055
     9
  val default_list: int * string
haftmann@31055
    10
    -> (Code_Printer.fixity -> Code_Thingol.iterm -> Pretty.T)
haftmann@31055
    11
    -> Code_Printer.fixity -> Code_Thingol.iterm -> Code_Thingol.iterm -> Pretty.T
haftmann@31055
    12
  val add_literal_list: string -> theory -> theory
haftmann@31055
    13
end;
haftmann@31055
    14
haftmann@31055
    15
structure List_Code : LIST_CODE =
haftmann@31055
    16
struct
haftmann@31055
    17
haftmann@31055
    18
open Basic_Code_Thingol;
haftmann@31055
    19
haftmann@31055
    20
fun implode_list nil' cons' t =
haftmann@31055
    21
  let
haftmann@31055
    22
    fun dest_cons (IConst (c, _) `$ t1 `$ t2) =
haftmann@31055
    23
          if c = cons'
haftmann@31055
    24
          then SOME (t1, t2)
haftmann@31055
    25
          else NONE
haftmann@31055
    26
      | dest_cons _ = NONE;
haftmann@31055
    27
    val (ts, t') = Code_Thingol.unfoldr dest_cons t;
haftmann@31055
    28
  in case t'
haftmann@31055
    29
   of IConst (c, _) => if c = nil' then SOME ts else NONE
haftmann@31055
    30
    | _ => NONE
haftmann@31055
    31
  end;
haftmann@31055
    32
haftmann@31055
    33
fun default_list (target_fxy, target_cons) pr fxy t1 t2 =
haftmann@31055
    34
  Code_Printer.brackify_infix (target_fxy, Code_Printer.R) fxy [
haftmann@31055
    35
    pr (Code_Printer.INFX (target_fxy, Code_Printer.X)) t1,
haftmann@31055
    36
    Code_Printer.str target_cons,
haftmann@31055
    37
    pr (Code_Printer.INFX (target_fxy, Code_Printer.R)) t2
haftmann@31055
    38
  ];
haftmann@31055
    39
haftmann@31055
    40
fun add_literal_list target =
haftmann@31055
    41
  let
haftmann@31055
    42
    fun pretty literals [nil', cons'] pr thm vars fxy [(t1, _), (t2, _)] =
haftmann@31055
    43
      case Option.map (cons t1) (implode_list nil' cons' t2)
haftmann@31055
    44
       of SOME ts =>
haftmann@31055
    45
            Code_Printer.literal_list literals (map (pr vars Code_Printer.NOBR) ts)
haftmann@31055
    46
        | NONE =>
haftmann@31055
    47
            default_list (Code_Printer.infix_cons literals) (pr vars) fxy t1 t2;
haftmann@31055
    48
  in Code_Target.add_syntax_const target
haftmann@31055
    49
    @{const_name Cons} (SOME (2, ([@{const_name Nil}, @{const_name Cons}], pretty)))
haftmann@31055
    50
  end
haftmann@31055
    51
haftmann@31055
    52
end;