src/Pure/Thy/thy_parse.ML
author wenzelm
Sat Apr 04 11:41:24 1998 +0200 (1998-04-04)
changeset 4787 90fc96d16df4
parent 4707 abe6f28a38c1
child 4852 58b5006d36cc
permissions -rw-r--r--
replaced thy_data by thy_setup;
     1 (*  Title:      Pure/Thy/thy_parse.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 The parser for theory files.
     6 *)
     7 
     8 infix 5 -- --$$ $$-- ^^;
     9 infix 3 >>;
    10 infix 0 ||;
    11 
    12 signature THY_PARSE =
    13 sig
    14   type token
    15   val !! : ('a -> 'b * 'c) -> 'a -> 'b * 'c
    16   val >> : ('a -> 'b * 'c) * ('b -> 'd) -> 'a -> 'd * 'c
    17   val || : ('a -> 'b) * ('a -> 'b) -> 'a -> 'b
    18   val -- : ('a -> 'b * 'c) * ('c -> 'd * 'e) -> 'a -> ('b * 'd) * 'e
    19   val ^^ : ('a -> string * 'b) * ('b -> string * 'c) -> 'a -> string * 'c
    20   val $$ : string -> token list -> string * token list
    21   val $$-- : string * (token list -> 'b * 'c) -> token list -> 'b * 'c
    22   val --$$ : ('a -> 'b * token list) * string -> 'a -> 'b * token list
    23   val ident: token list -> string * token list
    24   val long_ident: token list -> string * token list
    25   val long_id: token list -> string * token list
    26   val type_var: token list -> string * token list
    27   val type_args: token list -> string list * token list
    28   val nat: token list -> string * token list
    29   val string: token list -> string * token list
    30   val verbatim: token list -> string * token list
    31   val empty: 'a -> 'b list * 'a
    32   val optional: ('a -> 'b * 'a) -> 'b -> 'a -> 'b * 'a
    33   val repeat: ('a -> 'b * 'a) -> 'a -> 'b list * 'a
    34   val repeat1: ('a -> 'b * 'a) -> 'a -> 'b list * 'a
    35   val enum: string -> (token list -> 'a * token list)
    36     -> token list -> 'a list * token list
    37   val enum1: string -> (token list -> 'a * token list)
    38     -> token list -> 'a list * token list
    39   val list: (token list -> 'a * token list)
    40     -> token list -> 'a list * token list
    41   val list1: (token list -> 'a * token list)
    42     -> token list -> 'a list * token list
    43   val name: token list -> string * token list
    44   val sort: token list -> string * token list
    45   val typ: token list -> string * token list
    46   val opt_infix: token list -> string * token list
    47   val opt_mixfix: token list -> string * token list
    48   val opt_witness: token list -> string * token list
    49   val const_decls: token list -> string * token list
    50   type syntax
    51   val make_syntax: string list ->
    52     (string * (token list -> (string * string) * token list)) list -> syntax
    53   val parse_thy: syntax -> string -> string -> string
    54   val section: string -> string -> (token list -> string * token list)
    55     -> (string * (token list -> (string * string) * token list))
    56   val axm_section: string -> string
    57     -> (token list -> (string * string list) * token list)
    58     -> (string * (token list -> (string * string) * token list))
    59   val pure_keywords: string list
    60   val pure_sections:
    61     (string * (token list -> (string * string) * token list)) list
    62   (*items for building strings*)
    63   val cat: string -> string -> string
    64   val parens: string -> string
    65   val brackets: string -> string
    66   val mk_list: string list -> string
    67   val mk_big_list: string list -> string
    68   val mk_pair: string * string -> string
    69   val mk_triple: string * string * string -> string
    70   val strip_quotes: string -> string
    71 end;
    72 
    73 
    74 structure ThyParse : THY_PARSE=
    75 struct
    76 
    77 open ThyScan;
    78 
    79 
    80 (** parser toolbox **)
    81 
    82 type token = token_kind * string * int;
    83 
    84 
    85 (* errors *)
    86 
    87 exception SYNTAX_ERROR of string * string * int;
    88 
    89 fun syn_err s1 s2 n = raise SYNTAX_ERROR (s1, s2, n);
    90 
    91 fun eof_err () = error "Unexpected end-of-file";
    92 
    93 (*Similar to Prolog's cut: reports any syntax error instead of backtracking
    94   through a superior || *)
    95 fun !! parse toks = parse toks
    96   handle SYNTAX_ERROR (s1, s2, n) => error ("Syntax error on line " ^
    97     string_of_int n ^ ": " ^ s1 ^ " expected and " ^ s2 ^ " was found");
    98 
    99 
   100 (* parser combinators *)
   101 
   102 fun (parse >> f) toks = apfst f (parse toks);
   103 
   104 fun (parse1 || parse2) toks =
   105   parse1 toks handle SYNTAX_ERROR _ => parse2 toks;
   106 
   107 fun (parse1 -- parse2) toks =
   108   let
   109     val (x, toks') = parse1 toks;
   110     val (y, toks'') = parse2 toks';
   111   in
   112     ((x, y), toks'')
   113   end;
   114 
   115 fun (parse1 ^^ parse2) = parse1 -- parse2 >> op ^;
   116 
   117 
   118 (* generic parsers *)
   119 
   120 fun $$ a ((k, b, n) :: toks) =
   121       if k = Keyword andalso a = b then (a, toks)
   122       else syn_err (quote a) (quote b) n
   123   | $$ _ [] = eof_err ();
   124 
   125 fun (a $$-- parse) = $$ a -- parse >> #2;
   126 
   127 fun (parse --$$ a) = parse -- $$ a >> #1;
   128 
   129 
   130 fun kind k1 ((k2, s, n) :: toks) =
   131       if k1 = k2 then (s, toks)
   132       else syn_err (name_of_kind k1) (quote s) n
   133   | kind _ [] = eof_err ();
   134 
   135 val ident = kind Ident;
   136 val long_ident = kind LongIdent;
   137 val long_id = ident || long_ident;
   138 val type_var = kind TypeVar >> quote;
   139 val nat = kind Nat;
   140 val string = kind String;
   141 val verbatim = kind Verbatim;
   142 val eof = kind EOF;
   143 
   144 fun empty toks = ([], toks);
   145 
   146 fun optional parse def = parse || empty >> K def;
   147 
   148 fun repeat parse toks = (parse -- repeat parse >> op :: || empty) toks;
   149 fun repeat1 parse = parse -- repeat parse >> op ::;
   150 
   151 fun enum1 sep parse = parse -- repeat (sep $$-- parse) >> op ::;
   152 fun enum sep parse = enum1 sep parse || empty;
   153 
   154 fun list1 parse = enum1 "," parse;
   155 fun list parse = enum "," parse;
   156 
   157 
   158 
   159 (** theory parsers **)
   160 
   161 (* misc utilities *)
   162 
   163 fun cat s1 s2 = s1 ^ " " ^ s2;
   164 
   165 val parens = enclose "(" ")";
   166 val brackets = enclose "[" "]";
   167 
   168 val mk_list = brackets o commas;
   169 val mk_big_list = brackets o space_implode ",\n ";
   170 
   171 fun mk_pair (x, y) = parens (commas [x, y]);
   172 fun mk_triple (x, y, z) = parens (commas [x, y, z]);
   173 fun mk_triple1 ((x, y), z) = mk_triple (x, y, z);
   174 fun mk_triple2 (x, (y, z)) = mk_triple (x, y, z);
   175 
   176 fun split_decls l = flat (map (fn (xs, y) => map (rpair y) xs) l);
   177 
   178 fun strip_quotes str =
   179   implode (tl (take (size str - 1, explode str)));
   180 
   181 
   182 (* names *)
   183 
   184 val name = ident >> quote || string;
   185 val names = list name;
   186 val names1 = list1 name;
   187 val name_list = names >> mk_list;
   188 val name_list1 = names1 >> mk_list;
   189 
   190 
   191 (* classes *)
   192 
   193 val subclass = name -- optional ("<" $$-- !! name_list1) "[]";
   194 
   195 val class_decls = repeat1 (subclass >> mk_pair) >> mk_big_list;
   196 
   197 
   198 (* arities *)
   199 
   200 val sort =
   201   name >> brackets ||
   202   "{" $$-- name_list --$$ "}";
   203 
   204 val sort_list1 = list1 sort >> mk_list;
   205 
   206 
   207 val arity = optional ("(" $$-- !! (sort_list1 --$$")")) "[]" -- sort;
   208 
   209 val arity_decls = repeat1 (names1 --$$ "::" -- !! arity)
   210   >> (mk_big_list o map mk_triple2 o split_decls);
   211 
   212 
   213 (* mixfix annotations *)
   214 
   215 val infxl =
   216   "infixl" $$-- !! (nat >> cat "Infixl" || string -- nat >> (cat "InfixlName" o mk_pair));
   217 val infxr =
   218   "infixr" $$-- !! (nat >> cat "Infixr" || string -- nat >> (cat "InfixrName" o mk_pair));
   219 
   220 val binder = "binder" $$--
   221   !! (string -- (("[" $$-- nat --$$ "]") -- nat || nat >> (fn n => (n, n))))
   222     >> (cat "Binder" o mk_triple2);
   223 
   224 val opt_pris = optional ("[" $$-- !! (list nat --$$ "]")) [] >> mk_list;
   225 
   226 val mixfix = string -- !! (opt_pris -- optional nat "max_pri")
   227   >> (cat "Mixfix" o mk_triple2);
   228 
   229 fun opt_syn fx = optional ("(" $$-- fx --$$ ")") "NoSyn";
   230 
   231 val opt_infix = opt_syn (infxl || infxr);
   232 val opt_mixfix = opt_syn (mixfix || infxl || infxr || binder);
   233 
   234 
   235 (* types *)
   236 
   237 (* FIXME clean!! *)
   238 
   239 (*Parse an identifier, but only if it is not followed by "::", "=" or ",";
   240   the exclusion of a postfix comma can be controlled to allow expressions
   241   like "(id, id)" but disallow ones like "'a => id id,id :: ..."*)
   242 fun ident_no_colon _ [] = eof_err()
   243   | ident_no_colon allow_comma ((Ident, s, n) :: (rest as (Keyword, s2, n2) ::
   244                                 toks)) =
   245       if s2 = "::" orelse s2 = "=" orelse (not allow_comma andalso s2 = ",")
   246       then syn_err (name_of_kind Ident) (quote s2) n2
   247       else (s, rest)
   248   | ident_no_colon _ ((Ident, s, n) :: toks) = (s, toks)
   249   | ident_no_colon _ ((k, s, n) :: _) =
   250       syn_err (name_of_kind Ident) (quote s) n;
   251 
   252 (*type used in types, consts and syntax sections*)
   253 fun const_type allow_comma toks =
   254   let
   255     val simple_type =
   256       (ident || kind TypeVar ^^ optional ($$ "::" ^^ ident) "") --
   257           repeat (ident_no_colon allow_comma)
   258           >> (fn (args, ts) => cat args (space_implode " " ts)) ||
   259         ("(" $$-- (list1 (const_type true)) --$$ ")" >> (parens o commas)) --
   260           repeat1 (ident_no_colon allow_comma)
   261           >> (fn (args, ts) => cat args (space_implode " " ts));
   262 
   263       val appl_param =
   264         simple_type || "(" $$-- const_type true --$$ ")" >> parens || 
   265         "[" $$-- (list1 (const_type true)) --$$ "]" --$$ "=>" --
   266           const_type allow_comma >>
   267           (fn (src, dest) => mk_list src ^ " => " ^ dest);
   268   in ("[" $$-- (list1 (const_type true)) --$$ "]" --$$ "=>" --
   269         const_type allow_comma >>
   270         (fn (src, dest) => mk_list src ^ " => " ^ dest) ||
   271       repeat1 (appl_param --$$ "=>") -- const_type allow_comma >>
   272         (fn (src, dest) => space_implode " => " (src@[dest])) ||
   273       simple_type ||
   274       "(" $$-- const_type true --$$ ")" >> parens) toks
   275   end;
   276 
   277 val typ = string || (const_type false >> quote);
   278 
   279 
   280 fun mk_old_type_decl ((ts, n), syn) =
   281   map (fn t => (mk_triple (t, n, syn), false)) ts;
   282 
   283 fun mk_type_decl (((xs, t), None), syn) =
   284       [(mk_triple (t, string_of_int (length xs), syn), false)]
   285   | mk_type_decl (((xs, t), Some rhs), syn) =
   286       [(parens (commas [t, mk_list xs, rhs, syn]), true)];
   287 
   288 fun mk_type_decls tys =
   289   "|> Theory.add_types\n" ^ mk_big_list (keyfilter tys false) ^ "\n\n\
   290   \|> Theory.add_tyabbrs\n" ^ mk_big_list (keyfilter tys true);
   291 
   292 
   293 val old_type_decl = names1 -- nat -- opt_infix >> mk_old_type_decl;
   294 
   295 val type_args =
   296   type_var >> (fn x => [x]) ||
   297   "(" $$-- !! (list1 type_var --$$ ")") ||
   298   empty >> K [];
   299 
   300 val type_decl = type_args -- name --
   301   optional ("=" $$-- typ >> Some) None -- opt_infix >> mk_type_decl;
   302 
   303 val type_decls =
   304   repeat1 (old_type_decl || type_decl) >> (mk_type_decls o flat);
   305 
   306 
   307 (* consts *)
   308 
   309 val const_decls =
   310   repeat1 (names1 --$$ "::" -- !! (typ -- opt_mixfix))
   311   >> (mk_big_list o map mk_triple2 o split_decls);
   312 
   313 val opt_mode =
   314   optional
   315     ("(" $$-- !! (name -- optional ($$ "output" >> K "false") "true" --$$ ")"))
   316     ("\"\"", "true")
   317   >> mk_pair;
   318 
   319 val syntax_decls = opt_mode -- const_decls >> (fn (mode, txt) => mode ^ "\n" ^ txt);
   320 
   321 
   322 (* translations *)
   323 
   324 val trans_pat =
   325   optional ("(" $$-- !! (name --$$ ")")) "\"logic\"" -- string >> mk_pair;
   326 
   327 val trans_arrow =
   328   $$ "=>" >> K "Syntax.ParseRule " ||
   329   $$ "<=" >> K "Syntax.PrintRule " ||
   330   $$ "==" >> K "Syntax.ParsePrintRule ";
   331 
   332 val trans_line =
   333   trans_pat -- !! (trans_arrow -- trans_pat)
   334     >> (fn (left, (arr, right)) => arr ^ mk_pair (left, right));
   335 
   336 val trans_decls = repeat1 trans_line >> mk_big_list;
   337 
   338 
   339 (* ML translations *)
   340 
   341 val local_defs =
   342   " val parse_ast_translation = [];\n\
   343   \ val parse_translation = [];\n\
   344   \ val print_translation = [];\n\
   345   \ val typed_print_translation = [];\n\
   346   \ val print_ast_translation = [];\n\
   347   \ val token_translation = [];\n\
   348   \ val thy_setup = []";
   349 
   350 val trfun_args =
   351   "(parse_ast_translation, parse_translation, \
   352   \print_translation, print_ast_translation)";
   353 
   354 
   355 (* axioms *)
   356 
   357 val mk_axms = mk_big_list o map (mk_pair o apfst quote);
   358 
   359 fun mk_axiom_decls axms = (mk_axms axms, map fst axms);
   360 
   361 val axiom_decls = repeat1 (ident -- !! string) >> mk_axiom_decls;
   362 
   363 
   364 (* oracle *)
   365 
   366 val oracle_decl = (name --$$ "=" -- long_id) >> mk_pair;
   367 
   368 
   369 (* combined consts and axioms *)
   370 
   371 fun mk_constaxiom_decls x =
   372   let
   373     val (axms_defs, axms_names) =
   374       mk_axiom_decls (map (fn ((id, _), def) => (id ^ "_def", def)) x);
   375   in ((mk_big_list o map mk_triple2 o map (apfst quote o fst)) x ^
   376        "\n\n|> PureThy.add_store_defs\n" ^ axms_defs, axms_names)
   377   end;
   378 
   379 val constaxiom_decls =
   380   repeat1 (ident --$$ "::" -- !! (typ -- opt_mixfix) -- !! string)
   381   >> mk_constaxiom_decls;
   382 
   383 
   384 (* axclass *)
   385 
   386 fun mk_axclass_decl ((c, cs), axms) =
   387   (mk_pair (c, cs) ^ "\n" ^ mk_axms axms,
   388     (strip_quotes c ^ "I") :: map fst axms);
   389 
   390 val axclass_decl = subclass -- repeat (ident -- !! string) >> mk_axclass_decl;
   391 
   392 
   393 (* instance *)
   394 
   395 fun mk_witness (axths, opt_tac) =
   396   mk_list (keyfilter axths false) ^ "\n" ^
   397   mk_list (keyfilter axths true) ^ "\n" ^
   398   opt_tac;
   399 
   400 val axm_or_thm =
   401   string >> rpair false ||
   402   long_id >> rpair true;
   403 
   404 
   405 val opt_witness =
   406   optional ("(" $$-- list1 axm_or_thm --$$ ")") [] --
   407   optional (verbatim >> (parens o cat "Some" o parens)) "None"
   408   >> mk_witness;
   409 
   410 val instance_decl =
   411   (name --$$ "<" -- name >> (pair "|> AxClass.add_inst_subclass" o mk_pair) ||
   412     name --$$ "::" -- arity >> (pair "|> AxClass.add_inst_arity" o mk_triple2))
   413   -- opt_witness
   414   >> (fn ((x, y), z) => (cat_lines [x, y, z]));
   415 
   416 
   417 (* local, global path *)
   418 
   419 fun empty_decl toks = (empty >> K "") toks;
   420 
   421 val global_path =
   422   "|> (fn thy => if ! global_names then thy else Theory.add_path \"/\" thy)";
   423 
   424 val local_path =
   425   global_path ^ "\n\
   426   \|> (fn thy => if ! global_names then thy\
   427   \ else Theory.add_path thy_name thy)";
   428 
   429 
   430 
   431 (** theory syntax **)
   432 
   433 type syntax =
   434   Scan.lexicon * (token list -> (string * string) * token list) Symtab.table;
   435 
   436 fun make_syntax keywords sects =
   437   let
   438     val dups = duplicates (map fst sects);
   439     val sects' = gen_distinct eq_fst sects;
   440     val keys = map Symbol.explode (map fst sects' @ keywords);
   441   in
   442     if null dups then ()
   443     else warning ("Duplicate declaration of theory file sections:\n" ^ commas_quote dups);
   444     (Scan.make_lexicon keys, Symtab.make sects')
   445   end;
   446 
   447 
   448 (* header *)
   449 
   450 fun mk_header (thy_name, bases) =
   451   (thy_name, "mk_base " ^ mk_list bases ^ " " ^ quote thy_name);
   452 
   453 val base =
   454   ident >> (cat "Thy" o quote) ||
   455   string >> cat "File";
   456 
   457 val header = ident --$$ "=" -- enum1 "+" base >> mk_header;
   458 
   459 
   460 (* extension *)
   461 
   462 fun mk_extension (txts, mltxt) =
   463   let
   464     val cat_sects = space_implode "\n\n" o filter_out (equal "");
   465     val (extxts, postxts) = split_list txts;
   466   in
   467     (cat_sects extxts, cat_sects postxts, mltxt)
   468   end;
   469 
   470 fun sect tab ((Keyword, s, n) :: toks) =
   471       (case Symtab.lookup (tab, s) of
   472         Some parse => !! parse toks
   473       | None => syn_err "section" s n)
   474   | sect _ ((_, s, n) :: _) = syn_err "section" s n
   475   | sect _ [] = eof_err ();
   476 
   477 fun extension sectab = "+" $$-- !!
   478   (repeat (sect sectab) --$$ "end" -- optional verbatim "")
   479     >> mk_extension;
   480 
   481 fun opt_extension sectab = optional (extension sectab) ("", "", "");
   482 
   483 
   484 (* theory definition *)
   485 
   486 fun mk_structure tname ((thy_name, old_thys), (extxt, postxt, mltxt)) =
   487   if thy_name <> tname then
   488     error ("Filename \"" ^ tname ^ ".thy\" and theory name "
   489       ^ quote thy_name ^ " are different")
   490   else
   491     "val thy = " ^ old_thys ^ ";\n\n\
   492     \structure " ^ thy_name ^ " =\n\
   493     \struct\n\
   494     \\n\
   495     \local\n\
   496     \ val thy_name = \"" ^ tname ^ "\";\n"
   497     ^ local_defs ^ "\n\
   498     \in\n\
   499     \\n"
   500     ^ mltxt ^ "\n\
   501     \\n\
   502     \val thy = thy\n\
   503     \\n"
   504     ^ local_path ^
   505     "\n\
   506     \|> Theory.setup thy_setup\n\
   507     \|> Theory.add_trfuns\n"
   508     ^ trfun_args ^ "\n\
   509     \|> Theory.add_trfunsT typed_print_translation\n\
   510     \|> Theory.add_tokentrfuns token_translation\n\
   511     \\n"
   512     ^ extxt ^ "\n\
   513     \\n\
   514     \|> Theory.add_name " ^ quote thy_name ^ ";\n\
   515     \\n\
   516     \val _ = store_theory (thy, " ^ quote thy_name ^ ");\n\
   517     \val _ = context thy;\n\
   518     \\n\
   519     \\n"
   520     ^ postxt ^ "\n\
   521     \\n\
   522     \end;\n\
   523     \end;\n\
   524     \\n\
   525     \open " ^ thy_name ^ ";\n\
   526     \\n";
   527 
   528 fun theory_defn sectab tname =
   529   header -- opt_extension sectab -- eof >> (mk_structure tname o #1);
   530 
   531 fun parse_thy (lex, sectab) tname str =
   532   #1 (!! (theory_defn sectab tname) (tokenize lex str));
   533 
   534 
   535 (* standard sections *)
   536 
   537 fun mk_val ax = "val " ^ ax ^ " = get_axiom thy " ^ quote ax ^ ";";
   538 val mk_vals = cat_lines o map mk_val;
   539 
   540 fun mk_axm_sect "" (txt, axs) = (txt, mk_vals axs)
   541   | mk_axm_sect pretxt (txt, axs) = (pretxt ^ "\n" ^ txt, mk_vals axs);
   542 
   543 fun axm_section name pretxt parse =
   544   (name, parse >> mk_axm_sect pretxt);
   545 
   546 fun section name pretxt parse =
   547   axm_section name pretxt (parse >> rpair []);
   548 
   549 
   550 val pure_keywords =
   551  ["end", "ML", "MLtext", "mixfix", "infixr", "infixl", "binder", "global",
   552   "local", "output", "=", "+", ",", "<", "{", "}", "(", ")", "[", "]",
   553   "::", "==", "=>", "<="];
   554 
   555 val pure_sections =
   556  [section "classes" "|> Theory.add_classes" class_decls,
   557   section "default" "|> Theory.add_defsort" sort,
   558   section "types" "" type_decls,
   559   section "arities" "|> Theory.add_arities" arity_decls,
   560   section "consts" "|> Theory.add_consts" const_decls,
   561   section "syntax" "|> Theory.add_modesyntax" syntax_decls,
   562   section "translations" "|> Theory.add_trrules" trans_decls,
   563   axm_section "rules" "|> PureThy.add_store_axioms" axiom_decls,
   564   axm_section "defs" "|> PureThy.add_store_defs" axiom_decls,
   565   section "oracle" "|> Theory.add_oracle" oracle_decl,
   566   axm_section "constdefs" "|> Theory.add_consts" constaxiom_decls,
   567   axm_section "axclass" "|> AxClass.add_axclass" axclass_decl,
   568   section "instance" "" instance_decl,
   569   section "path" "|> Theory.add_path" name,
   570   section "global" global_path empty_decl,
   571   section "local" local_path empty_decl,
   572   section "MLtext" "" verbatim];
   573 
   574 
   575 end;