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