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