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