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