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