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