src/Pure/Syntax/syntax.ML
author wenzelm
Sat Sep 29 21:39:53 2007 +0200 (2007-09-29)
changeset 24768 123e219b66c2
parent 24709 ecfb9dcb6c4c
child 24923 9e095546cdac
permissions -rw-r--r--
added unparse interfaces (still unused);
add_typ/term_check: added stage and name argument;
added print_checks;
     1 (*  Title:      Pure/Syntax/syntax.ML
     2     ID:         $Id$
     3     Author:     Tobias Nipkow and Markus Wenzel, TU Muenchen
     4 
     5 Standard Isabelle syntax, based on arbitrary context-free grammars
     6 (specified by mixfix declarations).
     7 *)
     8 
     9 signature BASIC_SYNTAX =
    10 sig
    11   include AST0
    12   include SYN_TRANS0
    13   include MIXFIX0
    14   include PRINTER0
    15 end;
    16 
    17 signature SYNTAX =
    18 sig
    19   include AST1
    20   include LEXICON0
    21   include SYN_EXT0
    22   include TYPE_EXT0
    23   include SYN_TRANS1
    24   include MIXFIX1
    25   include PRINTER0
    26   val extend_trtab: string -> (string * ('a * stamp)) list ->
    27     ('a * stamp) Symtab.table -> ('a * stamp) Symtab.table
    28   val merge_trtabs: string -> ('a * stamp) Symtab.table -> ('a * stamp) Symtab.table ->
    29     ('a * stamp) Symtab.table
    30   val merge_tr'tabs: ('a * stamp) list Symtab.table -> ('a * stamp) list Symtab.table
    31     -> ('a * stamp) list Symtab.table
    32   val extend_tr'tab: (string * ('a * stamp)) list ->
    33     ('a * stamp) list Symtab.table -> ('a * stamp) list Symtab.table
    34   datatype 'a trrule =
    35     ParseRule of 'a * 'a |
    36     PrintRule of 'a * 'a |
    37     ParsePrintRule of 'a * 'a
    38   type syntax
    39   val eq_syntax: syntax * syntax -> bool
    40   val is_keyword: syntax -> string -> bool
    41   type mode
    42   val default_mode: mode
    43   val input_mode: mode
    44   val internalM: string
    45   val extend_type_gram: (string * int * mixfix) list -> syntax -> syntax
    46   val extend_const_gram: (string -> bool) ->
    47     mode -> (string * typ * mixfix) list -> syntax -> syntax
    48   val extend_consts: string list -> syntax -> syntax
    49   val extend_trfuns:
    50     (string * ((ast list -> ast) * stamp)) list *
    51     (string * ((term list -> term) * stamp)) list *
    52     (string * ((bool -> typ -> term list -> term) * stamp)) list *
    53     (string * ((ast list -> ast) * stamp)) list -> syntax -> syntax
    54   val extend_advanced_trfuns:
    55     (string * ((Proof.context -> ast list -> ast) * stamp)) list *
    56     (string * ((Proof.context -> term list -> term) * stamp)) list *
    57     (string * ((Proof.context -> bool -> typ -> term list -> term) * stamp)) list *
    58     (string * ((Proof.context -> ast list -> ast) * stamp)) list -> syntax -> syntax
    59   val extend_tokentrfuns: (string * string * (string -> output * int)) list -> syntax -> syntax
    60   val remove_const_gram: (string -> bool) ->
    61     mode -> (string * typ * mixfix) list -> syntax -> syntax
    62   val extend_trrules: Proof.context -> (string -> bool) -> syntax ->
    63     (string * string) trrule list -> syntax -> syntax
    64   val remove_trrules: Proof.context -> (string -> bool) -> syntax ->
    65     (string * string) trrule list -> syntax -> syntax
    66   val extend_trrules_i: ast trrule list -> syntax -> syntax
    67   val remove_trrules_i: ast trrule list -> syntax -> syntax
    68   val map_trrule: ('a -> 'b) -> 'a trrule -> 'b trrule
    69   val merge_syntaxes: syntax -> syntax -> syntax
    70   val basic_syn: syntax
    71   val basic_nonterms: string list
    72   val print_gram: syntax -> unit
    73   val print_trans: syntax -> unit
    74   val print_syntax: syntax -> unit
    75   val read: Proof.context -> (string -> bool) -> syntax -> typ -> string -> term list
    76   val standard_parse_term: Pretty.pp -> (term -> term Exn.result) ->
    77     (((string * int) * sort) list -> string * int -> Term.sort) ->
    78     (string -> string option) -> (string -> string option) ->
    79     (typ -> typ) -> (sort -> sort) -> Proof.context ->
    80     (string -> bool) -> syntax -> typ -> string -> term
    81   val standard_parse_typ: Proof.context -> syntax -> ((indexname * sort) list -> indexname -> sort) ->
    82     (sort -> sort) -> string -> typ
    83   val standard_parse_sort: Proof.context -> syntax -> (sort -> sort) -> string -> sort
    84   val pretty_term: (string -> xstring) -> Proof.context -> syntax -> bool -> term -> Pretty.T
    85   val pretty_typ: Proof.context -> syntax -> typ -> Pretty.T
    86   val pretty_sort: Proof.context -> syntax -> sort -> Pretty.T
    87   val ambiguity_level: int ref
    88   val ambiguity_is_error: bool ref
    89   val parse_sort: Proof.context -> string -> sort
    90   val parse_typ: Proof.context -> string -> typ
    91   val parse_term: Proof.context -> string -> term
    92   val parse_prop: Proof.context -> string -> term
    93   val unparse_sort: Proof.context -> sort -> Pretty.T
    94   val unparse_typ: Proof.context -> typ -> Pretty.T
    95   val unparse_term: Proof.context -> term -> Pretty.T
    96   val install_operations:
    97    {parse_sort: Proof.context -> string -> sort,
    98     parse_typ: Proof.context -> string -> typ,
    99     parse_term: Proof.context -> string -> term,
   100     parse_prop: Proof.context -> string -> term,
   101     unparse_sort: Proof.context -> sort -> Pretty.T,
   102     unparse_typ: Proof.context -> typ -> Pretty.T,
   103     unparse_term: Proof.context -> term -> Pretty.T} -> unit
   104   val print_checks: Proof.context -> unit
   105   val add_typ_check: int -> string ->
   106     (typ list -> Proof.context -> typ list * Proof.context) ->
   107     Context.generic -> Context.generic
   108   val add_term_check: int -> string ->
   109     (term list -> Proof.context -> term list * Proof.context) ->
   110     Context.generic -> Context.generic
   111   val add_typ_uncheck: int -> string ->
   112     (typ list -> Proof.context -> typ list * Proof.context) ->
   113     Context.generic -> Context.generic
   114   val add_term_uncheck: int -> string ->
   115     (term list -> Proof.context -> term list * Proof.context) ->
   116     Context.generic -> Context.generic
   117   val check_sort: Proof.context -> sort -> sort
   118   val check_typ: Proof.context -> typ -> typ
   119   val check_term: Proof.context -> term -> term
   120   val check_prop: Proof.context -> term -> term
   121   val check_typs: Proof.context -> typ list -> typ list
   122   val check_terms: Proof.context -> term list -> term list
   123   val check_props: Proof.context -> term list -> term list
   124   val uncheck_typs: Proof.context -> typ list -> typ list
   125   val uncheck_terms: Proof.context -> term list -> term list
   126   val read_sort: Proof.context -> string -> sort
   127   val read_typ: Proof.context -> string -> typ
   128   val read_term: Proof.context -> string -> term
   129   val read_prop: Proof.context -> string -> term
   130   val read_terms: Proof.context -> string list -> term list
   131   val read_props: Proof.context -> string list -> term list
   132   val read_sort_global: theory -> string -> sort
   133   val read_typ_global: theory -> string -> typ
   134   val read_term_global: theory -> string -> term
   135   val read_prop_global: theory -> string -> term
   136 end;
   137 
   138 structure Syntax: SYNTAX =
   139 struct
   140 
   141 (** tables of translation functions **)
   142 
   143 (* parse (ast) translations *)
   144 
   145 fun lookup_tr tab c = Option.map fst (Symtab.lookup tab c);
   146 
   147 fun err_dup_trfun name c =
   148   error ("More than one " ^ name ^ " for " ^ quote c);
   149 
   150 fun remove_trtab trfuns = fold (Symtab.remove SynExt.eq_trfun) trfuns;
   151 
   152 fun extend_trtab name trfuns tab = Symtab.extend (remove_trtab trfuns tab, trfuns)
   153   handle Symtab.DUP c => err_dup_trfun name c;
   154 
   155 fun merge_trtabs name tab1 tab2 = Symtab.merge SynExt.eq_trfun (tab1, tab2)
   156   handle Symtab.DUP c => err_dup_trfun name c;
   157 
   158 
   159 (* print (ast) translations *)
   160 
   161 fun lookup_tr' tab c = map fst (Symtab.lookup_list tab c);
   162 fun extend_tr'tab trfuns = fold_rev Symtab.update_list trfuns;
   163 fun remove_tr'tab trfuns = fold (Symtab.remove_list SynExt.eq_trfun) trfuns;
   164 fun merge_tr'tabs tab1 tab2 = Symtab.merge_list SynExt.eq_trfun (tab1, tab2);
   165 
   166 
   167 
   168 (** tables of token translation functions **)
   169 
   170 fun lookup_tokentr tabs modes =
   171   let val trs = distinct (eq_fst (op =)) (maps (these o AList.lookup (op =) tabs) (modes @ [""]))
   172   in fn c => Option.map fst (AList.lookup (op =) trs c) end;
   173 
   174 fun merge_tokentrtabs tabs1 tabs2 =
   175   let
   176     fun eq_tr ((c1, (_, s1)), (c2, (_, s2))) = c1 = c2 andalso s1 = s2;
   177 
   178     fun name (s, _) = implode (tl (Symbol.explode s));
   179 
   180     fun merge mode =
   181       let
   182         val trs1 = these (AList.lookup (op =) tabs1 mode);
   183         val trs2 = these (AList.lookup (op =) tabs2 mode);
   184         val trs = distinct eq_tr (trs1 @ trs2);
   185       in
   186         (case duplicates (eq_fst (op =)) trs of
   187           [] => (mode, trs)
   188         | dups => error ("More than one token translation function in mode " ^
   189             quote mode ^ " for " ^ commas_quote (map name dups)))
   190       end;
   191   in map merge (distinct (op =) (map fst (tabs1 @ tabs2))) end;
   192 
   193 fun extend_tokentrtab tokentrs tabs =
   194   let
   195     fun ins_tokentr (m, c, f) =
   196       AList.default (op =) (m, [])
   197       #> AList.map_entry (op =) m (cons ("_" ^ c, (f, stamp ())));
   198   in merge_tokentrtabs tabs (fold ins_tokentr tokentrs []) end;
   199 
   200 
   201 
   202 (** tables of translation rules **)
   203 
   204 type ruletab = (Ast.ast * Ast.ast) list Symtab.table;
   205 
   206 fun dest_ruletab tab = maps snd (Symtab.dest tab);
   207 
   208 
   209 (* empty, extend, merge ruletabs *)
   210 
   211 val extend_ruletab = fold_rev (fn r => Symtab.update_list (Ast.head_of_rule r, r));
   212 val remove_ruletab = fold (fn r => Symtab.remove_list (op =) (Ast.head_of_rule r, r));
   213 fun merge_ruletabs tab1 tab2 = Symtab.merge_list (op =) (tab1, tab2);
   214 
   215 
   216 
   217 (** datatype syntax **)
   218 
   219 datatype syntax =
   220   Syntax of {
   221     input: SynExt.xprod list,
   222     lexicon: Scan.lexicon,
   223     gram: Parser.gram,
   224     consts: string list,
   225     prmodes: string list,
   226     parse_ast_trtab: ((Proof.context -> Ast.ast list -> Ast.ast) * stamp) Symtab.table,
   227     parse_ruletab: ruletab,
   228     parse_trtab: ((Proof.context -> term list -> term) * stamp) Symtab.table,
   229     print_trtab: ((Proof.context -> bool -> typ -> term list -> term) * stamp) list Symtab.table,
   230     print_ruletab: ruletab,
   231     print_ast_trtab: ((Proof.context -> Ast.ast list -> Ast.ast) * stamp) list Symtab.table,
   232     tokentrtab: (string * (string * ((string -> output * int) * stamp)) list) list,
   233     prtabs: Printer.prtabs} * stamp;
   234 
   235 fun eq_syntax (Syntax (_, s1), Syntax (_, s2)) = s1 = s2;
   236 
   237 fun is_keyword (Syntax ({lexicon, ...}, _)) = Scan.is_literal lexicon o Symbol.explode;
   238 
   239 type mode = string * bool;
   240 val default_mode = ("", true);
   241 val input_mode = ("input", true);
   242 val internalM = "internal";
   243 
   244 
   245 (* empty_syntax *)
   246 
   247 val empty_syntax = Syntax
   248   ({input = [],
   249     lexicon = Scan.empty_lexicon,
   250     gram = Parser.empty_gram,
   251     consts = [],
   252     prmodes = [],
   253     parse_ast_trtab = Symtab.empty,
   254     parse_ruletab = Symtab.empty,
   255     parse_trtab = Symtab.empty,
   256     print_trtab = Symtab.empty,
   257     print_ruletab = Symtab.empty,
   258     print_ast_trtab = Symtab.empty,
   259     tokentrtab = [],
   260     prtabs = Printer.empty_prtabs}, stamp ());
   261 
   262 
   263 (* extend_syntax *)
   264 
   265 fun extend_syntax (mode, inout) syn_ext (Syntax (tabs, _)) =
   266   let
   267     val {input, lexicon, gram, consts = consts1, prmodes = prmodes1,
   268       parse_ast_trtab, parse_ruletab, parse_trtab, print_trtab, print_ruletab,
   269       print_ast_trtab, tokentrtab, prtabs} = tabs;
   270     val SynExt.SynExt {xprods, consts = consts2, prmodes = prmodes2,
   271       parse_ast_translation, parse_rules, parse_translation, print_translation, print_rules,
   272       print_ast_translation, token_translation} = syn_ext;
   273     fun if_inout xs = if inout then xs else [];
   274   in
   275     Syntax
   276     ({input = if_inout xprods @ input,
   277       lexicon = Scan.extend_lexicon (if_inout (SynExt.delims_of xprods)) lexicon,
   278       gram = Parser.extend_gram gram (if_inout xprods),
   279       consts = Library.merge (op =) (consts1, filter_out NameSpace.is_qualified consts2),
   280       prmodes = insert (op =) mode (Library.merge (op =) (prmodes1, prmodes2)),
   281       parse_ast_trtab =
   282         extend_trtab "parse ast translation" (if_inout parse_ast_translation) parse_ast_trtab,
   283       parse_ruletab = extend_ruletab (if_inout parse_rules) parse_ruletab,
   284       parse_trtab = extend_trtab "parse translation" (if_inout parse_translation) parse_trtab,
   285       print_trtab = extend_tr'tab print_translation print_trtab,
   286       print_ruletab = extend_ruletab print_rules print_ruletab,
   287       print_ast_trtab = extend_tr'tab print_ast_translation print_ast_trtab,
   288       tokentrtab = extend_tokentrtab token_translation tokentrtab,
   289       prtabs = Printer.extend_prtabs mode xprods prtabs}, stamp ())
   290   end;
   291 
   292 
   293 (* remove_syntax *)
   294 
   295 fun remove_syntax (mode, inout) syn_ext (Syntax (tabs, _)) =
   296   let
   297     val SynExt.SynExt {xprods, consts = _, prmodes = _,
   298       parse_ast_translation, parse_rules, parse_translation, print_translation, print_rules,
   299       print_ast_translation, token_translation = _} = syn_ext;
   300     val {input, lexicon, gram, consts, prmodes,
   301       parse_ast_trtab, parse_ruletab, parse_trtab, print_trtab, print_ruletab,
   302       print_ast_trtab, tokentrtab, prtabs} = tabs;
   303     val input' = if inout then subtract (op =) xprods input else input;
   304     fun if_inout xs = if inout then xs else [];
   305   in
   306     Syntax
   307     ({input = input',
   308       lexicon = if inout then Scan.make_lexicon (SynExt.delims_of input') else lexicon,
   309       gram = if inout then Parser.make_gram input' else gram,
   310       consts = consts,
   311       prmodes = prmodes,
   312       parse_ast_trtab = remove_trtab (if_inout parse_ast_translation) parse_ast_trtab,
   313       parse_ruletab = remove_ruletab (if_inout parse_rules) parse_ruletab,
   314       parse_trtab = remove_trtab (if_inout parse_translation) parse_trtab,
   315       print_trtab = remove_tr'tab print_translation print_trtab,
   316       print_ruletab = remove_ruletab print_rules print_ruletab,
   317       print_ast_trtab = remove_tr'tab print_ast_translation print_ast_trtab,
   318       tokentrtab = tokentrtab,
   319       prtabs = Printer.remove_prtabs mode xprods prtabs}, stamp ())
   320   end;
   321 
   322 
   323 (* merge_syntaxes *)
   324 
   325 fun merge_syntaxes (Syntax (tabs1, _)) (Syntax (tabs2, _)) =
   326   let
   327     val {input = input1, lexicon = lexicon1, gram = gram1, consts = consts1,
   328       prmodes = prmodes1, parse_ast_trtab = parse_ast_trtab1,
   329       parse_ruletab = parse_ruletab1, parse_trtab = parse_trtab1,
   330       print_trtab = print_trtab1, print_ruletab = print_ruletab1,
   331       print_ast_trtab = print_ast_trtab1, tokentrtab = tokentrtab1, prtabs = prtabs1} = tabs1;
   332 
   333     val {input = input2, lexicon = lexicon2, gram = gram2, consts = consts2,
   334       prmodes = prmodes2, parse_ast_trtab = parse_ast_trtab2,
   335       parse_ruletab = parse_ruletab2, parse_trtab = parse_trtab2,
   336       print_trtab = print_trtab2, print_ruletab = print_ruletab2,
   337       print_ast_trtab = print_ast_trtab2, tokentrtab = tokentrtab2, prtabs = prtabs2} = tabs2;
   338   in
   339     Syntax
   340     ({input = Library.merge (op =) (input1, input2),
   341       lexicon = Scan.merge_lexicons lexicon1 lexicon2,
   342       gram = Parser.merge_grams gram1 gram2,
   343       consts = sort_distinct string_ord (consts1 @ consts2),
   344       prmodes = Library.merge (op =) (prmodes1, prmodes2),
   345       parse_ast_trtab =
   346         merge_trtabs "parse ast translation" parse_ast_trtab1 parse_ast_trtab2,
   347       parse_ruletab = merge_ruletabs parse_ruletab1 parse_ruletab2,
   348       parse_trtab = merge_trtabs "parse translation" parse_trtab1 parse_trtab2,
   349       print_trtab = merge_tr'tabs print_trtab1 print_trtab2,
   350       print_ruletab = merge_ruletabs print_ruletab1 print_ruletab2,
   351       print_ast_trtab = merge_tr'tabs print_ast_trtab1 print_ast_trtab2,
   352       tokentrtab = merge_tokentrtabs tokentrtab1 tokentrtab2,
   353       prtabs = Printer.merge_prtabs prtabs1 prtabs2}, stamp ())
   354   end;
   355 
   356 
   357 (* basic syntax *)
   358 
   359 val basic_syn =
   360   empty_syntax
   361   |> extend_syntax default_mode TypeExt.type_ext
   362   |> extend_syntax default_mode SynExt.pure_ext;
   363 
   364 val basic_nonterms =
   365   (Lexicon.terminals @ [SynExt.logic, "type", "types", "sort", "classes",
   366     SynExt.args, SynExt.cargs, "pttrn", "pttrns", "idt", "idts", "aprop",
   367     "asms", SynExt.any_, SynExt.sprop, "num_const", "index", "struct"]);
   368 
   369 
   370 
   371 (** print syntax **)
   372 
   373 local
   374 
   375 fun pretty_strs_qs name strs =
   376   Pretty.strs (name :: map Library.quote (sort_strings strs));
   377 
   378 fun pretty_gram (Syntax (tabs, _)) =
   379   let
   380     val {lexicon, prmodes, gram, prtabs, ...} = tabs;
   381     val prmodes' = sort_strings (filter_out (equal "") prmodes);
   382   in
   383     [pretty_strs_qs "lexicon:" (Scan.dest_lexicon lexicon),
   384       Pretty.big_list "prods:" (Parser.pretty_gram gram),
   385       pretty_strs_qs "print modes:" prmodes']
   386   end;
   387 
   388 fun pretty_trans (Syntax (tabs, _)) =
   389   let
   390     fun pretty_trtab name tab =
   391       pretty_strs_qs name (Symtab.keys tab);
   392 
   393     fun pretty_ruletab name tab =
   394       Pretty.big_list name (map Ast.pretty_rule (dest_ruletab tab));
   395 
   396     fun pretty_tokentr (mode, trs) = Pretty.strs (Library.quote mode ^ ":" :: map fst trs);
   397 
   398     val {consts, parse_ast_trtab, parse_ruletab, parse_trtab, print_trtab,
   399       print_ruletab, print_ast_trtab, tokentrtab, ...} = tabs;
   400   in
   401     [pretty_strs_qs "consts:" consts,
   402       pretty_trtab "parse_ast_translation:" parse_ast_trtab,
   403       pretty_ruletab "parse_rules:" parse_ruletab,
   404       pretty_trtab "parse_translation:" parse_trtab,
   405       pretty_trtab "print_translation:" print_trtab,
   406       pretty_ruletab "print_rules:" print_ruletab,
   407       pretty_trtab "print_ast_translation:" print_ast_trtab,
   408       Pretty.big_list "token_translation:" (map pretty_tokentr tokentrtab)]
   409   end;
   410 
   411 in
   412 
   413 fun print_gram syn = Pretty.writeln (Pretty.chunks (pretty_gram syn));
   414 fun print_trans syn = Pretty.writeln (Pretty.chunks (pretty_trans syn));
   415 fun print_syntax syn = Pretty.writeln (Pretty.chunks (pretty_gram syn @ pretty_trans syn));
   416 
   417 end;
   418 
   419 
   420 
   421 (** read **)
   422 
   423 (* read_ast *)
   424 
   425 val ambiguity_level = ref 1;
   426 val ambiguity_is_error = ref false;
   427 
   428 fun read_asts ctxt is_logtype (Syntax (tabs, _)) xids root str =
   429   let
   430     val {lexicon, gram, parse_ast_trtab, ...} = tabs;
   431     val root' = if root <> "prop" andalso is_logtype root then SynExt.logic else root;
   432     val chars = Symbol.explode str;
   433     val pts = Parser.parse gram root' (Lexicon.tokenize lexicon xids chars);
   434 
   435     fun show_pt pt =
   436       Pretty.string_of (Ast.pretty_ast (hd (SynTrans.pts_to_asts ctxt (K NONE) [pt])));
   437   in
   438     if length pts > ! ambiguity_level then
   439       if ! ambiguity_is_error then error ("Ambiguous input " ^ quote str)
   440       else (warning ("Ambiguous input " ^ quote str ^ "\n" ^
   441           "produces " ^ string_of_int (length pts) ^ " parse trees.");
   442          List.app (warning o show_pt) pts)
   443     else ();
   444     SynTrans.pts_to_asts ctxt (lookup_tr parse_ast_trtab) pts
   445   end;
   446 
   447 
   448 (* read *)
   449 
   450 fun read ctxt is_logtype (syn as Syntax (tabs, _)) ty str =
   451   let
   452     val {parse_ruletab, parse_trtab, ...} = tabs;
   453     val asts = read_asts ctxt is_logtype syn false (SynExt.typ_to_nonterm ty) str;
   454   in
   455     SynTrans.asts_to_terms ctxt (lookup_tr parse_trtab)
   456       (map (Ast.normalize_ast (Symtab.lookup_list parse_ruletab)) asts)
   457   end;
   458 
   459 
   460 (* read terms *)
   461 
   462 (*brute-force disambiguation via type-inference*)
   463 fun disambig _ _ [t] = t
   464   | disambig pp check ts =
   465       let
   466         val err_results = map check ts;
   467         val errs = map_filter (fn Exn.Exn (ERROR msg) => SOME msg | _ => NONE) err_results;
   468         val results = map_filter Exn.get_result err_results;
   469 
   470         val ambiguity = length ts;
   471         fun ambig_msg () =
   472           if ambiguity > 1 andalso ambiguity <= ! ambiguity_level then
   473             "Got more than one parse tree.\n\
   474             \Retry with smaller ambiguity_level for more information."
   475           else "";
   476       in
   477         if null results then cat_error (ambig_msg ()) (cat_lines errs)
   478         else if length results = 1 then
   479           (if ambiguity > ! ambiguity_level then
   480             warning "Fortunately, only one parse tree is type correct.\n\
   481               \You may still want to disambiguate your grammar or your input."
   482           else (); hd results)
   483         else cat_error (ambig_msg ()) ("More than one term is type correct:\n" ^
   484           cat_lines (map (Pretty.string_of_term pp) ts))
   485       end;
   486 
   487 fun standard_parse_term pp check get_sort map_const map_free map_type map_sort
   488     ctxt is_logtype syn ty str =
   489   read ctxt is_logtype syn ty str
   490   |> map (TypeExt.decode_term get_sort map_const map_free map_type map_sort)
   491   |> disambig (Printer.pp_show_brackets pp) check;
   492 
   493 
   494 (* read types *)
   495 
   496 fun standard_parse_typ ctxt syn get_sort map_sort str =
   497   (case read ctxt (K false) syn SynExt.typeT str of
   498     [t] => TypeExt.typ_of_term (get_sort (TypeExt.term_sorts map_sort t)) map_sort t
   499   | _ => error "read_typ: ambiguous syntax");
   500 
   501 
   502 (* read sorts *)
   503 
   504 fun standard_parse_sort ctxt syn map_sort str =
   505   (case read ctxt (K false) syn TypeExt.sortT str of
   506     [t] => TypeExt.sort_of_term map_sort t
   507   | _ => error "read_sort: ambiguous syntax");
   508 
   509 
   510 
   511 (** prepare translation rules **)
   512 
   513 datatype 'a trrule =
   514   ParseRule of 'a * 'a |
   515   PrintRule of 'a * 'a |
   516   ParsePrintRule of 'a * 'a;
   517 
   518 fun map_trrule f (ParseRule (x, y)) = ParseRule (f x, f y)
   519   | map_trrule f (PrintRule (x, y)) = PrintRule (f x, f y)
   520   | map_trrule f (ParsePrintRule (x, y)) = ParsePrintRule (f x, f y);
   521 
   522 fun parse_rule (ParseRule pats) = SOME pats
   523   | parse_rule (PrintRule _) = NONE
   524   | parse_rule (ParsePrintRule pats) = SOME pats;
   525 
   526 fun print_rule (ParseRule _) = NONE
   527   | print_rule (PrintRule pats) = SOME (swap pats)
   528   | print_rule (ParsePrintRule pats) = SOME (swap pats);
   529 
   530 
   531 local
   532 
   533 fun check_rule (rule as (lhs, rhs)) =
   534   (case Ast.rule_error rule of
   535     SOME msg =>
   536       error ("Error in syntax translation rule: " ^ msg ^ "\n" ^
   537         Ast.str_of_ast lhs ^ "  ->  " ^ Ast.str_of_ast rhs)
   538   | NONE => rule);
   539 
   540 
   541 fun read_pattern ctxt is_logtype syn (root, str) =
   542   let
   543     val Syntax ({consts, ...}, _) = syn;
   544 
   545     fun constify (ast as Ast.Constant _) = ast
   546       | constify (ast as Ast.Variable x) =
   547           if member (op =) consts x orelse NameSpace.is_qualified x then Ast.Constant x
   548           else ast
   549       | constify (Ast.Appl asts) = Ast.Appl (map constify asts);
   550   in
   551     (case read_asts ctxt is_logtype syn true root str of
   552       [ast] => constify ast
   553     | _ => error ("Syntactically ambiguous input: " ^ quote str))
   554   end handle ERROR msg =>
   555     cat_error msg ("The error(s) above occurred in translation pattern " ^
   556       quote str);
   557 
   558 fun prep_rules rd_pat raw_rules =
   559   let val rules = map (map_trrule rd_pat) raw_rules in
   560     (map check_rule (map_filter parse_rule rules),
   561       map check_rule (map_filter print_rule rules))
   562   end
   563 
   564 in
   565 
   566 val cert_rules = prep_rules I;
   567 
   568 fun read_rules ctxt is_logtype syn =
   569   prep_rules (read_pattern ctxt is_logtype syn);
   570 
   571 end;
   572 
   573 
   574 
   575 (** pretty terms, typs, sorts **)
   576 
   577 fun pretty_t t_to_ast prt_t markup ctxt (syn as Syntax (tabs, _)) curried t =
   578   let
   579     val {print_trtab, print_ruletab, print_ast_trtab, tokentrtab, prtabs, ...} = tabs;
   580     val ast = t_to_ast ctxt (lookup_tr' print_trtab) t;
   581   in
   582     Pretty.markup markup (prt_t ctxt curried prtabs (lookup_tr' print_ast_trtab)
   583       (lookup_tokentr tokentrtab (print_mode_value ()))
   584       (Ast.normalize_ast (Symtab.lookup_list print_ruletab) ast))
   585   end;
   586 
   587 fun pretty_term extern =
   588   pretty_t Printer.term_to_ast (Printer.pretty_term_ast extern) Markup.term;
   589 fun pretty_typ ctxt syn =
   590   pretty_t Printer.typ_to_ast Printer.pretty_typ_ast Markup.typ ctxt syn false;
   591 fun pretty_sort ctxt syn =
   592   pretty_t Printer.sort_to_ast Printer.pretty_typ_ast Markup.sort ctxt syn false;
   593 
   594 
   595 
   596 (** modify syntax **)
   597 
   598 fun ext_syntax' f is_logtype prmode decls = extend_syntax prmode (f is_logtype decls);
   599 fun ext_syntax f = ext_syntax' (K f) (K false) default_mode;
   600 
   601 val extend_type_gram       = ext_syntax Mixfix.syn_ext_types;
   602 val extend_const_gram      = ext_syntax' Mixfix.syn_ext_consts;
   603 val extend_consts          = ext_syntax SynExt.syn_ext_const_names;
   604 val extend_trfuns          = ext_syntax SynExt.syn_ext_trfuns;
   605 val extend_advanced_trfuns = ext_syntax SynExt.syn_ext_advanced_trfuns;
   606 val extend_tokentrfuns     = ext_syntax SynExt.syn_ext_tokentrfuns;
   607 
   608 fun remove_const_gram is_logtype prmode decls =
   609   remove_syntax prmode (Mixfix.syn_ext_consts is_logtype decls);
   610 
   611 fun extend_trrules ctxt is_logtype syn =
   612   ext_syntax SynExt.syn_ext_rules o read_rules ctxt is_logtype syn;
   613 
   614 fun remove_trrules ctxt is_logtype syn =
   615   remove_syntax default_mode o SynExt.syn_ext_rules o read_rules ctxt is_logtype syn;
   616 
   617 val extend_trrules_i = ext_syntax SynExt.syn_ext_rules o cert_rules;
   618 val remove_trrules_i = remove_syntax default_mode o SynExt.syn_ext_rules o cert_rules;
   619 
   620 
   621 
   622 (** inner syntax operations **)
   623 
   624 (* (un)parsing *)
   625 
   626 local
   627   type operations =
   628    {parse_sort: Proof.context -> string -> sort,
   629     parse_typ: Proof.context -> string -> typ,
   630     parse_term: Proof.context -> string -> term,
   631     parse_prop: Proof.context -> string -> term,
   632     unparse_sort: Proof.context -> sort -> Pretty.T,
   633     unparse_typ: Proof.context -> typ -> Pretty.T,
   634     unparse_term: Proof.context -> term -> Pretty.T};
   635 
   636   val operations = ref (NONE: operations option);
   637 
   638   fun operation which ctxt x =
   639     (case ! operations of
   640       NONE => error "Inner syntax operations not yet installed"
   641     | SOME ops => which ops ctxt x);
   642 in
   643 
   644 val parse_sort = operation #parse_sort;
   645 val parse_typ = operation #parse_typ;
   646 val parse_term = operation #parse_term;
   647 val parse_prop = operation #parse_prop;
   648 val unparse_sort = operation #unparse_sort;
   649 val unparse_typ = operation #unparse_typ;
   650 val unparse_term = operation #unparse_term;
   651 
   652 fun install_operations ops = CRITICAL (fn () =>
   653   if is_some (! operations) then error "Inner syntax operations already installed"
   654   else operations := SOME ops);
   655 
   656 end;
   657 
   658 
   659 (* context-sensitive (un)checking *)
   660 
   661 local
   662 
   663 type key = int * bool;
   664 type 'a check = 'a list -> Proof.context -> 'a list * Proof.context;
   665 
   666 structure Checks = GenericDataFun
   667 (
   668   type T =
   669     ((key * ((string * typ check) * stamp) list) list *
   670      (key * ((string * term check) * stamp) list) list);
   671   val empty = ([], []);
   672   val extend = I;
   673   fun merge _ ((typ_checks1, term_checks1), (typ_checks2, term_checks2)) : T =
   674     (AList.join (op =) (K (Library.merge (eq_snd (op =)))) (typ_checks1, typ_checks2),
   675      AList.join (op =) (K (Library.merge (eq_snd (op =)))) (term_checks1, term_checks2));
   676 );
   677 
   678 fun gen_add which (key: key) name f =
   679   Checks.map (which (AList.map_default op = (key, []) (cons ((name, f), stamp ()))));
   680 
   681 fun gen_check which uncheck eq ctxt0 xs0 =
   682   let
   683     val funs = which (Checks.get (Context.Proof ctxt0))
   684       |> map_filter (fn ((i, u), fs) => if uncheck = u then SOME (i, map (snd o fst) fs) else NONE)
   685       |> Library.sort (int_ord o pairself fst)
   686       |> not uncheck ? map (apsnd rev);
   687 
   688     fun check_fixpoint fs (xs, ctxt) =
   689       let val (xs', ctxt') = fold uncurry fs (xs, ctxt) in
   690         if eq_list eq (xs, xs') then (xs, ctxt)
   691         else check_fixpoint fs (xs', ctxt')
   692       end;
   693   in #1 (fold (check_fixpoint o snd) funs (xs0, ctxt0)) end;
   694 
   695 fun map_sort f S =
   696   (case f (TFree ("", S)) of
   697     TFree ("", S') => S'
   698   | T => raise TYPE ("map_sort", [TFree ("", S), T], []));
   699 
   700 in
   701 
   702 fun print_checks ctxt =
   703   let
   704     fun split_checks checks =
   705       List.partition (fn ((_, un), _) => not un) checks
   706       |> pairself (map (fn ((i, _), fs) => (i, map (fst o fst) fs))
   707           #> sort (int_ord o pairself fst));
   708     fun pretty_checks kind checks =
   709       checks |> map (fn (i, names) => Pretty.block
   710         [Pretty.str (kind ^ " (stage " ^ signed_string_of_int i ^ "):"),
   711           Pretty.brk 1, Pretty.strs names]);
   712 
   713     val (typs, terms) = Checks.get (Context.Proof ctxt);
   714     val (typ_checks, typ_unchecks) = split_checks typs;
   715     val (term_checks, term_unchecks) = split_checks terms;
   716   in
   717     pretty_checks "typ_checks" typ_checks @
   718     pretty_checks "term_checks" term_checks @
   719     pretty_checks "typ_unchecks" typ_unchecks @
   720     pretty_checks "term_unchecks" term_unchecks
   721   end |> Pretty.chunks |> Pretty.writeln;
   722 
   723 fun add_typ_check stage = gen_add apfst (stage, false);
   724 fun add_term_check stage = gen_add apsnd (stage, false);
   725 fun add_typ_uncheck stage = gen_add apfst (stage, true);
   726 fun add_term_uncheck stage = gen_add apsnd (stage, true);
   727 
   728 val check_typs = gen_check fst false (op =);
   729 val check_terms = gen_check snd false (op aconv);
   730 fun check_props ctxt = map (TypeInfer.constrain propT) #> check_terms ctxt;
   731 
   732 val check_typ = singleton o check_typs;
   733 val check_term = singleton o check_terms;
   734 val check_prop = singleton o check_props;
   735 val check_sort = map_sort o check_typ;
   736 
   737 val uncheck_typs = gen_check fst true (op =);
   738 val uncheck_terms = gen_check snd true (op aconv);
   739 val uncheck_sort = map_sort o singleton o uncheck_typs;
   740 
   741 end;
   742 
   743 
   744 (* combined operations *)
   745 
   746 fun read_sort ctxt = parse_sort ctxt #> check_sort ctxt;
   747 fun read_typ ctxt = parse_typ ctxt #> singleton (check_typs ctxt);
   748 
   749 fun read_terms ctxt = map (parse_term ctxt) #> check_terms ctxt;
   750 fun read_props ctxt = map (parse_prop ctxt) #> check_props ctxt;
   751 
   752 val read_term = singleton o read_terms;
   753 val read_prop = singleton o read_props;
   754 
   755 val read_sort_global = read_sort o ProofContext.init;
   756 val read_typ_global = read_typ o ProofContext.init;
   757 val read_term_global = read_term o ProofContext.init;
   758 val read_prop_global = read_prop o ProofContext.init;
   759 
   760 
   761 (*export parts of internal Syntax structures*)
   762 open Lexicon SynExt Ast Parser TypeExt SynTrans Mixfix Printer;
   763 
   764 end;
   765 
   766 structure BasicSyntax: BASIC_SYNTAX = Syntax;
   767 open BasicSyntax;
   768 
   769 structure Hidden = struct end;
   770 structure Ast = Hidden;
   771 structure SynExt = Hidden;
   772 structure Parser = Hidden;
   773 structure TypeExt = Hidden;
   774 structure SynTrans = Hidden;
   775 structure Mixfix = Hidden;
   776 structure Printer = Hidden;