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