src/Pure/Syntax/syntax.ML
author wenzelm
Sun, 23 Sep 2007 22:23:27 +0200
changeset 24680 0d355aa59e67
parent 24613 bc889c3d55a3
child 24709 ecfb9dcb6c4c
permissions -rw-r--r--
TypeInfer.constrain: canonical argument order;

(*  Title:      Pure/Syntax/syntax.ML
    ID:         $Id$
    Author:     Tobias Nipkow and Markus Wenzel, TU Muenchen

Standard Isabelle syntax, based on arbitrary context-free grammars
(specified by mixfix declarations).
*)

signature BASIC_SYNTAX =
sig
  include AST0
  include SYN_TRANS0
  include MIXFIX0
  include PRINTER0
end;

signature SYNTAX =
sig
  include AST1
  include LEXICON0
  include SYN_EXT0
  include TYPE_EXT0
  include SYN_TRANS1
  include MIXFIX1
  include PRINTER0
  val extend_trtab: string -> (string * ('a * stamp)) list ->
    ('a * stamp) Symtab.table -> ('a * stamp) Symtab.table
  val merge_trtabs: string -> ('a * stamp) Symtab.table -> ('a * stamp) Symtab.table ->
    ('a * stamp) Symtab.table
  val merge_tr'tabs: ('a * stamp) list Symtab.table -> ('a * stamp) list Symtab.table
    -> ('a * stamp) list Symtab.table
  val extend_tr'tab: (string * ('a * stamp)) list ->
    ('a * stamp) list Symtab.table -> ('a * stamp) list Symtab.table
  datatype 'a trrule =
    ParseRule of 'a * 'a |
    PrintRule of 'a * 'a |
    ParsePrintRule of 'a * 'a
  type syntax
  val eq_syntax: syntax * syntax -> bool
  val is_keyword: syntax -> string -> bool
  type mode
  val default_mode: mode
  val input_mode: mode
  val internalM: string
  val extend_type_gram: (string * int * mixfix) list -> syntax -> syntax
  val extend_const_gram: (string -> bool) ->
    mode -> (string * typ * mixfix) list -> syntax -> syntax
  val extend_consts: string list -> syntax -> syntax
  val extend_trfuns:
    (string * ((ast list -> ast) * stamp)) list *
    (string * ((term list -> term) * stamp)) list *
    (string * ((bool -> typ -> term list -> term) * stamp)) list *
    (string * ((ast list -> ast) * stamp)) list -> syntax -> syntax
  val extend_advanced_trfuns:
    (string * ((Proof.context -> ast list -> ast) * stamp)) list *
    (string * ((Proof.context -> term list -> term) * stamp)) list *
    (string * ((Proof.context -> bool -> typ -> term list -> term) * stamp)) list *
    (string * ((Proof.context -> ast list -> ast) * stamp)) list -> syntax -> syntax
  val extend_tokentrfuns: (string * string * (string -> output * int)) list -> syntax -> syntax
  val remove_const_gram: (string -> bool) ->
    mode -> (string * typ * mixfix) list -> syntax -> syntax
  val extend_trrules: Proof.context -> (string -> bool) -> syntax ->
    (string * string) trrule list -> syntax -> syntax
  val remove_trrules: Proof.context -> (string -> bool) -> syntax ->
    (string * string) trrule list -> syntax -> syntax
  val extend_trrules_i: ast trrule list -> syntax -> syntax
  val remove_trrules_i: ast trrule list -> syntax -> syntax
  val map_trrule: ('a -> 'b) -> 'a trrule -> 'b trrule
  val merge_syntaxes: syntax -> syntax -> syntax
  val basic_syn: syntax
  val basic_nonterms: string list
  val print_gram: syntax -> unit
  val print_trans: syntax -> unit
  val print_syntax: syntax -> unit
  val read: Proof.context -> (string -> bool) -> syntax -> typ -> string -> term list
  val standard_parse_term: Pretty.pp -> (term -> term Exn.result) ->
    (((string * int) * sort) list -> string * int -> Term.sort) ->
    (string -> string option) -> (string -> string option) ->
    (typ -> typ) -> (sort -> sort) -> Proof.context ->
    (string -> bool) -> syntax -> typ -> string -> term
  val standard_parse_typ: Proof.context -> syntax -> ((indexname * sort) list -> indexname -> sort) ->
    (sort -> sort) -> string -> typ
  val standard_parse_sort: Proof.context -> syntax -> (sort -> sort) -> string -> sort
  val pretty_term: (string -> xstring) -> Proof.context -> syntax -> bool -> term -> Pretty.T
  val pretty_typ: Proof.context -> syntax -> typ -> Pretty.T
  val pretty_sort: Proof.context -> syntax -> sort -> Pretty.T
  val ambiguity_level: int ref
  val ambiguity_is_error: bool ref
  val install_parsers:
   {sort: Proof.context -> string -> sort,
    typ: Proof.context -> string -> typ,
    term: Proof.context -> string -> term,
    prop: Proof.context -> string -> term} -> unit
  val parse_sort: Proof.context -> string -> sort
  val parse_typ: Proof.context -> string -> typ
  val parse_term: Proof.context -> string -> term
  val parse_prop: Proof.context -> string -> term
  val global_parse_sort: theory -> string -> sort
  val global_parse_typ: theory -> string -> typ
  val global_parse_term: theory -> string -> term
  val global_parse_prop: theory -> string -> term
  val check_sort: Proof.context -> sort -> sort
  val check_typ: Proof.context -> typ -> typ
  val check_term: Proof.context -> term -> term
  val check_prop: Proof.context -> term -> term
  val check_typs: Proof.context -> typ list -> typ list
  val check_terms: Proof.context -> term list -> term list
  val check_props: Proof.context -> term list -> term list
  val add_typ_check: (typ list -> Proof.context -> typ list * Proof.context) ->
    Context.generic -> Context.generic
  val add_term_check: (term list -> Proof.context -> term list * Proof.context) ->
    Context.generic -> Context.generic
  val read_sort: Proof.context -> string -> sort
  val read_typ: Proof.context -> string -> typ
  val read_term: Proof.context -> string -> term
  val read_prop: Proof.context -> string -> term
  val read_terms: Proof.context -> string list -> term list
  val read_props: Proof.context -> string list -> term list
  val global_read_sort: theory -> string -> sort
  val global_read_typ: theory -> string -> typ
  val global_read_term: theory -> string -> term
  val global_read_prop: theory -> string -> term
end;

structure Syntax: SYNTAX =
struct

(** tables of translation functions **)

(* parse (ast) translations *)

fun lookup_tr tab c = Option.map fst (Symtab.lookup tab c);

fun err_dup_trfun name c =
  error ("More than one " ^ name ^ " for " ^ quote c);

fun remove_trtab trfuns = fold (Symtab.remove SynExt.eq_trfun) trfuns;

fun extend_trtab name trfuns tab = Symtab.extend (remove_trtab trfuns tab, trfuns)
  handle Symtab.DUP c => err_dup_trfun name c;

fun merge_trtabs name tab1 tab2 = Symtab.merge SynExt.eq_trfun (tab1, tab2)
  handle Symtab.DUP c => err_dup_trfun name c;


(* print (ast) translations *)

fun lookup_tr' tab c = map fst (Symtab.lookup_list tab c);
fun extend_tr'tab trfuns = fold_rev Symtab.update_list trfuns;
fun remove_tr'tab trfuns = fold (Symtab.remove_list SynExt.eq_trfun) trfuns;
fun merge_tr'tabs tab1 tab2 = Symtab.merge_list SynExt.eq_trfun (tab1, tab2);



(** tables of token translation functions **)

fun lookup_tokentr tabs modes =
  let val trs = distinct (eq_fst (op =)) (maps (these o AList.lookup (op =) tabs) (modes @ [""]))
  in fn c => Option.map fst (AList.lookup (op =) trs c) end;

fun merge_tokentrtabs tabs1 tabs2 =
  let
    fun eq_tr ((c1, (_, s1)), (c2, (_, s2))) = c1 = c2 andalso s1 = s2;

    fun name (s, _) = implode (tl (Symbol.explode s));

    fun merge mode =
      let
        val trs1 = these (AList.lookup (op =) tabs1 mode);
        val trs2 = these (AList.lookup (op =) tabs2 mode);
        val trs = distinct eq_tr (trs1 @ trs2);
      in
        (case duplicates (eq_fst (op =)) trs of
          [] => (mode, trs)
        | dups => error ("More than one token translation function in mode " ^
            quote mode ^ " for " ^ commas_quote (map name dups)))
      end;
  in map merge (distinct (op =) (map fst (tabs1 @ tabs2))) end;

fun extend_tokentrtab tokentrs tabs =
  let
    fun ins_tokentr (m, c, f) =
      AList.default (op =) (m, [])
      #> AList.map_entry (op =) m (cons ("_" ^ c, (f, stamp ())));
  in merge_tokentrtabs tabs (fold ins_tokentr tokentrs []) end;



(** tables of translation rules **)

type ruletab = (Ast.ast * Ast.ast) list Symtab.table;

fun dest_ruletab tab = maps snd (Symtab.dest tab);


(* empty, extend, merge ruletabs *)

val extend_ruletab = fold_rev (fn r => Symtab.update_list (Ast.head_of_rule r, r));
val remove_ruletab = fold (fn r => Symtab.remove_list (op =) (Ast.head_of_rule r, r));
fun merge_ruletabs tab1 tab2 = Symtab.merge_list (op =) (tab1, tab2);



(** datatype syntax **)

datatype syntax =
  Syntax of {
    input: SynExt.xprod list,
    lexicon: Scan.lexicon,
    gram: Parser.gram,
    consts: string list,
    prmodes: string list,
    parse_ast_trtab: ((Proof.context -> Ast.ast list -> Ast.ast) * stamp) Symtab.table,
    parse_ruletab: ruletab,
    parse_trtab: ((Proof.context -> term list -> term) * stamp) Symtab.table,
    print_trtab: ((Proof.context -> bool -> typ -> term list -> term) * stamp) list Symtab.table,
    print_ruletab: ruletab,
    print_ast_trtab: ((Proof.context -> Ast.ast list -> Ast.ast) * stamp) list Symtab.table,
    tokentrtab: (string * (string * ((string -> output * int) * stamp)) list) list,
    prtabs: Printer.prtabs} * stamp;

fun eq_syntax (Syntax (_, s1), Syntax (_, s2)) = s1 = s2;

fun is_keyword (Syntax ({lexicon, ...}, _)) = Scan.is_literal lexicon o Symbol.explode;

type mode = string * bool;
val default_mode = ("", true);
val input_mode = ("input", true);
val internalM = "internal";


(* empty_syntax *)

val empty_syntax = Syntax
  ({input = [],
    lexicon = Scan.empty_lexicon,
    gram = Parser.empty_gram,
    consts = [],
    prmodes = [],
    parse_ast_trtab = Symtab.empty,
    parse_ruletab = Symtab.empty,
    parse_trtab = Symtab.empty,
    print_trtab = Symtab.empty,
    print_ruletab = Symtab.empty,
    print_ast_trtab = Symtab.empty,
    tokentrtab = [],
    prtabs = Printer.empty_prtabs}, stamp ());


(* extend_syntax *)

fun extend_syntax (mode, inout) syn_ext (Syntax (tabs, _)) =
  let
    val {input, lexicon, gram, consts = consts1, prmodes = prmodes1,
      parse_ast_trtab, parse_ruletab, parse_trtab, print_trtab, print_ruletab,
      print_ast_trtab, tokentrtab, prtabs} = tabs;
    val SynExt.SynExt {xprods, consts = consts2, prmodes = prmodes2,
      parse_ast_translation, parse_rules, parse_translation, print_translation, print_rules,
      print_ast_translation, token_translation} = syn_ext;
    fun if_inout xs = if inout then xs else [];
  in
    Syntax
    ({input = if_inout xprods @ input,
      lexicon = Scan.extend_lexicon (if_inout (SynExt.delims_of xprods)) lexicon,
      gram = Parser.extend_gram gram (if_inout xprods),
      consts = Library.merge (op =) (consts1, filter_out NameSpace.is_qualified consts2),
      prmodes = insert (op =) mode (Library.merge (op =) (prmodes1, prmodes2)),
      parse_ast_trtab =
        extend_trtab "parse ast translation" (if_inout parse_ast_translation) parse_ast_trtab,
      parse_ruletab = extend_ruletab (if_inout parse_rules) parse_ruletab,
      parse_trtab = extend_trtab "parse translation" (if_inout parse_translation) parse_trtab,
      print_trtab = extend_tr'tab print_translation print_trtab,
      print_ruletab = extend_ruletab print_rules print_ruletab,
      print_ast_trtab = extend_tr'tab print_ast_translation print_ast_trtab,
      tokentrtab = extend_tokentrtab token_translation tokentrtab,
      prtabs = Printer.extend_prtabs mode xprods prtabs}, stamp ())
  end;


(* remove_syntax *)

fun remove_syntax (mode, inout) syn_ext (Syntax (tabs, _)) =
  let
    val SynExt.SynExt {xprods, consts = _, prmodes = _,
      parse_ast_translation, parse_rules, parse_translation, print_translation, print_rules,
      print_ast_translation, token_translation = _} = syn_ext;
    val {input, lexicon, gram, consts, prmodes,
      parse_ast_trtab, parse_ruletab, parse_trtab, print_trtab, print_ruletab,
      print_ast_trtab, tokentrtab, prtabs} = tabs;
    val input' = if inout then subtract (op =) xprods input else input;
    fun if_inout xs = if inout then xs else [];
  in
    Syntax
    ({input = input',
      lexicon = if inout then Scan.make_lexicon (SynExt.delims_of input') else lexicon,
      gram = if inout then Parser.make_gram input' else gram,
      consts = consts,
      prmodes = prmodes,
      parse_ast_trtab = remove_trtab (if_inout parse_ast_translation) parse_ast_trtab,
      parse_ruletab = remove_ruletab (if_inout parse_rules) parse_ruletab,
      parse_trtab = remove_trtab (if_inout parse_translation) parse_trtab,
      print_trtab = remove_tr'tab print_translation print_trtab,
      print_ruletab = remove_ruletab print_rules print_ruletab,
      print_ast_trtab = remove_tr'tab print_ast_translation print_ast_trtab,
      tokentrtab = tokentrtab,
      prtabs = Printer.remove_prtabs mode xprods prtabs}, stamp ())
  end;


(* merge_syntaxes *)

fun merge_syntaxes (Syntax (tabs1, _)) (Syntax (tabs2, _)) =
  let
    val {input = input1, lexicon = lexicon1, gram = gram1, consts = consts1,
      prmodes = prmodes1, parse_ast_trtab = parse_ast_trtab1,
      parse_ruletab = parse_ruletab1, parse_trtab = parse_trtab1,
      print_trtab = print_trtab1, print_ruletab = print_ruletab1,
      print_ast_trtab = print_ast_trtab1, tokentrtab = tokentrtab1, prtabs = prtabs1} = tabs1;

    val {input = input2, lexicon = lexicon2, gram = gram2, consts = consts2,
      prmodes = prmodes2, parse_ast_trtab = parse_ast_trtab2,
      parse_ruletab = parse_ruletab2, parse_trtab = parse_trtab2,
      print_trtab = print_trtab2, print_ruletab = print_ruletab2,
      print_ast_trtab = print_ast_trtab2, tokentrtab = tokentrtab2, prtabs = prtabs2} = tabs2;
  in
    Syntax
    ({input = Library.merge (op =) (input1, input2),
      lexicon = Scan.merge_lexicons lexicon1 lexicon2,
      gram = Parser.merge_grams gram1 gram2,
      consts = sort_distinct string_ord (consts1 @ consts2),
      prmodes = Library.merge (op =) (prmodes1, prmodes2),
      parse_ast_trtab =
        merge_trtabs "parse ast translation" parse_ast_trtab1 parse_ast_trtab2,
      parse_ruletab = merge_ruletabs parse_ruletab1 parse_ruletab2,
      parse_trtab = merge_trtabs "parse translation" parse_trtab1 parse_trtab2,
      print_trtab = merge_tr'tabs print_trtab1 print_trtab2,
      print_ruletab = merge_ruletabs print_ruletab1 print_ruletab2,
      print_ast_trtab = merge_tr'tabs print_ast_trtab1 print_ast_trtab2,
      tokentrtab = merge_tokentrtabs tokentrtab1 tokentrtab2,
      prtabs = Printer.merge_prtabs prtabs1 prtabs2}, stamp ())
  end;


(* basic syntax *)

val basic_syn =
  empty_syntax
  |> extend_syntax default_mode TypeExt.type_ext
  |> extend_syntax default_mode SynExt.pure_ext;

val basic_nonterms =
  (Lexicon.terminals @ [SynExt.logic, "type", "types", "sort", "classes",
    SynExt.args, SynExt.cargs, "pttrn", "pttrns", "idt", "idts", "aprop",
    "asms", SynExt.any_, SynExt.sprop, "num_const", "index", "struct"]);



(** print syntax **)

local

fun pretty_strs_qs name strs =
  Pretty.strs (name :: map Library.quote (sort_strings strs));

fun pretty_gram (Syntax (tabs, _)) =
  let
    val {lexicon, prmodes, gram, prtabs, ...} = tabs;
    val prmodes' = sort_strings (filter_out (equal "") prmodes);
  in
    [pretty_strs_qs "lexicon:" (Scan.dest_lexicon lexicon),
      Pretty.big_list "prods:" (Parser.pretty_gram gram),
      pretty_strs_qs "print modes:" prmodes']
  end;

fun pretty_trans (Syntax (tabs, _)) =
  let
    fun pretty_trtab name tab =
      pretty_strs_qs name (Symtab.keys tab);

    fun pretty_ruletab name tab =
      Pretty.big_list name (map Ast.pretty_rule (dest_ruletab tab));

    fun pretty_tokentr (mode, trs) = Pretty.strs (Library.quote mode ^ ":" :: map fst trs);

    val {consts, parse_ast_trtab, parse_ruletab, parse_trtab, print_trtab,
      print_ruletab, print_ast_trtab, tokentrtab, ...} = tabs;
  in
    [pretty_strs_qs "consts:" consts,
      pretty_trtab "parse_ast_translation:" parse_ast_trtab,
      pretty_ruletab "parse_rules:" parse_ruletab,
      pretty_trtab "parse_translation:" parse_trtab,
      pretty_trtab "print_translation:" print_trtab,
      pretty_ruletab "print_rules:" print_ruletab,
      pretty_trtab "print_ast_translation:" print_ast_trtab,
      Pretty.big_list "token_translation:" (map pretty_tokentr tokentrtab)]
  end;

in

fun print_gram syn = Pretty.writeln (Pretty.chunks (pretty_gram syn));
fun print_trans syn = Pretty.writeln (Pretty.chunks (pretty_trans syn));
fun print_syntax syn = Pretty.writeln (Pretty.chunks (pretty_gram syn @ pretty_trans syn));

end;



(** read **)

(* read_ast *)

val ambiguity_level = ref 1;
val ambiguity_is_error = ref false;

fun read_asts ctxt is_logtype (Syntax (tabs, _)) xids root str =
  let
    val {lexicon, gram, parse_ast_trtab, ...} = tabs;
    val root' = if root <> "prop" andalso is_logtype root then SynExt.logic else root;
    val chars = Symbol.explode str;
    val pts = Parser.parse gram root' (Lexicon.tokenize lexicon xids chars);

    fun show_pt pt =
      Pretty.string_of (Ast.pretty_ast (hd (SynTrans.pts_to_asts ctxt (K NONE) [pt])));
  in
    if length pts > ! ambiguity_level then
      if ! ambiguity_is_error then error ("Ambiguous input " ^ quote str)
      else (warning ("Ambiguous input " ^ quote str ^ "\n" ^
          "produces " ^ string_of_int (length pts) ^ " parse trees.");
         List.app (warning o show_pt) pts)
    else ();
    SynTrans.pts_to_asts ctxt (lookup_tr parse_ast_trtab) pts
  end;


(* read *)

fun read ctxt is_logtype (syn as Syntax (tabs, _)) ty str =
  let
    val {parse_ruletab, parse_trtab, ...} = tabs;
    val asts = read_asts ctxt is_logtype syn false (SynExt.typ_to_nonterm ty) str;
  in
    SynTrans.asts_to_terms ctxt (lookup_tr parse_trtab)
      (map (Ast.normalize_ast (Symtab.lookup_list parse_ruletab)) asts)
  end;


(* read terms *)

(*brute-force disambiguation via type-inference*)
fun disambig _ _ [t] = t
  | disambig pp check ts =
      let
        val err_results = map check ts;
        val errs = map_filter (fn Exn.Exn (ERROR msg) => SOME msg | _ => NONE) err_results;
        val results = map_filter Exn.get_result err_results;

        val ambiguity = length ts;
        fun ambig_msg () =
          if ambiguity > 1 andalso ambiguity <= ! ambiguity_level then
            "Got more than one parse tree.\n\
            \Retry with smaller ambiguity_level for more information."
          else "";
      in
        if null results then cat_error (ambig_msg ()) (cat_lines errs)
        else if length results = 1 then
          (if ambiguity > ! ambiguity_level then
            warning "Fortunately, only one parse tree is type correct.\n\
              \You may still want to disambiguate your grammar or your input."
          else (); hd results)
        else cat_error (ambig_msg ()) ("More than one term is type correct:\n" ^
          cat_lines (map (Pretty.string_of_term pp) ts))
      end;

fun standard_parse_term pp check get_sort map_const map_free map_type map_sort
    ctxt is_logtype syn ty str =
  read ctxt is_logtype syn ty str
  |> map (TypeExt.decode_term get_sort map_const map_free map_type map_sort)
  |> disambig (Printer.pp_show_brackets pp) check;


(* read types *)

fun standard_parse_typ ctxt syn get_sort map_sort str =
  (case read ctxt (K false) syn SynExt.typeT str of
    [t] => TypeExt.typ_of_term (get_sort (TypeExt.term_sorts map_sort t)) map_sort t
  | _ => error "read_typ: ambiguous syntax");


(* read sorts *)

fun standard_parse_sort ctxt syn map_sort str =
  (case read ctxt (K false) syn TypeExt.sortT str of
    [t] => TypeExt.sort_of_term map_sort t
  | _ => error "read_sort: ambiguous syntax");



(** prepare translation rules **)

datatype 'a trrule =
  ParseRule of 'a * 'a |
  PrintRule of 'a * 'a |
  ParsePrintRule of 'a * 'a;

fun map_trrule f (ParseRule (x, y)) = ParseRule (f x, f y)
  | map_trrule f (PrintRule (x, y)) = PrintRule (f x, f y)
  | map_trrule f (ParsePrintRule (x, y)) = ParsePrintRule (f x, f y);

fun parse_rule (ParseRule pats) = SOME pats
  | parse_rule (PrintRule _) = NONE
  | parse_rule (ParsePrintRule pats) = SOME pats;

fun print_rule (ParseRule _) = NONE
  | print_rule (PrintRule pats) = SOME (swap pats)
  | print_rule (ParsePrintRule pats) = SOME (swap pats);


local

fun check_rule (rule as (lhs, rhs)) =
  (case Ast.rule_error rule of
    SOME msg =>
      error ("Error in syntax translation rule: " ^ msg ^ "\n" ^
        Ast.str_of_ast lhs ^ "  ->  " ^ Ast.str_of_ast rhs)
  | NONE => rule);


fun read_pattern ctxt is_logtype syn (root, str) =
  let
    val Syntax ({consts, ...}, _) = syn;

    fun constify (ast as Ast.Constant _) = ast
      | constify (ast as Ast.Variable x) =
          if member (op =) consts x orelse NameSpace.is_qualified x then Ast.Constant x
          else ast
      | constify (Ast.Appl asts) = Ast.Appl (map constify asts);
  in
    (case read_asts ctxt is_logtype syn true root str of
      [ast] => constify ast
    | _ => error ("Syntactically ambiguous input: " ^ quote str))
  end handle ERROR msg =>
    cat_error msg ("The error(s) above occurred in translation pattern " ^
      quote str);

fun prep_rules rd_pat raw_rules =
  let val rules = map (map_trrule rd_pat) raw_rules in
    (map check_rule (map_filter parse_rule rules),
      map check_rule (map_filter print_rule rules))
  end

in

val cert_rules = prep_rules I;

fun read_rules ctxt is_logtype syn =
  prep_rules (read_pattern ctxt is_logtype syn);

end;



(** pretty terms, typs, sorts **)

fun pretty_t t_to_ast prt_t markup ctxt (syn as Syntax (tabs, _)) curried t =
  let
    val {print_trtab, print_ruletab, print_ast_trtab, tokentrtab, prtabs, ...} = tabs;
    val ast = t_to_ast ctxt (lookup_tr' print_trtab) t;
  in
    Pretty.markup markup (prt_t ctxt curried prtabs (lookup_tr' print_ast_trtab)
      (lookup_tokentr tokentrtab (print_mode_value ()))
      (Ast.normalize_ast (Symtab.lookup_list print_ruletab) ast))
  end;

fun pretty_term extern =
  pretty_t Printer.term_to_ast (Printer.pretty_term_ast extern) Markup.term;
fun pretty_typ ctxt syn =
  pretty_t Printer.typ_to_ast Printer.pretty_typ_ast Markup.typ ctxt syn false;
fun pretty_sort ctxt syn =
  pretty_t Printer.sort_to_ast Printer.pretty_typ_ast Markup.sort ctxt syn false;



(** modify syntax **)

fun ext_syntax' f is_logtype prmode decls = extend_syntax prmode (f is_logtype decls);
fun ext_syntax f = ext_syntax' (K f) (K false) default_mode;

val extend_type_gram       = ext_syntax Mixfix.syn_ext_types;
val extend_const_gram      = ext_syntax' Mixfix.syn_ext_consts;
val extend_consts          = ext_syntax SynExt.syn_ext_const_names;
val extend_trfuns          = ext_syntax SynExt.syn_ext_trfuns;
val extend_advanced_trfuns = ext_syntax SynExt.syn_ext_advanced_trfuns;
val extend_tokentrfuns     = ext_syntax SynExt.syn_ext_tokentrfuns;

fun remove_const_gram is_logtype prmode decls =
  remove_syntax prmode (Mixfix.syn_ext_consts is_logtype decls);

fun extend_trrules ctxt is_logtype syn =
  ext_syntax SynExt.syn_ext_rules o read_rules ctxt is_logtype syn;

fun remove_trrules ctxt is_logtype syn =
  remove_syntax default_mode o SynExt.syn_ext_rules o read_rules ctxt is_logtype syn;

val extend_trrules_i = ext_syntax SynExt.syn_ext_rules o cert_rules;
val remove_trrules_i = remove_syntax default_mode o SynExt.syn_ext_rules o cert_rules;



(** generic parsing and type-checking **)

(* parsing *)

type parsers =
 {sort: Proof.context -> string -> sort,
  typ: Proof.context -> string -> typ,
  term: Proof.context -> string -> term,
  prop: Proof.context -> string -> term};

local
  val parsers = ref (NONE: parsers option);
in
  fun install_parsers ps = CRITICAL (fn () =>
    if is_some (! parsers) then error "Inner syntax parsers already installed"
    else parsers := SOME ps);

  fun parse which ctxt s =
    (case ! parsers of
      NONE => error "Inner syntax parsers not yet installed"
    | SOME ps => which ps ctxt s);
end;

val parse_sort = parse #sort;
val parse_typ = parse #typ;
val parse_term = parse #term;
val parse_prop = parse #prop;

val global_parse_sort = parse_sort o ProofContext.init;
val global_parse_typ = parse_typ o ProofContext.init;
val global_parse_term = parse_term o ProofContext.init;
val global_parse_prop = parse_prop o ProofContext.init;


(* checking types/terms *)

local

structure Checks = GenericDataFun
(
  type T =
    ((typ list -> Proof.context -> typ list * Proof.context) * stamp) list *
    ((term list -> Proof.context -> term list * Proof.context) * stamp) list;
  val empty = ([], []);
  val extend = I;
  fun merge _ ((typ_checks1, term_checks1), (typ_checks2, term_checks2)) : T =
    (Library.merge (eq_snd op =) (typ_checks1, typ_checks2),
     Library.merge (eq_snd op =) (term_checks1, term_checks2));
);

fun gen_check which eq ctxt0 xs0 =
  let
    val funs = map fst (rev (which (Checks.get (Context.Proof ctxt0))));

    fun check [] xs ctxt = (xs, ctxt)
      | check (f :: fs) xs ctxt = f xs ctxt |-> check fs;

    fun check_fixpoint xs ctxt =
      let val (xs', ctxt') = check funs xs ctxt in
        if eq_list eq (xs, xs') then (xs, ctxt)
        else check_fixpoint xs' ctxt'
      end;
  in #1 (case funs of [f] => f xs0 ctxt0 | _ => check_fixpoint xs0 ctxt0) end;

in

val check_typs = gen_check fst (op =);
val check_terms = gen_check snd (op aconv);
fun check_props ctxt = map (TypeInfer.constrain propT) #> check_terms ctxt;

val check_typ = singleton o check_typs;
val check_term = singleton o check_terms;
val check_prop = singleton o check_props;

fun check_sort ctxt S =
  (case singleton (check_typs ctxt) (TFree ("", S)) of   (* FIXME TypeInfer.invent_type (!?) *)
    TFree ("", S') => S'
  | T => raise TYPE ("check_sort", [T], []));

fun add_typ_check f = Checks.map (apfst (cons (f, stamp ())));
fun add_term_check f = Checks.map (apsnd (cons (f, stamp ())));

end;


(* combined operations *)

fun read_sort ctxt = parse_sort ctxt #> check_sort ctxt;
fun read_typ ctxt = parse_typ ctxt #> singleton (check_typs ctxt);

fun read_terms ctxt = map (parse_term ctxt) #> check_terms ctxt;
fun read_props ctxt = map (parse_prop ctxt) #> check_props ctxt;

val read_term = singleton o read_terms;
val read_prop = singleton o read_props;

val global_read_sort = read_sort o ProofContext.init;
val global_read_typ = read_typ o ProofContext.init;
val global_read_term = read_term o ProofContext.init;
val global_read_prop = read_prop o ProofContext.init;


(*export parts of internal Syntax structures*)
open Lexicon SynExt Ast Parser TypeExt SynTrans Mixfix Printer;

end;

structure BasicSyntax: BASIC_SYNTAX = Syntax;
open BasicSyntax;

structure Hidden = struct end;
structure Ast = Hidden;
structure SynExt = Hidden;
structure Parser = Hidden;
structure TypeExt = Hidden;
structure SynTrans = Hidden;
structure Mixfix = Hidden;
structure Printer = Hidden;