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