src/Pure/Thy/thy_parse.ML
author wenzelm
Wed Oct 17 18:52:30 2001 +0200 (2001-10-17)
changeset 11819 9283b3c11234
parent 9328 1a46c94d1425
child 11830 84dc8a2479d4
permissions -rw-r--r--
tuned comments;
     1 (*  Title:      Pure/Thy/thy_parse.ML
     2     ID:         $Id$
     3     Author:     Markus Wenzel, TU Muenchen
     4     License:    GPL (GNU GENERAL PUBLIC LICENSE)
     5 
     6 The parser for *old-style* theory files.
     7 *)
     8 
     9 infix 5 -- --$$ $$-- ^^;
    10 infix 3 >>;
    11 infix 0 ||;
    12 
    13 signature THY_PARSE =
    14 sig
    15   type token
    16   val !! : ('a -> 'b * 'c) -> 'a -> 'b * 'c
    17   val >> : ('a -> 'b * 'c) * ('b -> 'd) -> 'a -> 'd * 'c
    18   val || : ('a -> 'b) * ('a -> 'b) -> 'a -> 'b
    19   val -- : ('a -> 'b * 'c) * ('c -> 'd * 'e) -> 'a -> ('b * 'd) * 'e
    20   val ^^ : ('a -> string * 'b) * ('b -> string * 'c) -> 'a -> string * 'c
    21   val $$ : string -> token list -> string * token list
    22   val $$-- : string * (token list -> 'b * 'c) -> token list -> 'b * 'c
    23   val --$$ : ('a -> 'b * token list) * string -> 'a -> 'b * token list
    24   val ident: token list -> string * token list
    25   val long_ident: token list -> string * token list
    26   val long_id: token list -> string * token list
    27   val type_var: token list -> string * token list
    28   val type_args: token list -> string list * token list
    29   val nat: token list -> string * token list
    30   val string: token list -> string * token list
    31   val verbatim: token list -> string * token list
    32   val empty: 'a -> 'b list * 'a
    33   val optional: ('a -> 'b * 'a) -> 'b -> 'a -> 'b * 'a
    34   val repeat: ('a -> 'b * 'a) -> 'a -> 'b list * 'a
    35   val repeat1: ('a -> 'b * 'a) -> 'a -> 'b list * 'a
    36   val enum: string -> (token list -> 'a * token list)
    37     -> token list -> 'a list * token list
    38   val enum1: string -> (token list -> 'a * token list)
    39     -> token list -> 'a list * token list
    40   val list: (token list -> 'a * token list)
    41     -> token list -> 'a list * token list
    42   val list1: (token list -> 'a * token list)
    43     -> token list -> 'a list * token list
    44   val name: token list -> string * token list
    45   val sort: token list -> string * token list
    46   val typ: token list -> string * token list
    47   val opt_infix: token list -> string * token list
    48   val opt_mixfix: token list -> string * token list
    49   val opt_witness: token list -> string * token list
    50   val const_decls: token list -> string * token list
    51   type syntax
    52   val get_lexicon: syntax -> Scan.lexicon;
    53   val make_syntax: string list ->
    54     (string * (token list -> (string * string) * token list)) list -> syntax
    55   val parse_thy: syntax -> string list -> 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 mk_triple1: (string * string) * string -> string
    73   val mk_triple2: string * (string * string) -> string
    74 end;
    75 
    76 
    77 structure ThyParse : THY_PARSE=
    78 struct
    79 
    80 open ThyScan;
    81 
    82 
    83 (** parser toolbox **)
    84 
    85 type token = token_kind * string * int;
    86 
    87 
    88 (* errors *)
    89 
    90 exception SYNTAX_ERROR of string * string * int;
    91 
    92 fun syn_err s1 s2 n = raise SYNTAX_ERROR (s1, s2, n);
    93 
    94 fun eof_err () = error "Unexpected end-of-file";
    95 
    96 (*Similar to Prolog's cut: reports any syntax error instead of backtracking
    97   through a superior || *)
    98 fun !! parse toks = parse toks
    99   handle SYNTAX_ERROR (s1, s2, n) => error ("Syntax error on line " ^
   100     string_of_int n ^ ": " ^ s1 ^ " expected and " ^ s2 ^ " was found");
   101 
   102 
   103 (* parser combinators *)
   104 
   105 fun (parse >> f) toks = apfst f (parse toks);
   106 
   107 fun (parse1 || parse2) toks =
   108   parse1 toks handle SYNTAX_ERROR _ => parse2 toks;
   109 
   110 fun (parse1 -- parse2) toks =
   111   let
   112     val (x, toks') = parse1 toks;
   113     val (y, toks'') = parse2 toks';
   114   in
   115     ((x, y), toks'')
   116   end;
   117 
   118 fun (parse1 ^^ parse2) = parse1 -- parse2 >> op ^;
   119 
   120 
   121 (* generic parsers *)
   122 
   123 fun $$ a ((k, b, n) :: toks) =
   124       if k = Keyword andalso a = b then (a, toks)
   125       else syn_err (quote a) (quote b) n
   126   | $$ _ [] = eof_err ();
   127 
   128 fun (a $$-- parse) = $$ a -- parse >> #2;
   129 
   130 fun (parse --$$ a) = parse -- $$ a >> #1;
   131 
   132 
   133 fun kind k1 ((k2, s, n) :: toks) =
   134       if k1 = k2 then (s, toks)
   135       else syn_err (name_of_kind k1) (quote s) n
   136   | kind _ [] = eof_err ();
   137 
   138 val ident = kind Ident;
   139 val long_ident = kind LongIdent;
   140 val long_id = ident || long_ident;
   141 val type_var = kind TypeVar >> quote;
   142 val nat = kind Nat;
   143 val string = kind String;
   144 val verbatim = kind Verbatim;
   145 val eof = kind EOF;
   146 
   147 fun empty toks = ([], toks);
   148 
   149 fun optional parse def = parse || empty >> K def;
   150 
   151 fun repeat parse toks = (parse -- repeat parse >> op :: || empty) toks;
   152 fun repeat1 parse = parse -- repeat parse >> op ::;
   153 
   154 fun enum1 sep parse = parse -- repeat (sep $$-- parse) >> op ::;
   155 fun enum sep parse = enum1 sep parse || empty;
   156 
   157 fun list1 parse = enum1 "," parse;
   158 fun list parse = enum "," parse;
   159 
   160 
   161 
   162 (** theory parsers **)
   163 
   164 (* misc utilities *)
   165 
   166 fun cat s1 s2 = s1 ^ " " ^ s2;
   167 
   168 val parens = enclose "(" ")";
   169 val brackets = enclose "[" "]";
   170 
   171 val mk_list = brackets o commas;
   172 val mk_big_list = brackets o space_implode ",\n ";
   173 
   174 fun mk_pair (x, y) = parens (commas [x, y]);
   175 fun mk_triple (x, y, z) = parens (commas [x, y, z]);
   176 fun mk_triple1 ((x, y), z) = mk_triple (x, y, z);
   177 fun mk_triple2 (x, (y, z)) = mk_triple (x, y, z);
   178 
   179 fun split_decls l = flat (map (fn (xs, y) => map (rpair y) xs) l);
   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 = name || "{" $$-- list ident --$$ "}" >> (quote o enclose "{" "}" o commas);
   206 val sort_list1 = list1 sort >> mk_list;
   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 "Syntax.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
   254     val simple_type =
   255       (ident || kind TypeVar ^^ optional ($$ "::" ^^ ident) "") --
   256           repeat (ident_no_colon allow_comma)
   257           >> (fn (args, ts) => cat args (space_implode " " ts)) ||
   258         ("(" $$-- (list1 (const_type true)) --$$ ")" >> (parens o commas)) --
   259           repeat1 (ident_no_colon allow_comma)
   260           >> (fn (args, ts) => cat args (space_implode " " ts));
   261 
   262       val appl_param =
   263         simple_type || "(" $$-- const_type true --$$ ")" >> parens || 
   264         "[" $$-- (list1 (const_type true)) --$$ "]" --$$ "=>" --
   265           const_type allow_comma >>
   266           (fn (src, dest) => mk_list src ^ " => " ^ dest);
   267   in ("[" $$-- (list1 (const_type true)) --$$ "]" --$$ "=>" --
   268         const_type allow_comma >>
   269         (fn (src, dest) => mk_list src ^ " => " ^ dest) ||
   270       repeat1 (appl_param --$$ "=>") -- const_type allow_comma >>
   271         (fn (src, dest) => space_implode " => " (src@[dest])) ||
   272       simple_type ||
   273       "(" $$-- const_type true --$$ ")" >> parens) toks
   274   end;
   275 
   276 val typ = string || (const_type false >> quote);
   277 
   278 
   279 fun mk_old_type_decl ((ts, n), syn) =
   280   map (fn t => (mk_triple (t, n, syn), false)) ts;
   281 
   282 fun mk_type_decl (((xs, t), None), syn) =
   283       [(mk_triple (t, string_of_int (length xs), syn), false)]
   284   | mk_type_decl (((xs, t), Some rhs), syn) =
   285       [(parens (commas [t, mk_list xs, rhs, syn]), true)];
   286 
   287 fun mk_type_decls tys =
   288   "|> Theory.add_types\n" ^ mk_big_list (keyfilter tys false) ^ "\n\n\
   289   \|> Theory.add_tyabbrs\n" ^ mk_big_list (keyfilter tys true);
   290 
   291 
   292 val old_type_decl = names1 -- nat -- opt_infix >> mk_old_type_decl;
   293 
   294 val type_args =
   295   type_var >> (fn x => [x]) ||
   296   "(" $$-- !! (list1 type_var --$$ ")") ||
   297   empty >> K [];
   298 
   299 val type_decl = type_args -- name --
   300   optional ("=" $$-- typ >> Some) None -- opt_infix >> mk_type_decl;
   301 
   302 val type_decls =
   303   repeat1 (old_type_decl || type_decl) >> (mk_type_decls o flat);
   304 
   305 
   306 (* consts *)
   307 
   308 val const_decls =
   309   repeat1 (names1 --$$ "::" -- !! (typ -- 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 local_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 val mk_axms' = mk_big_list o map (mk_pair o rpair "[]" o mk_pair o apfst quote);
   357 
   358 fun mk_axiom_decls axms = (mk_axms axms, map fst axms);
   359 
   360 val axiom_decls = repeat1 (ident -- !! string) >> mk_axiom_decls;
   361 
   362 
   363 (* oracle *)
   364 
   365 val oracle_decl = (name --$$ "=" -- long_id) >> mk_pair;
   366 
   367 
   368 (* combined consts and axioms *)
   369 
   370 fun mk_constaxiom_decls x =
   371   let
   372     val (axms_defs, axms_names) =
   373       mk_axiom_decls (map (fn ((id, _), def) => (id ^ "_def", def)) x);
   374   in ((mk_big_list o map mk_triple2 o map (apfst quote o fst)) x ^
   375        "\n\n|> (#1 oo (PureThy.add_defs false o map Thm.no_attributes))\n" ^ axms_defs, axms_names)
   376   end;
   377 
   378 val constaxiom_decls =
   379   repeat1 (ident --$$ "::" -- !! (typ -- opt_mixfix) -- !! string)
   380   >> 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, unenclose c ^ "I" :: map fst axms);
   387 
   388 val axclass_decl = subclass -- repeat (ident -- !! string) >> mk_axclass_decl;
   389 
   390 
   391 (* instance *)
   392 
   393 fun mk_witness (axths, opt_tac) =
   394   mk_list (keyfilter axths false) ^ "\n" ^
   395   mk_list (keyfilter axths true) ^ "\n" ^
   396   opt_tac;
   397 
   398 val axm_or_thm =
   399   string >> rpair false ||
   400   long_id >> rpair true;
   401 
   402 
   403 val opt_witness =
   404   optional ("(" $$-- list1 axm_or_thm --$$ ")") [] --
   405   optional (verbatim >> (parens o cat "Some" o parens)) "None"
   406   >> mk_witness;
   407 
   408 val instance_decl =
   409   (name --$$ "<" -- name >> (pair "|> AxClass.add_inst_subclass" o mk_pair) ||
   410     name --$$ "::" -- arity >> (pair "|> AxClass.add_inst_arity" o mk_triple2))
   411   -- opt_witness
   412   >> (fn ((x, y), z) => (cat_lines [x, y, z]));
   413 
   414 
   415 (* locale *)
   416 
   417 val locale_decl =
   418   (name --$$ "=") -- 
   419     (optional ((ident >> (fn x => parens ("Some" ^ quote x))) --$$ "+") ("None")) --
   420     ("fixes" $$--
   421       (repeat (name --$$ "::" -- !! (typ -- opt_mixfix)) 
   422        >> (mk_big_list o map mk_triple2))) --
   423     (optional 
   424      ("assumes" $$-- (repeat ((ident >> quote) -- !! string) 
   425 		     >> (mk_list o map mk_pair)))
   426      "[]") --
   427     (optional 
   428      ("defines" $$-- (repeat ((ident >> quote) -- !! string) 
   429 		      >> (mk_list o map mk_pair)))
   430      "[]")
   431   >> (fn ((((nm, ext), cs), asms), defs) => cat_lines [nm, ext, cs, asms, defs]);
   432 
   433 
   434 
   435 (** theory syntax **)
   436 
   437 type syntax =
   438   Scan.lexicon * (token list -> (string * string) * token list) Symtab.table;
   439 
   440 fun get_lexicon (lex, _) = lex;
   441 
   442 fun make_syntax keywords sects =
   443   let
   444     val dups = duplicates (map fst sects);
   445     val sects' = gen_distinct eq_fst sects;
   446     val keys = map Symbol.explode (map fst sects' @ keywords);
   447   in
   448     if null dups then ()
   449     else warning ("Duplicate declaration of theory file sections:\n" ^ commas_quote dups);
   450     (Scan.make_lexicon keys, Symtab.make sects')
   451   end;
   452 
   453 
   454 (* header *)
   455 
   456 fun mk_header (thy_name, parents) =
   457   (thy_name, "IsarThy.begin_theory " ^ cat (quote thy_name) (mk_list parents) ^ " []");
   458 
   459 val header = ident --$$ "=" -- enum1 "+" name >> mk_header;
   460 
   461 
   462 (* extension *)
   463 
   464 fun mk_extension (txts, mltxt) =
   465   let
   466     val cat_sects = space_implode "\n\n" o filter_out (equal "");
   467     val (extxts, postxts) = split_list txts;
   468   in
   469     (cat_sects extxts, cat_sects postxts, mltxt)
   470   end;
   471 
   472 fun sect tab ((Keyword, s, n) :: toks) =
   473       (case Symtab.lookup (tab, s) of
   474         Some parse => !! parse toks
   475       | None => syn_err "section" s n)
   476   | sect _ ((_, s, n) :: _) = syn_err "section" s n
   477   | sect _ [] = eof_err ();
   478 
   479 fun extension sectab = "+" $$-- !!
   480   (repeat (sect sectab) --$$ "end" -- optional verbatim "")
   481     >> mk_extension;
   482 
   483 fun opt_extension sectab = optional (extension sectab) ("", "", "");
   484 
   485 
   486 (* theory definition *)
   487 
   488 fun mk_structure ((thy_name, bg_theory), (extxt, postxt, mltxt)) =
   489   "structure " ^ thy_name ^ " =\n\
   490   \struct\n\
   491   \\n\
   492   \local\n"
   493   ^ local_defs ^ "\n\
   494   \in\n\
   495   \\n"
   496   ^ mltxt ^ "\n\
   497   \\n\
   498   \val thy = " ^ bg_theory ^ "\n\
   499   \\n\
   500   \|> Theory.add_trfuns\n"
   501   ^ trfun_args ^ "\n\
   502   \|> Theory.add_trfunsT typed_print_translation\n\
   503   \|> Theory.add_tokentrfuns token_translation\n\
   504   \\n"
   505   ^ extxt ^ "\n\
   506   \\n\
   507   \|> IsarThy.end_theory;\n\
   508   \\n\
   509   \val _ = context thy;\n\
   510   \\n\
   511   \\n"
   512   ^ postxt ^ "\n\
   513   \\n\
   514   \end;\n\
   515   \end;\n\
   516   \\n\
   517   \open " ^ thy_name ^ ";\n";
   518 
   519 fun theory_defn sectab =
   520   header -- opt_extension sectab -- eof >> (mk_structure o #1);
   521 
   522 fun parse_thy (lex, sectab) chs = #1 (!! (theory_defn sectab) (tokenize lex chs));
   523 
   524 
   525 (* standard sections *)
   526 
   527 fun mk_val ax = "val " ^ ax ^ " = PureThy.get_thm thy " ^ quote ax ^ ";";
   528 val mk_vals = cat_lines o map mk_val;
   529 
   530 fun mk_axm_sect "" (txt, axs) = (txt, mk_vals axs)
   531   | mk_axm_sect pretxt (txt, axs) = (pretxt ^ "\n" ^ txt, mk_vals axs);
   532 
   533 fun axm_section name pretxt parse =
   534   (name, parse >> mk_axm_sect pretxt);
   535 
   536 fun section name pretxt parse =
   537   axm_section name pretxt (parse >> rpair []);
   538 
   539 
   540 val pure_keywords =
   541  ["end", "ML", "mixfix", "infixr", "infixl", "binder", "output", "=",
   542   "+", ",", "<", "{", "}", "(", ")", "[", "]", "::", "==", "=>",
   543   "<=", "fixes", "assumes", "defines"];
   544 
   545 val pure_sections =
   546  [section "classes" "|> Theory.add_classes" class_decls,
   547   section "default" "|> Theory.add_defsort" sort,
   548   section "types" "" type_decls,
   549   section "nonterminals" "|> Theory.add_nonterminals" (repeat1 name >> mk_list),
   550   section "arities" "|> Theory.add_arities" arity_decls,
   551   section "consts" "|> Theory.add_consts" const_decls,
   552   section "syntax" "|> Theory.add_modesyntax" syntax_decls,
   553   section "translations" "|> Theory.add_trrules" trans_decls,
   554   axm_section "rules" "|> (#1 oo (PureThy.add_axioms o map Thm.no_attributes))" axiom_decls,
   555   axm_section "defs" "|> (#1 oo (PureThy.add_defs false o map Thm.no_attributes))" axiom_decls,
   556   section "oracle" "|> Theory.add_oracle" oracle_decl,
   557   axm_section "constdefs" "|> Theory.add_consts" constaxiom_decls,
   558   axm_section "axclass" "|> (#1 ooo AxClass.add_axclass)" axclass_decl,
   559   section "instance" "" instance_decl,
   560   section "path" "|> Theory.add_path" name,
   561   section "global" "|> PureThy.global_path" empty_decl,
   562   section "local" "|> PureThy.local_path" empty_decl,
   563   section "setup" "|> Library.apply" long_id,
   564   section "MLtext" "" verbatim,
   565   section "locale" "|> Locale.add_locale" locale_decl];
   566 
   567 
   568 end;