src/Pure/sign.ML
author clasohm
Thu Jan 26 12:44:50 1995 +0100 (1995-01-26)
changeset 879 27675591cc50
parent 865 b38c67991122
child 881 d7dcba167ed8
permissions -rw-r--r--
added reference variable ambiguity_level to control ambiguity warnings
     1 (*  Title:      Pure/sign.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson and Markus Wenzel
     4 
     5 The abstract type "sg" of signatures.
     6 *)
     7 
     8 signature SIGN =
     9 sig
    10   structure Symtab: SYMTAB
    11   structure Syntax: SYNTAX
    12   structure Type: TYPE
    13   sharing Symtab = Type.Symtab
    14   local open Type Syntax in
    15     type sg
    16     val rep_sg: sg ->
    17       {tsig: type_sig,
    18        const_tab: typ Symtab.table,
    19        syn: syntax,
    20        stamps: string ref list}
    21     val subsig: sg * sg -> bool
    22     val eq_sg: sg * sg -> bool
    23     val is_draft: sg -> bool
    24     val const_type: sg -> string -> typ option
    25     val classes: sg -> class list
    26     val subsort: sg -> sort * sort -> bool
    27     val norm_sort: sg -> sort -> sort
    28     val print_sg: sg -> unit
    29     val pretty_sg: sg -> Pretty.T
    30     val pprint_sg: sg -> pprint_args -> unit
    31     val pretty_term: sg -> term -> Pretty.T
    32     val pretty_typ: sg -> typ -> Pretty.T
    33     val pretty_sort: sort -> Pretty.T
    34     val string_of_term: sg -> term -> string
    35     val string_of_typ: sg -> typ -> string
    36     val pprint_term: sg -> term -> pprint_args -> unit
    37     val pprint_typ: sg -> typ -> pprint_args -> unit
    38     val certify_typ: sg -> typ -> typ
    39     val certify_term: sg -> term -> term * typ * int
    40     val read_typ: sg * (indexname -> sort option) -> string -> typ
    41     val infer_types: sg -> (indexname -> typ option) ->
    42       (indexname -> sort option) -> bool -> term list * typ ->
    43       int * term * (indexname * typ) list
    44     val add_classes: (class * class list) list -> sg -> sg
    45     val add_classrel: (class * class) list -> sg -> sg
    46     val add_defsort: sort -> sg -> sg
    47     val add_types: (string * int * mixfix) list -> sg -> sg
    48     val add_tyabbrs: (string * string list * string * mixfix) list -> sg -> sg
    49     val add_tyabbrs_i: (string * string list * typ * mixfix) list -> sg -> sg
    50     val add_arities: (string * sort list * sort) list -> sg -> sg
    51     val add_consts: (string * string * mixfix) list -> sg -> sg
    52     val add_consts_i: (string * typ * mixfix) list -> sg -> sg
    53     val add_syntax: (string * string * mixfix) list -> sg -> sg
    54     val add_syntax_i: (string * typ * mixfix) list -> sg -> sg
    55     val add_trfuns:
    56       (string * (ast list -> ast)) list *
    57       (string * (term list -> term)) list *
    58       (string * (term list -> term)) list *
    59       (string * (ast list -> ast)) list -> sg -> sg
    60     val add_trrules: xrule list -> sg -> sg
    61     val add_name: string -> sg -> sg
    62     val make_draft: sg -> sg
    63     val merge: sg * sg -> sg
    64     val pure: sg
    65     val const_of_class: class -> string
    66     val class_of_const: string -> class
    67     val ambiguity_level: int ref
    68   end
    69 end;
    70 
    71 functor SignFun(structure Syntax: SYNTAX and Type: TYPE): SIGN =
    72 struct
    73 
    74 structure Symtab = Type.Symtab;
    75 structure Syntax = Syntax;
    76 structure BasicSyntax: BASIC_SYNTAX = Syntax;
    77 structure Pretty = Syntax.Pretty;
    78 structure Type = Type;
    79 open BasicSyntax Type;
    80 
    81 
    82 (** datatype sg **)
    83 
    84 (*the "ref" in stamps ensures that no two signatures are identical -- it is
    85   impossible to forge a signature*)
    86 
    87 datatype sg =
    88   Sg of {
    89     tsig: type_sig,                 (*order-sorted signature of types*)
    90     const_tab: typ Symtab.table,    (*types of constants*)
    91     syn: Syntax.syntax,             (*syntax for parsing and printing*)
    92     stamps: string ref list};       (*unique theory indentifier*)
    93 
    94 fun rep_sg (Sg args) = args;
    95 val tsig_of = #tsig o rep_sg;
    96 
    97 
    98 (* stamps *)
    99 
   100 fun is_draft (Sg {stamps = ref "#" :: _, ...}) = true
   101   | is_draft _ = false;
   102 
   103 fun subsig (Sg {stamps = s1, ...}, Sg {stamps = s2, ...}) = s1 subset s2;
   104 
   105 fun eq_sg (Sg {stamps = s1, ...}, Sg {stamps = s2, ...}) = eq_set (s1, s2);
   106 
   107 
   108 (* consts *)
   109 
   110 fun const_type (Sg {const_tab, ...}) c =
   111   Symtab.lookup (const_tab, c);
   112 
   113 
   114 (* classes and sorts *)
   115 
   116 val classes = #classes o Type.rep_tsig o tsig_of;
   117 
   118 val subsort = Type.subsort o tsig_of;
   119 val norm_sort = Type.norm_sort o tsig_of;
   120 
   121 fun pretty_sort [c] = Pretty.str c
   122   | pretty_sort cs = Pretty.str_list "{" "}" cs;
   123 
   124 
   125 
   126 (** print signature **)
   127 
   128 val stamp_names = rev o map !;
   129 
   130 fun print_sg sg =
   131   let
   132     fun prt_typ syn ty = Pretty.quote (Syntax.pretty_typ syn ty);
   133 
   134     fun pretty_subclass (cl, cls) = Pretty.block
   135       [Pretty.str (cl ^ " <"), Pretty.brk 1, pretty_sort cls];
   136 
   137     fun pretty_default cls = Pretty.block
   138       [Pretty.str "default:", Pretty.brk 1, pretty_sort cls];
   139 
   140     fun pretty_arg (ty, n) = Pretty.str (ty ^ " " ^ string_of_int n);
   141 
   142     fun pretty_abbr syn (ty, (vs, rhs)) = Pretty.block
   143       [prt_typ syn (Type (ty, map (fn v => TVar ((v, 0), [])) vs)),
   144         Pretty.str " =", Pretty.brk 1, prt_typ syn rhs];
   145 
   146     fun pretty_arity ty (cl, []) = Pretty.block
   147           [Pretty.str (ty ^ " ::"), Pretty.brk 1, Pretty.str cl]
   148       | pretty_arity ty (cl, srts) = Pretty.block
   149           [Pretty.str (ty ^ " ::"), Pretty.brk 1,
   150             Pretty.list "(" ")" (map pretty_sort srts),
   151             Pretty.brk 1, Pretty.str cl];
   152 
   153     fun pretty_coreg (ty, ars) = map (pretty_arity ty) ars;
   154 
   155     fun pretty_const syn (c, ty) = Pretty.block
   156       [Pretty.str (quote c ^ " ::"), Pretty.brk 1, prt_typ syn ty];
   157 
   158 
   159     val Sg {tsig, const_tab, syn, stamps} = sg;
   160     val {classes, subclass, default, args, abbrs, coreg} = rep_tsig tsig;
   161   in
   162     Pretty.writeln (Pretty.strs ("stamps:" :: stamp_names stamps));
   163     Pretty.writeln (Pretty.strs ("classes:" :: classes));
   164     Pretty.writeln (Pretty.big_list "subclass:" (map pretty_subclass subclass));
   165     Pretty.writeln (pretty_default default);
   166     Pretty.writeln (Pretty.big_list "types:" (map pretty_arg args));
   167     Pretty.writeln (Pretty.big_list "abbrs:" (map (pretty_abbr syn) abbrs));
   168     Pretty.writeln (Pretty.big_list "coreg:" (flat (map pretty_coreg coreg)));
   169     Pretty.writeln (Pretty.big_list "consts:"
   170       (map (pretty_const syn) (Symtab.dest const_tab)))
   171   end;
   172 
   173 
   174 fun pretty_sg (Sg {stamps, ...}) =
   175   Pretty.str_list "{" "}" (stamp_names stamps);
   176 
   177 val pprint_sg = Pretty.pprint o pretty_sg;
   178 
   179 
   180 
   181 (** pretty printing of terms and types **)
   182 
   183 fun pretty_term (Sg {syn, ...}) = Syntax.pretty_term syn;
   184 fun pretty_typ (Sg {syn, ...}) = Syntax.pretty_typ syn;
   185 
   186 fun string_of_term (Sg {syn, ...}) = Syntax.string_of_term syn;
   187 fun string_of_typ (Sg {syn, ...}) = Syntax.string_of_typ syn;
   188 
   189 fun pprint_term sg = Pretty.pprint o Pretty.quote o (pretty_term sg);
   190 fun pprint_typ sg = Pretty.pprint o Pretty.quote o (pretty_typ sg);
   191 
   192 
   193 
   194 (** read types **)  (*exception ERROR*)
   195 
   196 fun err_in_type s =
   197   error ("The error(s) above occurred in type " ^ quote s);
   198 
   199 fun read_raw_typ syn tsig sort_of str =
   200   Syntax.read_typ syn (fn x => if_none (sort_of x) (defaultS tsig)) str
   201     handle ERROR => err_in_type str;
   202 
   203 (*read and certify typ wrt a signature*)
   204 fun read_typ (Sg {tsig, syn, ...}, sort_of) str =
   205   cert_typ tsig (read_raw_typ syn tsig sort_of str)
   206     handle TYPE (msg, _, _) => (writeln msg; err_in_type str);
   207 
   208 
   209 
   210 (** certify types and terms **)   (*exception TYPE*)
   211 
   212 fun certify_typ (Sg {tsig, ...}) ty = cert_typ tsig ty;
   213 
   214 
   215 fun mapfilt_atoms f (Abs (_, _, t)) = mapfilt_atoms f t
   216   | mapfilt_atoms f (t $ u) = mapfilt_atoms f t @ mapfilt_atoms f u
   217   | mapfilt_atoms f a = (case f a of Some y => [y] | None => []);
   218 
   219 fun certify_term (sg as Sg {tsig, ...}) tm =
   220   let
   221     fun valid_const a T =
   222       (case const_type sg a of
   223         Some U => typ_instance (tsig, T, U)
   224       | _ => false);
   225 
   226     fun atom_err (Const (a, T)) =
   227           if valid_const a T then None
   228           else Some ("Illegal type for constant " ^ quote a ^ " :: " ^
   229             quote (string_of_typ sg T))
   230       | atom_err (Var ((x, i), _)) =
   231           if i < 0 then Some ("Negative index for Var " ^ quote x) else None
   232       | atom_err _ = None;
   233 
   234     val norm_tm =
   235       (case it_term_types (typ_errors tsig) (tm, []) of
   236         [] => map_term_types (norm_typ tsig) tm
   237       | errs => raise_type (cat_lines errs) [] [tm]);
   238   in
   239     (case mapfilt_atoms atom_err norm_tm of
   240       [] => (norm_tm, type_of norm_tm, maxidx_of_term norm_tm)
   241     | errs => raise_type (cat_lines errs) [] [norm_tm])
   242   end;
   243 
   244 
   245 
   246 (** infer_types **)         (*exception ERROR*)
   247 
   248 val ambiguity_level = ref 1;
   249 
   250 fun infer_types sg types sorts print_msg (ts, T) =
   251   let
   252     val Sg {tsig, ...} = sg;
   253     val show_typ = string_of_typ sg;
   254     val show_term = string_of_term sg;
   255 
   256     fun term_err [] = ""
   257       | term_err [t] = "\nInvolving this term:\n" ^ show_term t
   258       | term_err ts = 
   259           "\nInvolving these terms:\n" ^ cat_lines (map show_term ts);
   260 
   261     fun exn_type_msg (msg, Ts, ts) =
   262 	msg ^ "\nType checking error: " ^ msg ^ "\n" ^
   263 	cat_lines (map show_typ Ts) ^ term_err ts ^ "\n";
   264 
   265     val T' = certify_typ sg T
   266       handle TYPE arg => error (exn_type_msg arg);
   267 
   268     val ct = const_type sg;
   269 
   270     fun process_terms (t::ts) (idx, infrd_t, tye) msg n =
   271          let fun mk_some (x, y) = (Some x, Some y);
   272 
   273              val ((infrd_t', tye'), msg') = 
   274               (mk_some (Type.infer_types (tsig, ct, types, sorts, T', t)), msg)
   275               handle TYPE arg => ((None, None), exn_type_msg arg)
   276 
   277              val old_show_brackets = !show_brackets;
   278 
   279              val _ = (show_brackets := true);
   280 
   281              val msg'' = 
   282                if is_none idx then (if is_none infrd_t' then msg' else "")
   283                else if is_none infrd_t' then "" 
   284                else (if msg' = "" then 
   285                 "Error: More than one term is type correct:\n" ^
   286                 (show_term (the infrd_t)) else msg') ^ "\n" ^ 
   287                 (show_term (the infrd_t')) ^ "\n";
   288 
   289              val _ = (show_brackets := old_show_brackets);
   290          in if is_none infrd_t' then
   291               process_terms ts (idx, infrd_t, tye) msg'' (n+1)
   292             else
   293               process_terms ts (Some n, infrd_t', tye') msg'' (n+1)
   294          end
   295       | process_terms [] (idx, infrd_t, tye) msg _ = 
   296           if msg = "" then (the idx, the infrd_t, the tye) 
   297           else error msg;
   298 
   299     val (idx, infrd_t, tye) = process_terms ts (None, None, None) "" 0;
   300   in if print_msg andalso length ts > !ambiguity_level then
   301        writeln "Fortunately, only one parse tree is type correct.\n\
   302          \It helps (speed!) if you disambiguate your grammar or your input."
   303      else ();
   304      (idx, infrd_t, tye)
   305   end;
   306 
   307 
   308 
   309 (** extend signature **)    (*exception ERROR*)
   310 
   311 (** signature extension functions **)  (*exception ERROR*)
   312 
   313 fun decls_of name_of mfixs =
   314   map (fn (x, y, mx) => (name_of x mx, y)) mfixs;
   315 
   316 
   317 (* add default sort *)
   318 
   319 fun ext_defsort (syn, tsig, ctab) defsort =
   320   (syn, ext_tsig_defsort tsig defsort, ctab);
   321 
   322 
   323 (* add type constructors *)
   324 
   325 fun ext_types (syn, tsig, ctab) types =
   326   (Syntax.extend_type_gram syn types,
   327     ext_tsig_types tsig (decls_of Syntax.type_name types),
   328     ctab);
   329 
   330 
   331 (* add type abbreviations *)
   332 
   333 fun read_abbr syn tsig (t, vs, rhs_src) =
   334   (t, vs, read_raw_typ syn tsig (K None) rhs_src)
   335     handle ERROR => error ("in type abbreviation " ^ t);
   336 
   337 fun ext_abbrs rd_abbr (syn, tsig, ctab) abbrs =
   338   let
   339     fun mfix_of (t, vs, _, mx) = (t, length vs, mx);
   340     val syn1 = Syntax.extend_type_gram syn (map mfix_of abbrs);
   341 
   342     fun decl_of (t, vs, rhs, mx) =
   343       rd_abbr syn1 tsig (Syntax.type_name t mx, vs, rhs);
   344   in
   345     (syn1, ext_tsig_abbrs tsig (map decl_of abbrs), ctab)
   346   end;
   347 
   348 val ext_tyabbrs_i = ext_abbrs (K (K I));
   349 val ext_tyabbrs = ext_abbrs read_abbr;
   350 
   351 
   352 (* add type arities *)
   353 
   354 fun ext_arities (syn, tsig, ctab) arities =
   355   let
   356     val tsig1 = ext_tsig_arities tsig arities;
   357     val log_types = logical_types tsig1;
   358   in
   359     (Syntax.extend_log_types syn log_types, tsig1, ctab)
   360   end;
   361 
   362 
   363 (* add term constants and syntax *)
   364 
   365 fun err_in_const c =
   366   error ("in declaration of constant " ^ quote c);
   367 
   368 fun err_dup_consts cs =
   369   error ("Duplicate declaration of constant(s) " ^ commas_quote cs);
   370 
   371 
   372 fun read_const syn tsig (c, ty_src, mx) =
   373   (c, read_raw_typ syn tsig (K None) ty_src, mx)
   374     handle ERROR => err_in_const (Syntax.const_name c mx);
   375 
   376 fun ext_cnsts rd_const syn_only (syn, tsig, ctab) raw_consts =
   377   let
   378     fun prep_const (c, ty, mx) = (c, varifyT (cert_typ tsig (no_tvars ty)), mx)
   379       handle TYPE (msg, _, _) => (writeln msg; err_in_const (Syntax.const_name c mx));
   380 
   381     val consts = map (prep_const o rd_const syn tsig) raw_consts;
   382     val decls =
   383       if syn_only then []
   384       else filter_out (equal "" o fst) (decls_of Syntax.const_name consts);
   385   in
   386     (Syntax.extend_const_gram syn consts, tsig,
   387       Symtab.extend_new (ctab, decls)
   388         handle Symtab.DUPS cs => err_dup_consts cs)
   389   end;
   390 
   391 val ext_consts_i = ext_cnsts (K (K I)) false;
   392 val ext_consts = ext_cnsts read_const false;
   393 val ext_syntax_i = ext_cnsts (K (K I)) true;
   394 val ext_syntax = ext_cnsts read_const true;
   395 
   396 
   397 (* add type classes *)
   398 
   399 fun const_of_class c = c ^ "_class";
   400 
   401 fun class_of_const c_class =
   402   let
   403     val c = implode (take (size c_class - 6, explode c_class));
   404   in
   405     if const_of_class c = c_class then c
   406     else raise_term ("class_of_const: bad name " ^ quote c_class) []
   407   end;
   408 
   409 
   410 fun ext_classes (syn, tsig, ctab) classes =
   411   let
   412     val names = map fst classes;
   413     val consts =
   414       map (fn c => (const_of_class c, a_itselfT --> propT, NoSyn)) names;
   415   in
   416     ext_consts_i
   417       (Syntax.extend_consts syn names, ext_tsig_classes tsig classes, ctab)
   418       consts
   419   end;
   420 
   421 
   422 (* add to subclass relation *)
   423 
   424 fun ext_classrel (syn, tsig, ctab) pairs =
   425   (syn, ext_tsig_subclass tsig pairs, ctab);
   426 
   427 
   428 (* add syntactic translations *)
   429 
   430 fun ext_trfuns (syn, tsig, ctab) trfuns =
   431   (Syntax.extend_trfuns syn trfuns, tsig, ctab);
   432 
   433 fun ext_trrules (syn, tsig, ctab) xrules =
   434   (Syntax.extend_trrules syn xrules, tsig, ctab);
   435 
   436 
   437 (* build signature *)
   438 
   439 fun ext_stamps stamps name =
   440   let
   441     val stmps = (case stamps of ref "#" :: ss => ss | ss => ss);
   442   in
   443     if exists (equal name o !) stmps then
   444       error ("Theory already contains a " ^ quote name ^ " component")
   445     else ref name :: stmps
   446   end;
   447 
   448 fun make_sign (syn, tsig, ctab) stamps name =
   449   Sg {tsig = tsig, const_tab = ctab, syn = syn,
   450     stamps = ext_stamps stamps name};
   451 
   452 fun extend_sign extfun name decls (Sg {tsig, const_tab, syn, stamps}) =
   453   make_sign (extfun (syn, tsig, const_tab) decls) stamps name;
   454 
   455 
   456 (* the external interfaces *)
   457 
   458 val add_classes   = extend_sign ext_classes "#";
   459 val add_classrel  = extend_sign ext_classrel "#";
   460 val add_defsort   = extend_sign ext_defsort "#";
   461 val add_types     = extend_sign ext_types "#";
   462 val add_tyabbrs   = extend_sign ext_tyabbrs "#";
   463 val add_tyabbrs_i = extend_sign ext_tyabbrs_i "#";
   464 val add_arities   = extend_sign ext_arities "#";
   465 val add_consts    = extend_sign ext_consts "#";
   466 val add_consts_i  = extend_sign ext_consts_i "#";
   467 val add_syntax    = extend_sign ext_syntax "#";
   468 val add_syntax_i  = extend_sign ext_syntax_i "#";
   469 val add_trfuns    = extend_sign ext_trfuns "#";
   470 val add_trrules   = extend_sign ext_trrules "#";
   471 
   472 fun add_name name sg = extend_sign K name () sg;
   473 val make_draft = add_name "#";
   474 
   475 
   476 
   477 (** merge signatures **)    (*exception TERM*) (*exception ERROR (* FIXME *)*)
   478 
   479 fun merge (sg1, sg2) =
   480   if subsig (sg2, sg1) then sg1
   481   else if subsig (sg1, sg2) then sg2
   482   else if is_draft sg1 orelse is_draft sg2 then
   483     raise_term "Illegal merge of draft signatures" []
   484   else
   485     (*neither is union already; must form union*)
   486     let
   487       val Sg {tsig = tsig1, const_tab = const_tab1, syn = syn1,
   488         stamps = stamps1} = sg1;
   489       val Sg {tsig = tsig2, const_tab = const_tab2, syn = syn2,
   490         stamps = stamps2} = sg2;
   491 
   492 
   493       val stamps = merge_rev_lists stamps1 stamps2;
   494       val _ =
   495         (case duplicates (stamp_names stamps) of
   496           [] => ()
   497         | dups => raise_term ("Attempt to merge different versions of theories "
   498             ^ commas_quote dups) []);
   499 
   500       val tsig = merge_tsigs (tsig1, tsig2);
   501 
   502       val const_tab = Symtab.merge (op =) (const_tab1, const_tab2)
   503         handle Symtab.DUPS cs =>
   504           raise_term ("Incompatible types for constant(s) " ^ commas_quote cs) [];
   505 
   506       val syn = Syntax.merge_syntaxes syn1 syn2;
   507     in
   508       Sg {tsig = tsig, const_tab = const_tab, syn = syn, stamps = stamps}
   509     end;
   510 
   511 
   512 
   513 (** the Pure signature **)
   514 
   515 val pure =
   516   make_sign (Syntax.pure_syn, tsig0, Symtab.null) [] "#"
   517   |> add_types
   518    (("fun", 2, NoSyn) ::
   519     ("prop", 0, NoSyn) ::
   520     ("itself", 1, NoSyn) ::
   521     Syntax.pure_types)
   522   |> add_classes [(logicC, [])]
   523   |> add_defsort logicS
   524   |> add_arities
   525    [("fun", [logicS, logicS], logicS),
   526     ("prop", [], logicS),
   527     ("itself", [logicS], logicS)]
   528   |> add_syntax Syntax.pure_syntax
   529   |> add_trfuns Syntax.pure_trfuns
   530   |> add_consts
   531    [("==", "['a::{}, 'a] => prop", Mixfix ("(_ ==/ _)", [3, 2], 2)),
   532     ("=?=", "['a::{}, 'a] => prop", Mixfix ("(_ =?=/ _)", [3, 2], 2)),
   533     ("==>", "[prop, prop] => prop", Mixfix ("(_ ==>/ _)", [2, 1], 1)),
   534     ("all", "('a => prop) => prop", Binder ("!!", 0, 0)),
   535     ("TYPE", "'a itself", NoSyn)]
   536   |> add_name "Pure";
   537 
   538 
   539 end;