src/Pure/Thy/thy_parse.ML
author wenzelm
Wed May 20 18:56:59 1998 +0200 (1998-05-20)
changeset 4952 addfa29d0481
parent 4852 58b5006d36cc
child 4965 06914837e073
permissions -rw-r--r--
tuned keywords;
     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 = [];";
   348 
   349 val trfun_args =
   350   "(parse_ast_translation, parse_translation, \
   351   \print_translation, print_ast_translation)";
   352 
   353 
   354 (* axioms *)
   355 
   356 val mk_axms = mk_big_list o map (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|> (PureThy.add_defs o map Attribute.none)\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,
   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 (* local, global path *)
   417 
   418 fun empty_decl toks = (empty >> K "") toks;
   419 
   420 val global_path =
   421   "|> (fn thy => if ! global_names then thy else Theory.root_path thy)";
   422 
   423 val local_path =
   424   global_path ^ "\n\
   425   \|> (fn thy => if ! global_names then thy\
   426   \ else Theory.add_path thy_name thy)";
   427 
   428 
   429 
   430 (** theory syntax **)
   431 
   432 type syntax =
   433   Scan.lexicon * (token list -> (string * string) * token list) Symtab.table;
   434 
   435 fun make_syntax keywords sects =
   436   let
   437     val dups = duplicates (map fst sects);
   438     val sects' = gen_distinct eq_fst sects;
   439     val keys = map Symbol.explode (map fst sects' @ keywords);
   440   in
   441     if null dups then ()
   442     else warning ("Duplicate declaration of theory file sections:\n" ^ commas_quote dups);
   443     (Scan.make_lexicon keys, Symtab.make sects')
   444   end;
   445 
   446 
   447 (* header *)
   448 
   449 fun mk_header (thy_name, bases) =
   450   (thy_name, "mk_base " ^ mk_list bases ^ " " ^ quote thy_name);
   451 
   452 val base =
   453   ident >> (cat "Thy" o quote) ||
   454   string >> cat "File";
   455 
   456 val header = ident --$$ "=" -- enum1 "+" base >> mk_header;
   457 
   458 
   459 (* extension *)
   460 
   461 fun mk_extension (txts, mltxt) =
   462   let
   463     val cat_sects = space_implode "\n\n" o filter_out (equal "");
   464     val (extxts, postxts) = split_list txts;
   465   in
   466     (cat_sects extxts, cat_sects postxts, mltxt)
   467   end;
   468 
   469 fun sect tab ((Keyword, s, n) :: toks) =
   470       (case Symtab.lookup (tab, s) of
   471         Some parse => !! parse toks
   472       | None => syn_err "section" s n)
   473   | sect _ ((_, s, n) :: _) = syn_err "section" s n
   474   | sect _ [] = eof_err ();
   475 
   476 fun extension sectab = "+" $$-- !!
   477   (repeat (sect sectab) --$$ "end" -- optional verbatim "")
   478     >> mk_extension;
   479 
   480 fun opt_extension sectab = optional (extension sectab) ("", "", "");
   481 
   482 
   483 (* theory definition *)
   484 
   485 fun mk_structure tname ((thy_name, old_thys), (extxt, postxt, mltxt)) =
   486   if thy_name <> tname then
   487     error ("Filename \"" ^ tname ^ ".thy\" and theory name "
   488       ^ quote thy_name ^ " are different")
   489   else
   490     "val thy = " ^ old_thys ^ ";\n\n\
   491     \structure " ^ thy_name ^ " =\n\
   492     \struct\n\
   493     \\n\
   494     \local\n\
   495     \ val thy_name = \"" ^ tname ^ "\";\n"
   496     ^ local_defs ^ "\n\
   497     \in\n\
   498     \\n"
   499     ^ mltxt ^ "\n\
   500     \\n\
   501     \val thy = thy\n\
   502     \\n"
   503     ^ local_path ^
   504     "\n\
   505     \|> Theory.add_trfuns\n"
   506     ^ trfun_args ^ "\n\
   507     \|> Theory.add_trfunsT typed_print_translation\n\
   508     \|> Theory.add_tokentrfuns token_translation\n\
   509     \\n"
   510     ^ extxt ^ "\n\
   511     \\n\
   512     \|> Theory.add_name " ^ quote thy_name ^ ";\n\
   513     \\n\
   514     \val _ = store_theory (thy, " ^ quote thy_name ^ ");\n\
   515     \val _ = context thy;\n\
   516     \\n\
   517     \\n"
   518     ^ postxt ^ "\n\
   519     \\n\
   520     \end;\n\
   521     \end;\n\
   522     \\n\
   523     \open " ^ thy_name ^ ";\n\
   524     \\n";
   525 
   526 fun theory_defn sectab tname =
   527   header -- opt_extension sectab -- eof >> (mk_structure tname o #1);
   528 
   529 fun parse_thy (lex, sectab) tname str =
   530   #1 (!! (theory_defn sectab tname) (tokenize lex str));
   531 
   532 
   533 (* standard sections *)
   534 
   535 fun mk_val ax = "val " ^ ax ^ " = get_axiom thy " ^ quote ax ^ ";";
   536 val mk_vals = cat_lines o map mk_val;
   537 
   538 fun mk_axm_sect "" (txt, axs) = (txt, mk_vals axs)
   539   | mk_axm_sect pretxt (txt, axs) = (pretxt ^ "\n" ^ txt, mk_vals axs);
   540 
   541 fun axm_section name pretxt parse =
   542   (name, parse >> mk_axm_sect pretxt);
   543 
   544 fun section name pretxt parse =
   545   axm_section name pretxt (parse >> rpair []);
   546 
   547 
   548 val pure_keywords =
   549  ["end", "ML", "mixfix", "infixr", "infixl", "binder", "output", "=",
   550   "+", ",", "<", "{", "}", "(", ")", "[", "]", "::", "==", "=>",
   551   "<="];
   552 
   553 val pure_sections =
   554  [section "classes" "|> Theory.add_classes" class_decls,
   555   section "default" "|> Theory.add_defsort" sort,
   556   section "types" "" type_decls,
   557   section "nonterminals" "|> Theory.add_nonterminals" (repeat1 name >> mk_list),
   558   section "arities" "|> Theory.add_arities" arity_decls,
   559   section "consts" "|> Theory.add_consts" const_decls,
   560   section "syntax" "|> Theory.add_modesyntax" syntax_decls,
   561   section "translations" "|> Theory.add_trrules" trans_decls,
   562   axm_section "rules" "|> (PureThy.add_axioms o map Attribute.none)" axiom_decls,
   563   axm_section "defs" "|> (PureThy.add_defs o map Attribute.none)" axiom_decls,
   564   section "oracle" "|> Theory.add_oracle" oracle_decl,
   565   axm_section "constdefs" "|> Theory.add_consts" constaxiom_decls,
   566   axm_section "axclass" "|> AxClass.add_axclass" axclass_decl,
   567   section "instance" "" instance_decl,
   568   section "path" "|> Theory.add_path" name,
   569   section "global" global_path empty_decl,
   570   section "local" local_path empty_decl,
   571   section "setup" "|> Theory.apply" long_id,
   572   section "MLtext" "" verbatim];
   573 
   574 
   575 end;