src/HOL/Tools/numeral_syntax.ML
author wenzelm
Sun Dec 10 22:27:06 2006 +0100 (2006-12-10)
changeset 21763 12a2773e3608
parent 20094 99f27df2b6d0
child 21780 ec264b9daf94
permissions -rw-r--r--
tuned comments;
     1 (*  Title:      HOL/Tools/numeral_syntax.ML
     2     ID:         $Id$
     3     Authors:    Markus Wenzel, TU Muenchen
     4 
     5 Concrete syntax for generic numerals.
     6 *)
     7 
     8 signature NUMERAL_SYNTAX =
     9 sig
    10   val setup: theory -> theory
    11 end;
    12 
    13 structure NumeralSyntax: NUMERAL_SYNTAX =
    14 struct
    15 
    16 
    17 (* bit strings *)   (*we try to handle superfluous leading digits nicely*)
    18 
    19 fun prefix_len _ [] = 0
    20   | prefix_len pred (x :: xs) =
    21       if pred x then 1 + prefix_len pred xs else 0;
    22 
    23 fun dest_bin_str tm =
    24   let
    25     val rev_digs = HOLogic.bin_of tm handle TERM _ => raise Match
    26     val (sign, zs) =
    27       (case rev rev_digs of
    28         ~1 :: bs => ("-", prefix_len (equal 1) bs)
    29       | bs => ("", prefix_len (equal 0) bs));
    30     val i = HOLogic.int_of rev_digs;
    31     val num = IntInf.toString (IntInf.abs i);
    32   in
    33     if i = IntInf.fromInt 0 orelse i = IntInf.fromInt 1 then raise Match
    34     else sign ^ implode (replicate zs "0") ^ num
    35   end;
    36 
    37 
    38 (* translation of integer numeral tokens to and from bitstrings *)
    39 
    40 fun numeral_tr (*"_Numeral"*) [t as Const (str, _)] =
    41       (Syntax.const "Numeral.number_of" $ (HOLogic.mk_binum (Syntax.read_xnum str)))
    42   | numeral_tr (*"_Numeral"*) ts = raise TERM ("numeral_tr", ts);
    43 
    44 fun numeral_tr' show_sorts (*"number_of"*) (Type ("fun", [_, T])) (t :: ts) =
    45       let val t' = Syntax.const "_Numeral" $ Syntax.free (dest_bin_str t) in
    46         if not (! show_types) andalso can Term.dest_Type T then t'
    47         else Syntax.const Syntax.constrainC $ t' $ Syntax.term_of_typ show_sorts T
    48       end
    49   | numeral_tr' _ (*"number_of"*) T (t :: ts) =
    50       if T = dummyT then Syntax.const "_Numeral" $ Syntax.free (dest_bin_str t)
    51       else raise Match
    52   | numeral_tr' _ (*"number_of"*) _ _ = raise Match;
    53 
    54 
    55 (* theory setup *)
    56 
    57 val setup =
    58   Theory.add_trfuns ([], [("_Numeral", numeral_tr)], [], []) #>
    59   Theory.add_trfunsT [("number_of", numeral_tr'), ("Numeral.number_of", numeral_tr')];
    60 
    61 end;