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