src/Pure/Syntax/syntax.ML
author haftmann
Fri Dec 05 18:42:37 2008 +0100 (2008-12-05)
changeset 29004 a5a91f387791
parent 28904 3ef9489eeef5
child 29134 9657871890c7
permissions -rw-r--r--
removed Table.extend, NameSpace.extend_table
     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 = fold Symtab.update_new trfuns (remove_trtab trfuns tab)
   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", "float_const",
   395     "index", "struct"]);
   396 
   397 
   398 
   399 (** print syntax **)
   400 
   401 local
   402 
   403 fun pretty_strs_qs name strs =
   404   Pretty.strs (name :: map quote (sort_strings strs));
   405 
   406 fun pretty_gram (Syntax (tabs, _)) =
   407   let
   408     val {lexicon, prmodes, gram, prtabs, ...} = tabs;
   409     val prmodes' = sort_strings (filter_out (fn s => s = "") prmodes);
   410   in
   411     [pretty_strs_qs "lexicon:" (Scan.dest_lexicon lexicon),
   412       Pretty.big_list "prods:" (Parser.pretty_gram gram),
   413       pretty_strs_qs "print modes:" prmodes']
   414   end;
   415 
   416 fun pretty_trans (Syntax (tabs, _)) =
   417   let
   418     fun pretty_trtab name tab =
   419       pretty_strs_qs name (Symtab.keys tab);
   420 
   421     fun pretty_ruletab name tab =
   422       Pretty.big_list name (map Ast.pretty_rule (dest_ruletab tab));
   423 
   424     fun pretty_tokentr (mode, trs) = Pretty.strs (quote mode ^ ":" :: map fst trs);
   425 
   426     val {consts, parse_ast_trtab, parse_ruletab, parse_trtab, print_trtab,
   427       print_ruletab, print_ast_trtab, tokentrtab, ...} = tabs;
   428   in
   429     [pretty_strs_qs "consts:" consts,
   430       pretty_trtab "parse_ast_translation:" parse_ast_trtab,
   431       pretty_ruletab "parse_rules:" parse_ruletab,
   432       pretty_trtab "parse_translation:" parse_trtab,
   433       pretty_trtab "print_translation:" print_trtab,
   434       pretty_ruletab "print_rules:" print_ruletab,
   435       pretty_trtab "print_ast_translation:" print_ast_trtab,
   436       Pretty.big_list "token_translation:" (map pretty_tokentr tokentrtab)]
   437   end;
   438 
   439 in
   440 
   441 fun print_gram syn = Pretty.writeln (Pretty.chunks (pretty_gram syn));
   442 fun print_trans syn = Pretty.writeln (Pretty.chunks (pretty_trans syn));
   443 fun print_syntax syn = Pretty.writeln (Pretty.chunks (pretty_gram syn @ pretty_trans syn));
   444 
   445 end;
   446 
   447 
   448 (* reconstructing infixes -- educated guessing *)
   449 
   450 fun guess_infix (Syntax ({gram, ...}, _)) c =
   451   (case Parser.guess_infix_lr gram c of
   452     SOME (s, l, r, j) => SOME
   453      (if l then Mixfix.InfixlName (s, j)
   454       else if r then Mixfix.InfixrName (s, j)
   455       else Mixfix.InfixName (s, j))
   456   | NONE => NONE);
   457 
   458 
   459 
   460 (** read **)
   461 
   462 (* read token -- with optional YXML encoding of position *)
   463 
   464 fun read_token str =
   465   let val (text, pos) =
   466     (case YXML.parse str handle Fail msg => error msg of
   467       XML.Elem ("token", props, [XML.Text text]) => (text, Position.of_properties props)
   468     | XML.Elem ("token", props, []) => ("", Position.of_properties props)
   469     | XML.Text text => (text, Position.none)
   470     | _ => (str, Position.none))
   471   in (SymbolPos.explode (text, pos), pos) end;
   472 
   473 
   474 (* read_ast *)
   475 
   476 val ambiguity_is_error = ref false;
   477 val ambiguity_level = ref 1;
   478 val ambiguity_limit = ref 10;
   479 
   480 fun ambiguity_msg pos = "Parse error: ambiguous syntax" ^ Position.str_of pos;
   481 
   482 fun read_asts ctxt is_logtype (Syntax (tabs, _)) xids root (syms, pos) =
   483   let
   484     val {lexicon, gram, parse_ast_trtab, ...} = tabs;
   485     val toks = Lexicon.tokenize lexicon xids syms;
   486     val _ = List.app Lexicon.report_token toks;
   487 
   488     val root' = if root <> "prop" andalso is_logtype root then SynExt.logic else root;
   489     val pts = Parser.parse gram root' (filter Lexicon.is_proper toks);
   490     val len = length pts;
   491 
   492     val limit = ! ambiguity_limit;
   493     fun show_pt pt =
   494       Pretty.string_of (Ast.pretty_ast (hd (SynTrans.pts_to_asts ctxt (K NONE) [pt])));
   495   in
   496     if len <= ! ambiguity_level then ()
   497     else if ! ambiguity_is_error then error (ambiguity_msg pos)
   498     else
   499       (warning (cat_lines
   500         (("Ambiguous input " ^ Position.str_of pos ^
   501           "\nproduces " ^ string_of_int len ^ " parse trees" ^
   502           (if len <= limit then "" else " (" ^ string_of_int limit ^ " displayed)") ^ ":") ::
   503           map show_pt (Library.take (limit, pts)))));
   504     SynTrans.pts_to_asts ctxt (lookup_tr parse_ast_trtab) pts
   505   end;
   506 
   507 
   508 (* read *)
   509 
   510 fun read ctxt is_logtype (syn as Syntax (tabs, _)) ty inp =
   511   let
   512     val {parse_ruletab, parse_trtab, ...} = tabs;
   513     val asts = read_asts ctxt is_logtype syn false (SynExt.typ_to_nonterm ty) inp;
   514   in
   515     SynTrans.asts_to_terms ctxt (lookup_tr parse_trtab)
   516       (map (Ast.normalize_ast (Symtab.lookup_list parse_ruletab)) asts)
   517   end;
   518 
   519 
   520 (* read terms *)
   521 
   522 (*brute-force disambiguation via type-inference*)
   523 fun disambig _ _ [t] = t
   524   | disambig pp check ts =
   525       let
   526         val level = ! ambiguity_level;
   527         val limit = ! ambiguity_limit;
   528 
   529         val ambiguity = length ts;
   530         fun ambig_msg () =
   531           if ambiguity > 1 andalso ambiguity <= level then
   532             "Got more than one parse tree.\n\
   533             \Retry with smaller Syntax.ambiguity_level for more information."
   534           else "";
   535 
   536         val errs = map check ts;
   537         val results = map_filter (fn (t, NONE) => SOME t | _ => NONE) (ts ~~ errs);
   538         val len = length results;
   539       in
   540         if null results then cat_error (ambig_msg ()) (cat_lines (map_filter I errs))
   541         else if len = 1 then
   542           (if ambiguity > level then
   543             warning "Fortunately, only one parse tree is type correct.\n\
   544               \You may still want to disambiguate your grammar or your input."
   545           else (); hd results)
   546         else cat_error (ambig_msg ()) (cat_lines
   547           (("Ambiguous input, " ^ string_of_int len ^ " terms are type correct" ^
   548             (if len <= limit then "" else " (" ^ string_of_int limit ^ " displayed)") ^ ":") ::
   549             map (Pretty.string_of_term pp) (Library.take (limit, results))))
   550       end;
   551 
   552 fun standard_parse_term pp check get_sort map_const map_free map_type map_sort
   553     ctxt is_logtype syn ty (syms, pos) =
   554   read ctxt is_logtype syn ty (syms, pos)
   555   |> map (TypeExt.decode_term get_sort map_const map_free map_type map_sort)
   556   |> disambig (Printer.pp_show_brackets pp) check;
   557 
   558 
   559 (* read types *)
   560 
   561 fun standard_parse_typ ctxt syn get_sort map_sort (syms, pos) =
   562   (case read ctxt (K false) syn SynExt.typeT (syms, pos) of
   563     [t] => TypeExt.typ_of_term (get_sort (TypeExt.term_sorts map_sort t)) map_sort t
   564   | _ => error (ambiguity_msg pos));
   565 
   566 
   567 (* read sorts *)
   568 
   569 fun standard_parse_sort ctxt syn map_sort (syms, pos) =
   570   (case read ctxt (K false) syn TypeExt.sortT (syms, pos) of
   571     [t] => TypeExt.sort_of_term map_sort t
   572   | _ => error (ambiguity_msg pos));
   573 
   574 
   575 
   576 (** prepare translation rules **)
   577 
   578 datatype 'a trrule =
   579   ParseRule of 'a * 'a |
   580   PrintRule of 'a * 'a |
   581   ParsePrintRule of 'a * 'a;
   582 
   583 fun map_trrule f (ParseRule (x, y)) = ParseRule (f x, f y)
   584   | map_trrule f (PrintRule (x, y)) = PrintRule (f x, f y)
   585   | map_trrule f (ParsePrintRule (x, y)) = ParsePrintRule (f x, f y);
   586 
   587 fun parse_rule (ParseRule pats) = SOME pats
   588   | parse_rule (PrintRule _) = NONE
   589   | parse_rule (ParsePrintRule pats) = SOME pats;
   590 
   591 fun print_rule (ParseRule _) = NONE
   592   | print_rule (PrintRule pats) = SOME (swap pats)
   593   | print_rule (ParsePrintRule pats) = SOME (swap pats);
   594 
   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     val Syntax ({consts, ...}, _) = syn;
   608 
   609     fun constify (ast as Ast.Constant _) = ast
   610       | constify (ast as Ast.Variable x) =
   611           if member (op =) consts x orelse NameSpace.is_qualified x then Ast.Constant x
   612           else ast
   613       | constify (Ast.Appl asts) = Ast.Appl (map constify asts);
   614 
   615     val (syms, pos) = read_token str;
   616   in
   617     (case read_asts ctxt is_logtype syn true root (syms, pos) of
   618       [ast] => constify ast
   619     | _ => error (ambiguity_msg pos))
   620   end;
   621 
   622 fun prep_rules rd_pat raw_rules =
   623   let val rules = map (map_trrule rd_pat) raw_rules in
   624     (map check_rule (map_filter parse_rule rules),
   625       map check_rule (map_filter print_rule rules))
   626   end
   627 
   628 in
   629 
   630 val cert_rules = prep_rules I;
   631 
   632 fun read_rules ctxt is_logtype syn =
   633   prep_rules (read_pattern ctxt is_logtype syn);
   634 
   635 end;
   636 
   637 
   638 
   639 (** unparse terms, typs, sorts **)
   640 
   641 local
   642 
   643 fun unparse_t t_to_ast prt_t markup ctxt (syn as Syntax (tabs, _)) curried t =
   644   let
   645     val {print_trtab, print_ruletab, print_ast_trtab, tokentrtab, prtabs, ...} = tabs;
   646     val ast = t_to_ast ctxt (lookup_tr' print_trtab) t;
   647   in
   648     Pretty.markup markup (prt_t ctxt curried prtabs (lookup_tr' print_ast_trtab)
   649       (lookup_tokentr tokentrtab (print_mode_value ()))
   650       (Ast.normalize_ast (Symtab.lookup_list print_ruletab) ast))
   651   end;
   652 
   653 in
   654 
   655 fun standard_unparse_term extern =
   656   unparse_t Printer.term_to_ast (Printer.pretty_term_ast extern) Markup.term;
   657 
   658 fun standard_unparse_typ ctxt syn =
   659   unparse_t Printer.typ_to_ast Printer.pretty_typ_ast Markup.typ ctxt syn false;
   660 
   661 fun standard_unparse_sort ctxt syn =
   662   unparse_t Printer.sort_to_ast Printer.pretty_typ_ast Markup.sort ctxt syn false;
   663 
   664 end;
   665 
   666 
   667 
   668 (** modify syntax **)
   669 
   670 fun ext_syntax f decls = update_syntax mode_default (f decls);
   671 
   672 val update_type_gram       = ext_syntax Mixfix.syn_ext_types;
   673 val update_consts          = ext_syntax SynExt.syn_ext_const_names;
   674 val update_trfuns          = ext_syntax SynExt.syn_ext_trfuns;
   675 val update_advanced_trfuns = ext_syntax SynExt.syn_ext_advanced_trfuns;
   676 val extend_tokentrfuns     = ext_syntax SynExt.syn_ext_tokentrfuns;
   677 
   678 fun update_const_gram is_logtype prmode decls =
   679   update_syntax prmode (Mixfix.syn_ext_consts is_logtype decls);
   680 
   681 fun remove_const_gram is_logtype prmode decls =
   682   remove_syntax prmode (Mixfix.syn_ext_consts is_logtype decls);
   683 
   684 fun update_trrules ctxt is_logtype syn =
   685   ext_syntax SynExt.syn_ext_rules o read_rules ctxt is_logtype syn;
   686 
   687 fun remove_trrules ctxt is_logtype syn =
   688   remove_syntax mode_default o SynExt.syn_ext_rules o read_rules ctxt is_logtype syn;
   689 
   690 val update_trrules_i = ext_syntax SynExt.syn_ext_rules o cert_rules;
   691 val remove_trrules_i = remove_syntax mode_default o SynExt.syn_ext_rules o cert_rules;
   692 
   693 
   694 
   695 (** inner syntax operations **)
   696 
   697 (* (un)parsing *)
   698 
   699 fun parse_token markup str =
   700   let
   701     val (syms, pos) = read_token str;
   702     val _ = Position.report markup pos;
   703   in (syms, pos) end;
   704 
   705 local
   706   type operations =
   707    {parse_sort: Proof.context -> string -> sort,
   708     parse_typ: Proof.context -> string -> typ,
   709     parse_term: Proof.context -> string -> term,
   710     parse_prop: Proof.context -> string -> term,
   711     unparse_sort: Proof.context -> sort -> Pretty.T,
   712     unparse_typ: Proof.context -> typ -> Pretty.T,
   713     unparse_term: Proof.context -> term -> Pretty.T};
   714 
   715   val operations = ref (NONE: operations option);
   716 
   717   fun operation which ctxt x =
   718     (case ! operations of
   719       NONE => error "Inner syntax operations not yet installed"
   720     | SOME ops => which ops ctxt x);
   721 in
   722 
   723 val parse_sort = operation #parse_sort;
   724 val parse_typ = operation #parse_typ;
   725 val parse_term = operation #parse_term;
   726 val parse_prop = operation #parse_prop;
   727 val unparse_sort = operation #unparse_sort;
   728 val unparse_typ = operation #unparse_typ;
   729 val unparse_term = operation #unparse_term;
   730 
   731 fun install_operations ops = CRITICAL (fn () =>
   732   if is_some (! operations) then error "Inner syntax operations already installed"
   733   else operations := SOME ops);
   734 
   735 end;
   736 
   737 
   738 (* context-sensitive (un)checking *)
   739 
   740 local
   741 
   742 type key = int * bool;
   743 type 'a check = 'a list -> Proof.context -> ('a list * Proof.context) option;
   744 
   745 structure Checks = GenericDataFun
   746 (
   747   type T =
   748     ((key * ((string * typ check) * stamp) list) list *
   749      (key * ((string * term check) * stamp) list) list);
   750   val empty = ([], []);
   751   val extend = I;
   752   fun merge _ ((typ_checks1, term_checks1), (typ_checks2, term_checks2)) : T =
   753     (AList.join (op =) (K (Library.merge (eq_snd (op =)))) (typ_checks1, typ_checks2),
   754      AList.join (op =) (K (Library.merge (eq_snd (op =)))) (term_checks1, term_checks2));
   755 );
   756 
   757 fun gen_add which (key: key) name f =
   758   Checks.map (which (AList.map_default op = (key, []) (cons ((name, f), stamp ()))));
   759 
   760 fun check_stage fs = perhaps_loop (perhaps_apply (map uncurry fs));
   761 
   762 fun gen_check which uncheck ctxt0 xs0 =
   763   let
   764     val funs = which (Checks.get (Context.Proof ctxt0))
   765       |> map_filter (fn ((i, u), fs) => if uncheck = u then SOME (i, map (snd o fst) fs) else NONE)
   766       |> Library.sort (int_ord o pairself fst) |> map snd
   767       |> not uncheck ? map rev;
   768     val check_all = perhaps_apply (map check_stage funs);
   769   in #1 (perhaps check_all (xs0, ctxt0)) end;
   770 
   771 fun map_sort f S =
   772   (case f (TFree ("", S)) of
   773     TFree ("", S') => S'
   774   | _ => raise TYPE ("map_sort", [TFree ("", S)], []));
   775 
   776 in
   777 
   778 fun print_checks ctxt =
   779   let
   780     fun split_checks checks =
   781       List.partition (fn ((_, un), _) => not un) checks
   782       |> pairself (map (fn ((i, _), fs) => (i, map (fst o fst) fs))
   783           #> sort (int_ord o pairself fst));
   784     fun pretty_checks kind checks =
   785       checks |> map (fn (i, names) => Pretty.block
   786         [Pretty.str (kind ^ " (stage " ^ signed_string_of_int i ^ "):"),
   787           Pretty.brk 1, Pretty.strs names]);
   788 
   789     val (typs, terms) = Checks.get (Context.Proof ctxt);
   790     val (typ_checks, typ_unchecks) = split_checks typs;
   791     val (term_checks, term_unchecks) = split_checks terms;
   792   in
   793     pretty_checks "typ_checks" typ_checks @
   794     pretty_checks "term_checks" term_checks @
   795     pretty_checks "typ_unchecks" typ_unchecks @
   796     pretty_checks "term_unchecks" term_unchecks
   797   end |> Pretty.chunks |> Pretty.writeln;
   798 
   799 fun add_typ_check stage = gen_add apfst (stage, false);
   800 fun add_term_check stage = gen_add apsnd (stage, false);
   801 fun add_typ_uncheck stage = gen_add apfst (stage, true);
   802 fun add_term_uncheck stage = gen_add apsnd (stage, true);
   803 
   804 val check_typs = gen_check fst false;
   805 val check_terms = gen_check snd false;
   806 fun check_props ctxt = map (TypeExt.type_constraint propT) #> check_terms ctxt;
   807 
   808 val check_typ = singleton o check_typs;
   809 val check_term = singleton o check_terms;
   810 val check_prop = singleton o check_props;
   811 val check_sort = map_sort o check_typ;
   812 
   813 val uncheck_typs = gen_check fst true;
   814 val uncheck_terms = gen_check snd true;
   815 val uncheck_sort = map_sort o singleton o uncheck_typs;
   816 
   817 end;
   818 
   819 
   820 (* derived operations for classrel and arity *)
   821 
   822 val uncheck_classrel = map o singleton o uncheck_sort;
   823 
   824 fun unparse_classrel ctxt cs = Pretty.block (flat
   825   (separate [Pretty.str " <", Pretty.brk 1] (map (single o unparse_sort ctxt o single) cs)));
   826 
   827 fun uncheck_arity ctxt (a, Ss, S) =
   828   let
   829     val T = Type (a, replicate (length Ss) dummyT);
   830     val a' =
   831       (case singleton (uncheck_typs ctxt) T of
   832         Type (a', _) => a'
   833       | T => raise TYPE ("uncheck_arity", [T], []));
   834     val Ss' = map (uncheck_sort ctxt) Ss;
   835     val S' = uncheck_sort ctxt S;
   836   in (a', Ss', S') end;
   837 
   838 fun unparse_arity ctxt (a, Ss, S) =
   839   let
   840     val prtT = unparse_typ ctxt (Type (a, []));
   841     val dom =
   842       if null Ss then []
   843       else [Pretty.list "(" ")" (map (unparse_sort ctxt) Ss), Pretty.brk 1];
   844   in Pretty.block ([prtT, Pretty.str " ::", Pretty.brk 1] @ dom @ [unparse_sort ctxt S]) end;
   845 
   846 
   847 (* read = parse + check *)
   848 
   849 fun read_sort ctxt = parse_sort ctxt #> check_sort ctxt;
   850 fun read_typ ctxt = parse_typ ctxt #> singleton (check_typs ctxt);
   851 
   852 fun read_terms ctxt = map (parse_term ctxt) #> check_terms ctxt;
   853 fun read_props ctxt = map (parse_prop ctxt) #> check_props ctxt;
   854 
   855 val read_term = singleton o read_terms;
   856 val read_prop = singleton o read_props;
   857 
   858 val read_sort_global = read_sort o ProofContext.init;
   859 val read_typ_global = read_typ o ProofContext.init;
   860 val read_term_global = read_term o ProofContext.init;
   861 val read_prop_global = read_prop o ProofContext.init;
   862 
   863 
   864 (* pretty = uncheck + unparse *)
   865 
   866 fun pretty_term ctxt = singleton (uncheck_terms ctxt) #> unparse_term ctxt;
   867 fun pretty_typ ctxt = singleton (uncheck_typs ctxt) #> unparse_typ ctxt;
   868 fun pretty_sort ctxt = uncheck_sort ctxt #> unparse_sort ctxt;
   869 fun pretty_classrel ctxt = uncheck_classrel ctxt #> unparse_classrel ctxt;
   870 fun pretty_arity ctxt = uncheck_arity ctxt #> unparse_arity ctxt;
   871 
   872 val string_of_term = Pretty.string_of oo pretty_term;
   873 val string_of_typ = Pretty.string_of oo pretty_typ;
   874 val string_of_sort = Pretty.string_of oo pretty_sort;
   875 val string_of_classrel = Pretty.string_of oo pretty_classrel;
   876 val string_of_arity = Pretty.string_of oo pretty_arity;
   877 
   878 
   879 (* global pretty printing *)
   880 
   881 structure PrettyGlobal = ProofDataFun(type T = bool fun init _ = false);
   882 val is_pretty_global = PrettyGlobal.get;
   883 val set_pretty_global = PrettyGlobal.put;
   884 val init_pretty_global = set_pretty_global true o ProofContext.init;
   885 
   886 val pretty_term_global = pretty_term o init_pretty_global;
   887 val pretty_typ_global = pretty_typ o init_pretty_global;
   888 val pretty_sort_global = pretty_sort o init_pretty_global;
   889 
   890 val string_of_term_global = string_of_term o init_pretty_global;
   891 val string_of_typ_global = string_of_typ o init_pretty_global;
   892 val string_of_sort_global = string_of_sort o init_pretty_global;
   893 
   894 
   895 (* pp operations -- deferred evaluation *)
   896 
   897 fun pp ctxt = Pretty.pp
   898  (fn x => pretty_term ctxt x,
   899   fn x => pretty_typ ctxt x,
   900   fn x => pretty_sort ctxt x,
   901   fn x => pretty_classrel ctxt x,
   902   fn x => pretty_arity ctxt x);
   903 
   904 fun pp_global thy = Pretty.pp
   905  (fn x => pretty_term_global thy x,
   906   fn x => pretty_typ_global thy x,
   907   fn x => pretty_sort_global thy x,
   908   fn x => pretty_classrel (init_pretty_global thy) x,
   909   fn x => pretty_arity (init_pretty_global thy) x);
   910 
   911 
   912 (*export parts of internal Syntax structures*)
   913 open Lexicon SynExt Ast Parser TypeExt SynTrans Mixfix Printer;
   914 
   915 end;
   916 
   917 structure BasicSyntax: BASIC_SYNTAX = Syntax;
   918 open BasicSyntax;
   919 
   920 forget_structure "Ast";
   921 forget_structure "SynExt";
   922 forget_structure "Parser";
   923 forget_structure "TypeExt";
   924 forget_structure "SynTrans";
   925 forget_structure "Mixfix";
   926 forget_structure "Printer";