src/Pure/Thy/thy_parse.ML
author wenzelm
Mon May 25 21:27:22 1998 +0200 (1998-05-25)
changeset 4965 06914837e073
parent 4952 addfa29d0481
child 5058 52a78ff5599e
permissions -rw-r--r--
tuned local, global;
tuned begin and end theory;
     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 (* empty *)
   192 
   193 fun empty_decl toks = (empty >> K "") toks;
   194 
   195 
   196 (* classes *)
   197 
   198 val subclass = name -- optional ("<" $$-- !! name_list1) "[]";
   199 
   200 val class_decls = repeat1 (subclass >> mk_pair) >> mk_big_list;
   201 
   202 
   203 (* arities *)
   204 
   205 val sort =
   206   name >> brackets ||
   207   "{" $$-- name_list --$$ "}";
   208 
   209 val sort_list1 = list1 sort >> mk_list;
   210 
   211 
   212 val arity = optional ("(" $$-- !! (sort_list1 --$$")")) "[]" -- sort;
   213 
   214 val arity_decls = repeat1 (names1 --$$ "::" -- !! arity)
   215   >> (mk_big_list o map mk_triple2 o split_decls);
   216 
   217 
   218 (* mixfix annotations *)
   219 
   220 val infxl =
   221   "infixl" $$-- !! (nat >> cat "Infixl" || string -- nat >> (cat "InfixlName" o mk_pair));
   222 val infxr =
   223   "infixr" $$-- !! (nat >> cat "Infixr" || string -- nat >> (cat "InfixrName" o mk_pair));
   224 
   225 val binder = "binder" $$--
   226   !! (string -- (("[" $$-- nat --$$ "]") -- nat || nat >> (fn n => (n, n))))
   227     >> (cat "Binder" o mk_triple2);
   228 
   229 val opt_pris = optional ("[" $$-- !! (list nat --$$ "]")) [] >> mk_list;
   230 
   231 val mixfix = string -- !! (opt_pris -- optional nat "max_pri")
   232   >> (cat "Mixfix" o mk_triple2);
   233 
   234 fun opt_syn fx = optional ("(" $$-- fx --$$ ")") "NoSyn";
   235 
   236 val opt_infix = opt_syn (infxl || infxr);
   237 val opt_mixfix = opt_syn (mixfix || infxl || infxr || binder);
   238 
   239 
   240 (* types *)
   241 
   242 (* FIXME clean!! *)
   243 
   244 (*Parse an identifier, but only if it is not followed by "::", "=" or ",";
   245   the exclusion of a postfix comma can be controlled to allow expressions
   246   like "(id, id)" but disallow ones like "'a => id id,id :: ..."*)
   247 fun ident_no_colon _ [] = eof_err()
   248   | ident_no_colon allow_comma ((Ident, s, n) :: (rest as (Keyword, s2, n2) ::
   249                                 toks)) =
   250       if s2 = "::" orelse s2 = "=" orelse (not allow_comma andalso s2 = ",")
   251       then syn_err (name_of_kind Ident) (quote s2) n2
   252       else (s, rest)
   253   | ident_no_colon _ ((Ident, s, n) :: toks) = (s, toks)
   254   | ident_no_colon _ ((k, s, n) :: _) =
   255       syn_err (name_of_kind Ident) (quote s) n;
   256 
   257 (*type used in types, consts and syntax sections*)
   258 fun const_type allow_comma toks =
   259   let
   260     val simple_type =
   261       (ident || kind TypeVar ^^ optional ($$ "::" ^^ ident) "") --
   262           repeat (ident_no_colon allow_comma)
   263           >> (fn (args, ts) => cat args (space_implode " " ts)) ||
   264         ("(" $$-- (list1 (const_type true)) --$$ ")" >> (parens o commas)) --
   265           repeat1 (ident_no_colon allow_comma)
   266           >> (fn (args, ts) => cat args (space_implode " " ts));
   267 
   268       val appl_param =
   269         simple_type || "(" $$-- const_type true --$$ ")" >> parens || 
   270         "[" $$-- (list1 (const_type true)) --$$ "]" --$$ "=>" --
   271           const_type allow_comma >>
   272           (fn (src, dest) => mk_list src ^ " => " ^ dest);
   273   in ("[" $$-- (list1 (const_type true)) --$$ "]" --$$ "=>" --
   274         const_type allow_comma >>
   275         (fn (src, dest) => mk_list src ^ " => " ^ dest) ||
   276       repeat1 (appl_param --$$ "=>") -- const_type allow_comma >>
   277         (fn (src, dest) => space_implode " => " (src@[dest])) ||
   278       simple_type ||
   279       "(" $$-- const_type true --$$ ")" >> parens) toks
   280   end;
   281 
   282 val typ = string || (const_type false >> quote);
   283 
   284 
   285 fun mk_old_type_decl ((ts, n), syn) =
   286   map (fn t => (mk_triple (t, n, syn), false)) ts;
   287 
   288 fun mk_type_decl (((xs, t), None), syn) =
   289       [(mk_triple (t, string_of_int (length xs), syn), false)]
   290   | mk_type_decl (((xs, t), Some rhs), syn) =
   291       [(parens (commas [t, mk_list xs, rhs, syn]), true)];
   292 
   293 fun mk_type_decls tys =
   294   "|> Theory.add_types\n" ^ mk_big_list (keyfilter tys false) ^ "\n\n\
   295   \|> Theory.add_tyabbrs\n" ^ mk_big_list (keyfilter tys true);
   296 
   297 
   298 val old_type_decl = names1 -- nat -- opt_infix >> mk_old_type_decl;
   299 
   300 val type_args =
   301   type_var >> (fn x => [x]) ||
   302   "(" $$-- !! (list1 type_var --$$ ")") ||
   303   empty >> K [];
   304 
   305 val type_decl = type_args -- name --
   306   optional ("=" $$-- typ >> Some) None -- opt_infix >> mk_type_decl;
   307 
   308 val type_decls =
   309   repeat1 (old_type_decl || type_decl) >> (mk_type_decls o flat);
   310 
   311 
   312 (* consts *)
   313 
   314 val const_decls =
   315   repeat1 (names1 --$$ "::" -- !! (typ -- opt_mixfix))
   316   >> (mk_big_list o map mk_triple2 o split_decls);
   317 
   318 val opt_mode =
   319   optional
   320     ("(" $$-- !! (name -- optional ($$ "output" >> K "false") "true" --$$ ")"))
   321     ("\"\"", "true")
   322   >> mk_pair;
   323 
   324 val syntax_decls = opt_mode -- const_decls >> (fn (mode, txt) => mode ^ "\n" ^ txt);
   325 
   326 
   327 (* translations *)
   328 
   329 val trans_pat =
   330   optional ("(" $$-- !! (name --$$ ")")) "\"logic\"" -- string >> mk_pair;
   331 
   332 val trans_arrow =
   333   $$ "=>" >> K "Syntax.ParseRule " ||
   334   $$ "<=" >> K "Syntax.PrintRule " ||
   335   $$ "==" >> K "Syntax.ParsePrintRule ";
   336 
   337 val trans_line =
   338   trans_pat -- !! (trans_arrow -- trans_pat)
   339     >> (fn (left, (arr, right)) => arr ^ mk_pair (left, right));
   340 
   341 val trans_decls = repeat1 trans_line >> mk_big_list;
   342 
   343 
   344 (* ML translations *)
   345 
   346 val local_defs =
   347   " val parse_ast_translation = [];\n\
   348   \ val parse_translation = [];\n\
   349   \ val print_translation = [];\n\
   350   \ val typed_print_translation = [];\n\
   351   \ val print_ast_translation = [];\n\
   352   \ val token_translation = [];";
   353 
   354 val trfun_args =
   355   "(parse_ast_translation, parse_translation, \
   356   \print_translation, print_ast_translation)";
   357 
   358 
   359 (* axioms *)
   360 
   361 val mk_axms = mk_big_list o map (mk_pair o apfst quote);
   362 
   363 fun mk_axiom_decls axms = (mk_axms axms, map fst axms);
   364 
   365 val axiom_decls = repeat1 (ident -- !! string) >> mk_axiom_decls;
   366 
   367 
   368 (* oracle *)
   369 
   370 val oracle_decl = (name --$$ "=" -- long_id) >> mk_pair;
   371 
   372 
   373 (* combined consts and axioms *)
   374 
   375 fun mk_constaxiom_decls x =
   376   let
   377     val (axms_defs, axms_names) =
   378       mk_axiom_decls (map (fn ((id, _), def) => (id ^ "_def", def)) x);
   379   in ((mk_big_list o map mk_triple2 o map (apfst quote o fst)) x ^
   380        "\n\n|> (PureThy.add_defs o map Attribute.none)\n" ^ axms_defs, axms_names)
   381   end;
   382 
   383 val constaxiom_decls =
   384   repeat1 (ident --$$ "::" -- !! (typ -- opt_mixfix) -- !! string)
   385   >> mk_constaxiom_decls;
   386 
   387 
   388 (* axclass *)
   389 
   390 fun mk_axclass_decl ((c, cs), axms) =
   391   (mk_pair (c, cs) ^ "\n" ^ mk_axms axms,
   392     (strip_quotes c ^ "I") :: map fst axms);
   393 
   394 val axclass_decl = subclass -- repeat (ident -- !! string) >> mk_axclass_decl;
   395 
   396 
   397 (* instance *)
   398 
   399 fun mk_witness (axths, opt_tac) =
   400   mk_list (keyfilter axths false) ^ "\n" ^
   401   mk_list (keyfilter axths true) ^ "\n" ^
   402   opt_tac;
   403 
   404 val axm_or_thm =
   405   string >> rpair false ||
   406   long_id >> rpair true;
   407 
   408 
   409 val opt_witness =
   410   optional ("(" $$-- list1 axm_or_thm --$$ ")") [] --
   411   optional (verbatim >> (parens o cat "Some" o parens)) "None"
   412   >> mk_witness;
   413 
   414 val instance_decl =
   415   (name --$$ "<" -- name >> (pair "|> AxClass.add_inst_subclass" o mk_pair) ||
   416     name --$$ "::" -- arity >> (pair "|> AxClass.add_inst_arity" o mk_triple2))
   417   -- opt_witness
   418   >> (fn ((x, y), z) => (cat_lines [x, y, z]));
   419 
   420 
   421 
   422 (** theory syntax **)
   423 
   424 type syntax =
   425   Scan.lexicon * (token list -> (string * string) * token list) Symtab.table;
   426 
   427 fun make_syntax keywords sects =
   428   let
   429     val dups = duplicates (map fst sects);
   430     val sects' = gen_distinct eq_fst sects;
   431     val keys = map Symbol.explode (map fst sects' @ keywords);
   432   in
   433     if null dups then ()
   434     else warning ("Duplicate declaration of theory file sections:\n" ^ commas_quote dups);
   435     (Scan.make_lexicon keys, Symtab.make sects')
   436   end;
   437 
   438 
   439 (* header *)
   440 
   441 fun mk_header (thy_name, bases) =
   442   (thy_name, "mk_base " ^ mk_list bases ^ " " ^ quote thy_name);
   443 
   444 val base =
   445   ident >> (cat "Thy" o quote) ||
   446   string >> cat "File";
   447 
   448 val header = ident --$$ "=" -- enum1 "+" base >> mk_header;
   449 
   450 
   451 (* extension *)
   452 
   453 fun mk_extension (txts, mltxt) =
   454   let
   455     val cat_sects = space_implode "\n\n" o filter_out (equal "");
   456     val (extxts, postxts) = split_list txts;
   457   in
   458     (cat_sects extxts, cat_sects postxts, mltxt)
   459   end;
   460 
   461 fun sect tab ((Keyword, s, n) :: toks) =
   462       (case Symtab.lookup (tab, s) of
   463         Some parse => !! parse toks
   464       | None => syn_err "section" s n)
   465   | sect _ ((_, s, n) :: _) = syn_err "section" s n
   466   | sect _ [] = eof_err ();
   467 
   468 fun extension sectab = "+" $$-- !!
   469   (repeat (sect sectab) --$$ "end" -- optional verbatim "")
   470     >> mk_extension;
   471 
   472 fun opt_extension sectab = optional (extension sectab) ("", "", "");
   473 
   474 
   475 (* theory definition *)
   476 
   477 fun mk_structure tname ((thy_name, old_thys), (extxt, postxt, mltxt)) =
   478   if thy_name <> tname then
   479     error ("Filename \"" ^ tname ^ ".thy\" and theory name "
   480       ^ quote thy_name ^ " are different")
   481   else
   482     "val thy = " ^ old_thys ^ ";\n\n\
   483     \structure " ^ thy_name ^ " =\n\
   484     \struct\n\
   485     \\n\
   486     \local\n"
   487     ^ local_defs ^ "\n\
   488     \in\n\
   489     \\n"
   490     ^ mltxt ^ "\n\
   491     \\n\
   492     \val thy = thy\n\
   493     \|> PureThy.put_name " ^ quote thy_name ^ "\n\
   494     \|> PureThy.local_path\n\
   495     \|> Theory.add_trfuns\n"
   496     ^ trfun_args ^ "\n\
   497     \|> Theory.add_trfunsT typed_print_translation\n\
   498     \|> Theory.add_tokentrfuns token_translation\n\
   499     \\n"
   500     ^ extxt ^ "\n\
   501     \\n\
   502     \|> PureThy.end_theory\n\
   503     \\n\
   504     \val _ = store_theory thy;\n\
   505     \val _ = context thy;\n\
   506     \\n\
   507     \\n"
   508     ^ postxt ^ "\n\
   509     \\n\
   510     \end;\n\
   511     \end;\n\
   512     \\n\
   513     \open " ^ thy_name ^ ";\n\
   514     \\n";
   515 
   516 fun theory_defn sectab tname =
   517   header -- opt_extension sectab -- eof >> (mk_structure tname o #1);
   518 
   519 fun parse_thy (lex, sectab) tname str =
   520   #1 (!! (theory_defn sectab tname) (tokenize lex str));
   521 
   522 
   523 (* standard sections *)
   524 
   525 fun mk_val ax = "val " ^ ax ^ " = get_axiom thy " ^ quote ax ^ ";";
   526 val mk_vals = cat_lines o map mk_val;
   527 
   528 fun mk_axm_sect "" (txt, axs) = (txt, mk_vals axs)
   529   | mk_axm_sect pretxt (txt, axs) = (pretxt ^ "\n" ^ txt, mk_vals axs);
   530 
   531 fun axm_section name pretxt parse =
   532   (name, parse >> mk_axm_sect pretxt);
   533 
   534 fun section name pretxt parse =
   535   axm_section name pretxt (parse >> rpair []);
   536 
   537 
   538 val pure_keywords =
   539  ["end", "ML", "mixfix", "infixr", "infixl", "binder", "output", "=",
   540   "+", ",", "<", "{", "}", "(", ")", "[", "]", "::", "==", "=>",
   541   "<="];
   542 
   543 val pure_sections =
   544  [section "classes" "|> Theory.add_classes" class_decls,
   545   section "default" "|> Theory.add_defsort" sort,
   546   section "types" "" type_decls,
   547   section "nonterminals" "|> Theory.add_nonterminals" (repeat1 name >> mk_list),
   548   section "arities" "|> Theory.add_arities" arity_decls,
   549   section "consts" "|> Theory.add_consts" const_decls,
   550   section "syntax" "|> Theory.add_modesyntax" syntax_decls,
   551   section "translations" "|> Theory.add_trrules" trans_decls,
   552   axm_section "rules" "|> (PureThy.add_axioms o map Attribute.none)" axiom_decls,
   553   axm_section "defs" "|> (PureThy.add_defs o map Attribute.none)" axiom_decls,
   554   section "oracle" "|> Theory.add_oracle" oracle_decl,
   555   axm_section "constdefs" "|> Theory.add_consts" constaxiom_decls,
   556   axm_section "axclass" "|> AxClass.add_axclass" axclass_decl,
   557   section "instance" "" instance_decl,
   558   section "path" "|> Theory.add_path" name,
   559   section "global" "|> PureThy.global_path" empty_decl,
   560   section "local" "|> PureThy.local_path" empty_decl,
   561   section "setup" "|> Theory.apply" long_id,
   562   section "MLtext" "" verbatim];
   563 
   564 
   565 end;