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