src/Pure/ProofGeneral/proof_general_pgip.ML
author wenzelm
Sat Dec 30 16:08:10 2006 +0100 (2006-12-30)
changeset 21969 a8bf1106cb7c
parent 21959 b50182aff75f
child 21970 1845e43aee93
permissions -rw-r--r--
removed conditional combinator;
avoid handle _;
showctxt: print_context (cf. local theory context);
searchtheorems: proper find_theorems;
refrain from setting ml_prompts again;
tuned init_pgip;
aspinall@21637
     1
(*  Title:      Pure/ProofGeneral/proof_general_pgip.ML
aspinall@21637
     2
    ID:         $Id$
aspinall@21637
     3
    Author:     David Aspinall and Markus Wenzel
aspinall@21637
     4
aspinall@21637
     5
Isabelle configuration for Proof General using PGIP protocol.
wenzelm@21940
     6
See http://proofgeneral.inf.ed.ac.uk/kit
aspinall@21637
     7
*)
aspinall@21637
     8
aspinall@21637
     9
signature PROOF_GENERAL_PGIP =
aspinall@21637
    10
sig
wenzelm@21940
    11
  val init_pgip: bool -> unit             (* main PGIP loop with true; fail with false *)
aspinall@21642
    12
aspinall@21649
    13
  (* These two are just to support the semi-PGIP Emacs mode *)
wenzelm@21940
    14
  val init_pgip_channel: (string -> unit) -> unit
wenzelm@21940
    15
  val process_pgip: string -> unit
aspinall@21637
    16
end
aspinall@21637
    17
aspinall@21637
    18
structure ProofGeneralPgip : PROOF_GENERAL_PGIP  =
aspinall@21637
    19
struct
aspinall@21637
    20
aspinall@21637
    21
structure P = OuterParse;
aspinall@21637
    22
aspinall@21637
    23
open Pgip;
aspinall@21637
    24
wenzelm@21949
    25
aspinall@21637
    26
(* print modes *)
aspinall@21637
    27
aspinall@21637
    28
val proof_generalN = "ProofGeneral";  (*token markup (colouring vars, etc.)*)
aspinall@21637
    29
val pgmlN = "PGML";                   (*XML escapes and PGML symbol elements*)
aspinall@21637
    30
val pgmlatomsN = "PGMLatoms";         (*variable kind decorations*)
aspinall@21637
    31
val thm_depsN = "thm_deps";           (*meta-information about theorem deps*)
aspinall@21637
    32
aspinall@21637
    33
aspinall@21637
    34
(* text output: print modes for xsymbol and PGML *)
aspinall@21637
    35
aspinall@21637
    36
local
aspinall@21637
    37
aspinall@21637
    38
fun xsym_output "\\" = "\\\\"
aspinall@21637
    39
  | xsym_output s = if Symbol.is_raw s then Symbol.decode_raw s else s;
aspinall@21637
    40
aspinall@21637
    41
fun xsymbols_output s =
wenzelm@21940
    42
  if Output.has_mode Symbol.xsymbolsN andalso exists_string (equal "\\") s then
aspinall@21637
    43
    let val syms = Symbol.explode s
aspinall@21637
    44
    in (implode (map xsym_output syms), real (Symbol.length syms)) end
aspinall@21637
    45
  else Symbol.default_output s;
aspinall@21637
    46
aspinall@21637
    47
(* XML immediately rendered pretty printer. Take care not to double escape *)
aspinall@21637
    48
fun pgml_sym s =
aspinall@21637
    49
  (case Symbol.decode s of
aspinall@21637
    50
    Symbol.Char s => XML.text s
wenzelm@21940
    51
  | Symbol.Sym sn => XML.element "sym" [("name", sn)] [XML.text s]
aspinall@21637
    52
  | Symbol.Ctrl sn => XML.element "ctrl" [("name", sn)] [XML.text s] (* FIXME: no such PGML! *)
aspinall@21637
    53
  | Symbol.Raw s => s);
aspinall@21637
    54
aspinall@21637
    55
fun pgml_output str =
aspinall@21637
    56
  let val syms = Symbol.explode str
aspinall@21637
    57
  in (implode (map pgml_sym syms), real (Symbol.length syms)) end;
aspinall@21637
    58
aspinall@21637
    59
in
aspinall@21637
    60
aspinall@21637
    61
fun setup_xsymbols_output () =
wenzelm@21940
    62
  Output.add_mode Symbol.xsymbolsN
aspinall@21637
    63
    (xsymbols_output, K xsymbols_output, Symbol.default_indent, Symbol.encode_raw);
aspinall@21637
    64
aspinall@21637
    65
fun setup_pgml_output () =
aspinall@21637
    66
  Output.add_mode pgmlN
aspinall@21637
    67
    (pgml_output, K pgml_output, Symbol.default_indent, Symbol.encode_raw);
aspinall@21637
    68
aspinall@21637
    69
end;
aspinall@21637
    70
aspinall@21637
    71
aspinall@21637
    72
(* token translations *)
aspinall@21637
    73
aspinall@21637
    74
local
aspinall@21637
    75
aspinall@21637
    76
val class_tag = "class"
aspinall@21637
    77
val tfree_tag = "tfree"
aspinall@21637
    78
val tvar_tag = "tvar"
aspinall@21637
    79
val free_tag = "free"
aspinall@21637
    80
val bound_tag = "bound"
aspinall@21637
    81
val var_tag = "var"
aspinall@21637
    82
val skolem_tag = "skolem"
aspinall@21637
    83
aspinall@21637
    84
fun xml_atom kind x = XML.element "atom" [("kind", kind)] [XML.text x];
aspinall@21637
    85
wenzelm@21940
    86
fun tagit kind x =
wenzelm@21949
    87
  (xml_atom kind x, real (Symbol.length (Symbol.explode x)));
aspinall@21637
    88
aspinall@21637
    89
fun free_or_skolem x =
aspinall@21637
    90
  (case try Name.dest_skolem x of
aspinall@21637
    91
    NONE => tagit free_tag x
aspinall@21637
    92
  | SOME x' => tagit skolem_tag x');
aspinall@21637
    93
aspinall@21637
    94
fun var_or_skolem s =
aspinall@21637
    95
  (case Syntax.read_variable s of
aspinall@21637
    96
    SOME (x, i) =>
aspinall@21637
    97
      (case try Name.dest_skolem x of
aspinall@21637
    98
        NONE => tagit var_tag s
aspinall@21637
    99
      | SOME x' => tagit skolem_tag
aspinall@21637
   100
          (setmp show_question_marks true Syntax.string_of_vname (x', i)))
aspinall@21637
   101
  | NONE => tagit var_tag s);
aspinall@21637
   102
aspinall@21637
   103
val proof_general_trans =
aspinall@21637
   104
 Syntax.tokentrans_mode proof_generalN
aspinall@21637
   105
  [("class", tagit class_tag),
aspinall@21637
   106
   ("tfree", tagit tfree_tag),
aspinall@21637
   107
   ("tvar", tagit tvar_tag),
aspinall@21637
   108
   ("free", free_or_skolem),
aspinall@21637
   109
   ("bound", tagit bound_tag),
aspinall@21637
   110
   ("var", var_or_skolem)];
aspinall@21637
   111
aspinall@21637
   112
in
aspinall@21637
   113
aspinall@21637
   114
val _ = Context.add_setup (Theory.add_tokentrfuns proof_general_trans);
aspinall@21637
   115
aspinall@21637
   116
end;
aspinall@21637
   117
aspinall@21637
   118
aspinall@21637
   119
(** assembling and issuing PGIP packets **)
aspinall@21637
   120
aspinall@21637
   121
val pgip_refid  = ref NONE: string option ref;
aspinall@21637
   122
val pgip_refseq = ref NONE: int option ref;
aspinall@21637
   123
aspinall@21637
   124
local
aspinall@21637
   125
  val pgip_class  = "pg"
aspinall@21637
   126
  val pgip_tag = "Isabelle/Isar"
aspinall@21637
   127
  val pgip_id = ref ""
aspinall@21637
   128
  val pgip_seq = ref 0
aspinall@21637
   129
  fun pgip_serial () = inc pgip_seq
aspinall@21637
   130
aspinall@21637
   131
  fun assemble_pgips pgips =
wenzelm@21940
   132
    Pgip { tag = SOME pgip_tag,
wenzelm@21940
   133
           class = pgip_class,
wenzelm@21940
   134
           seq = pgip_serial(),
wenzelm@21940
   135
           id = !pgip_id,
wenzelm@21940
   136
           destid = !pgip_refid,
wenzelm@21940
   137
           (* destid=refid since Isabelle only communicates back to sender *)
wenzelm@21940
   138
           refid  = !pgip_refid,
wenzelm@21940
   139
           refseq = !pgip_refseq,
wenzelm@21940
   140
           content = pgips }
aspinall@21637
   141
in
aspinall@21637
   142
aspinall@21637
   143
fun init_pgip_session_id () =
aspinall@21637
   144
    pgip_id := getenv "HOSTNAME" ^ "/" ^ getenv "USER" ^ "/" ^
aspinall@21637
   145
               getenv "ISABELLE_PID" ^ "/" ^ Time.toString (Time.now ())
aspinall@21637
   146
aspinall@21637
   147
fun matching_pgip_id id = (id = !pgip_id)
aspinall@21637
   148
wenzelm@21940
   149
val output_xml_fn = ref writeln_default
aspinall@21649
   150
fun output_xml s = (!output_xml_fn) (XML.string_of_tree s);  (* TODO: string buffer *)
aspinall@21637
   151
wenzelm@21940
   152
fun issue_pgip_rawtext str =
aspinall@21649
   153
    output_xml (PgipOutput.output (assemble_pgips [XML.Rawtext str]))
aspinall@21637
   154
aspinall@21637
   155
fun issue_pgips pgipops =
aspinall@21637
   156
    output_xml (PgipOutput.output (assemble_pgips (map PgipOutput.output pgipops)));
aspinall@21637
   157
aspinall@21637
   158
fun issue_pgip pgipop =
aspinall@21637
   159
    output_xml (PgipOutput.output (assemble_pgips [PgipOutput.output pgipop]));
aspinall@21637
   160
aspinall@21637
   161
end;
aspinall@21637
   162
aspinall@21637
   163
aspinall@21637
   164
(** messages and notification **)
aspinall@21637
   165
aspinall@21637
   166
local
aspinall@21637
   167
    val delay_msgs = ref false   (*true: accumulate messages*)
aspinall@21637
   168
    val delayed_msgs = ref []
aspinall@21637
   169
aspinall@21637
   170
    fun queue_or_issue pgip =
wenzelm@21940
   171
        if ! delay_msgs then
wenzelm@21940
   172
            delayed_msgs := pgip :: ! delayed_msgs
wenzelm@21940
   173
        else issue_pgip pgip
aspinall@21637
   174
in
wenzelm@21940
   175
    fun normalmsg area cat urgent s =
wenzelm@21940
   176
        let
wenzelm@21940
   177
            val content = XML.Elem("pgmltext",[],[XML.Rawtext s])
wenzelm@21940
   178
            val pgip = Normalresponse {area=area,messagecategory=cat,
wenzelm@21940
   179
                                       urgent=urgent,content=[content] }
wenzelm@21940
   180
        in
wenzelm@21940
   181
            queue_or_issue pgip
wenzelm@21940
   182
        end
aspinall@21637
   183
aspinall@21885
   184
    fun errormsg fatality s =
wenzelm@21940
   185
        let
aspinall@21885
   186
              val content = XML.Elem("pgmltext",[],[XML.Rawtext s])
wenzelm@21940
   187
              val pgip = Errorresponse {area=NONE,fatality=fatality,
wenzelm@21940
   188
                                        content=[content],
wenzelm@21940
   189
                                        (* FIXME: pass in locations *)
wenzelm@21940
   190
                                        location=NONE}
wenzelm@21940
   191
        in
wenzelm@21940
   192
            queue_or_issue pgip
wenzelm@21940
   193
        end
aspinall@21637
   194
aspinall@21637
   195
    fun start_delay_msgs () = (set delay_msgs; delayed_msgs := [])
aspinall@21637
   196
    fun end_delayed_msgs () = (reset delay_msgs; ! delayed_msgs)
aspinall@21637
   197
end;
aspinall@21637
   198
aspinall@21637
   199
(* NB: all of the standard error/message functions now expect already-escaped text.
aspinall@21637
   200
   FIXME: this may cause us problems now we're generating trees; on the other
wenzelm@21940
   201
   hand the output functions were tuned some time ago, so it ought to be
aspinall@21637
   202
   enough to use Rawtext always above. *)
aspinall@21637
   203
aspinall@21637
   204
fun setup_messages () =
aspinall@21885
   205
 (writeln_fn := (fn s => normalmsg Message Normal false s);
aspinall@21885
   206
  priority_fn := (fn s => normalmsg Message Normal true s);
aspinall@21885
   207
  tracing_fn := (fn s => normalmsg  Message Tracing false s);
aspinall@21885
   208
  info_fn := (fn s => normalmsg Message Information false s);
aspinall@21885
   209
  debug_fn := (fn s => normalmsg Message Internal false s);
aspinall@21885
   210
  warning_fn := (fn s => errormsg Nonfatal s);
aspinall@21885
   211
  error_fn := (fn s => errormsg Fatal s);
aspinall@21885
   212
  panic_fn := (fn s => errormsg Panic s))
aspinall@21637
   213
aspinall@21637
   214
(* immediate messages *)
aspinall@21637
   215
aspinall@21637
   216
fun tell_clear_goals ()      = issue_pgip (Cleardisplay {area=Display})
aspinall@21637
   217
fun tell_clear_response ()   = issue_pgip (Cleardisplay {area=Message})
aspinall@21637
   218
fun tell_file_loaded path    = issue_pgip (Informfileloaded {url=PgipTypes.pgipurl_of_path path})
aspinall@21637
   219
fun tell_file_retracted path = issue_pgip (Informfileretracted {url=PgipTypes.pgipurl_of_path path})
aspinall@21637
   220
aspinall@21637
   221
aspinall@21637
   222
aspinall@21637
   223
(** theory / proof state output **)
aspinall@21637
   224
aspinall@21637
   225
local
aspinall@21637
   226
aspinall@21637
   227
fun statedisplay prts =
aspinall@21637
   228
    let
wenzelm@21940
   229
        val display = Pretty.output (Pretty.chunks prts)
wenzelm@21940
   230
        val statedisplay = XML.Elem("statedisplay",[], [XML.Rawtext display])
aspinall@21637
   231
    in
wenzelm@21940
   232
        issue_pgip (Proofstate {pgml=[XML.Elem("pgml",[],[statedisplay])]})
aspinall@21637
   233
    end
aspinall@21637
   234
aspinall@21637
   235
fun print_current_goals n m st =
aspinall@21637
   236
  statedisplay (Display.pretty_current_goals n m st)
aspinall@21637
   237
aspinall@21637
   238
fun print_state b st =
aspinall@21637
   239
  statedisplay (Toplevel.pretty_state b st)
aspinall@21637
   240
aspinall@21637
   241
in
aspinall@21637
   242
aspinall@21637
   243
fun setup_state () =
aspinall@21637
   244
  (Display.print_current_goals_fn := print_current_goals;
aspinall@21637
   245
   Toplevel.print_state_fn := print_state);
aspinall@21637
   246
      (*    Toplevel.prompt_state_fn := (fn s => suffix (special "372")
wenzelm@21940
   247
                                        (Toplevel.prompt_state_default s))); *)
aspinall@21637
   248
aspinall@21637
   249
end;
aspinall@21637
   250
aspinall@21637
   251
aspinall@21637
   252
(* theory loader actions *)
aspinall@21637
   253
aspinall@21637
   254
local
aspinall@21637
   255
aspinall@21637
   256
fun trace_action action name =
aspinall@21637
   257
  if action = ThyInfo.Update then
aspinall@21637
   258
    List.app tell_file_loaded (ThyInfo.loaded_files name)
aspinall@21637
   259
  else if action = ThyInfo.Outdate orelse action = ThyInfo.Remove then
aspinall@21637
   260
    List.app tell_file_retracted (ThyInfo.loaded_files name)
aspinall@21637
   261
  else ();
aspinall@21637
   262
aspinall@21637
   263
in
aspinall@21637
   264
  fun setup_thy_loader () = ThyInfo.add_hook trace_action;
aspinall@21637
   265
  fun sync_thy_loader () = List.app (trace_action ThyInfo.Update) (ThyInfo.names ());
aspinall@21637
   266
end;
aspinall@21637
   267
aspinall@21637
   268
wenzelm@21949
   269
(* get informed about files *)
aspinall@21637
   270
wenzelm@21858
   271
val thy_name = Path.implode o #1 o Path.split_ext o Path.base o Path.explode;
aspinall@21637
   272
aspinall@21637
   273
val inform_file_retracted = ThyInfo.if_known_thy ThyInfo.remove_thy o thy_name;
aspinall@21637
   274
val inform_file_processed = ThyInfo.if_known_thy ThyInfo.touch_child_thys o thy_name;
aspinall@21637
   275
aspinall@21637
   276
fun proper_inform_file_processed file state =
aspinall@21637
   277
  let val name = thy_name file in
aspinall@21637
   278
    if Toplevel.is_toplevel state andalso ThyInfo.known_thy name then
aspinall@21637
   279
     (ThyInfo.touch_child_thys name;
aspinall@21637
   280
      ThyInfo.pretend_use_thy_only name handle ERROR msg =>
aspinall@21637
   281
       (warning msg; warning ("Failed to register theory: " ^ quote name);
wenzelm@21858
   282
        tell_file_retracted (Path.base (Path.explode file))))
aspinall@21637
   283
    else raise Toplevel.UNDEF
aspinall@21637
   284
  end;
aspinall@21637
   285
aspinall@21637
   286
fun vacuous_inform_file_processed file state =
aspinall@21637
   287
 (warning ("No theory " ^ quote (thy_name file));
wenzelm@21858
   288
  tell_file_retracted (Path.base (Path.explode file)));
aspinall@21637
   289
aspinall@21637
   290
aspinall@21637
   291
(* restart top-level loop (keeps most state information) *)
aspinall@21637
   292
aspinall@21637
   293
val welcome = priority o Session.welcome;
aspinall@21637
   294
aspinall@21637
   295
fun restart () =
aspinall@21637
   296
    (sync_thy_loader ();
aspinall@21637
   297
     tell_clear_goals ();
aspinall@21637
   298
     tell_clear_response ();
aspinall@21637
   299
     welcome ();
aspinall@21655
   300
     priority "Running new version of PGIP code.  In testing.";
aspinall@21637
   301
     raise Toplevel.RESTART)
aspinall@21637
   302
aspinall@21637
   303
aspinall@21637
   304
(* theorem dependency output *)
aspinall@21637
   305
local
aspinall@21637
   306
aspinall@21637
   307
val spaces_quote = space_implode " " o map quote;
aspinall@21637
   308
aspinall@21637
   309
fun thm_deps_message (thms, deps) =
wenzelm@21940
   310
    let
wenzelm@21940
   311
        val valuethms = XML.Elem("value",[("name", "thms")],[XML.Text thms])
wenzelm@21940
   312
        val valuedeps = XML.Elem("value",[("name", "deps")],[XML.Text deps])
aspinall@21637
   313
    in
wenzelm@21940
   314
        issue_pgip (Metainforesponse {attrs=[("infotype", "isabelle_theorem_dependencies")],
wenzelm@21940
   315
                                      content=[valuethms,valuedeps]})
aspinall@21637
   316
    end
aspinall@21637
   317
aspinall@21637
   318
(* FIXME: check this uses non-transitive closure function here *)
wenzelm@21969
   319
fun tell_thm_deps ths =
wenzelm@21969
   320
  if Output.has_mode thm_depsN then
wenzelm@21969
   321
    let
wenzelm@21969
   322
      val names = filter_out (equal "") (map PureThy.get_name_hint ths);
wenzelm@21969
   323
      val deps = filter_out (equal "")
wenzelm@21969
   324
        (Symtab.keys (fold Proofterm.thms_of_proof
wenzelm@21969
   325
          (map Thm.proof_of ths) Symtab.empty));
wenzelm@21969
   326
    in
wenzelm@21969
   327
      if null names orelse null deps then ()
wenzelm@21969
   328
      else thm_deps_message (spaces_quote names, spaces_quote deps)
wenzelm@21969
   329
    end
wenzelm@21969
   330
  else ();
aspinall@21637
   331
aspinall@21637
   332
in
aspinall@21637
   333
aspinall@21637
   334
fun setup_present_hook () =
aspinall@21637
   335
  Present.add_hook (fn _ => fn res => tell_thm_deps (maps #2 res));
aspinall@21637
   336
aspinall@21637
   337
end;
aspinall@21637
   338
aspinall@21637
   339
(** lexicalstructure element with keywords (PGIP version of elisp keywords file) **)
aspinall@21637
   340
wenzelm@21940
   341
fun lexicalstructure_keywords () =
aspinall@21637
   342
    let val commands = OuterSyntax.dest_keywords ()
wenzelm@21940
   343
        fun category_of k = if k mem commands then "major" else "minor"
aspinall@21637
   344
         (* NB: we might filter to only include words like elisp case (OuterSyntax.is_keyword). *)
wenzelm@21940
   345
        fun keyword_elt (keyword,help,kind,_) =
wenzelm@21940
   346
            XML.Elem("keyword", [("word", keyword), ("category", category_of kind)],
wenzelm@21940
   347
                     [XML.Elem("shorthelp", [], [XML.Text help])])
wenzelm@21940
   348
        in
aspinall@21637
   349
            (* Also, note we don't call init_outer_syntax here to add interface commands,
aspinall@21637
   350
            but they should never appear in scripts anyway so it shouldn't matter *)
aspinall@21637
   351
            Lexicalstructure {content = map keyword_elt (OuterSyntax.dest_parsers()) }
aspinall@21637
   352
        end
aspinall@21637
   353
aspinall@21637
   354
(* TODO: we can issue a lexicalstructure/keyword when the syntax gets extended dynamically;
aspinall@21637
   355
   hooks needed in outer_syntax.ML to do that. *)
aspinall@21637
   356
aspinall@21637
   357
aspinall@21637
   358
(* Configuration: GUI config, proverinfo messages *)
aspinall@21637
   359
aspinall@21637
   360
local
aspinall@21637
   361
    val isabellewww = "http://isabelle.in.tum.de/"
aspinall@21637
   362
    val staticconfig = "~~/lib/ProofGeneral/pgip_isar.xml"
wenzelm@21940
   363
    fun orenv v d = case getenv v of "" => d  | s => s
aspinall@21637
   364
    fun config_file()  = orenv "ISABELLE_PGIPCONFIG" staticconfig
aspinall@21637
   365
    fun isabelle_www() = orenv "ISABELLE_HOMEPAGE" isabellewww
aspinall@21637
   366
in
aspinall@21637
   367
fun send_pgip_config () =
aspinall@21637
   368
    let
wenzelm@21858
   369
        val path = Path.explode (config_file())
wenzelm@21940
   370
        val ex = File.exists path
aspinall@21637
   371
wenzelm@21940
   372
        val wwwpage =
wenzelm@21940
   373
            (Url.explode (isabelle_www()))
wenzelm@21969
   374
            handle ERROR _ =>
wenzelm@21940
   375
                   (Output.panic
wenzelm@21940
   376
                        ("Error in URL in environment variable ISABELLE_HOMEPAGE.");
wenzelm@21940
   377
                        Url.explode isabellewww)
wenzelm@21940
   378
wenzelm@21940
   379
        val proverinfo =
aspinall@21637
   380
            Proverinfo { name = "Isabelle",
wenzelm@21940
   381
                         version = version,
wenzelm@21940
   382
                         instance = Session.name(),
wenzelm@21940
   383
                         descr = "The Isabelle/Isar theorem prover",
wenzelm@21940
   384
                         url = wwwpage,
wenzelm@21940
   385
                         filenameextns = ".thy;" }
aspinall@21637
   386
    in
wenzelm@21940
   387
        if ex then
wenzelm@21940
   388
            (issue_pgip proverinfo;
wenzelm@21940
   389
             issue_pgip_rawtext (File.read path);
wenzelm@21940
   390
             issue_pgip (lexicalstructure_keywords()))
aspinall@21637
   391
        else Output.panic ("PGIP configuration file \"" ^ config_file() ^ "\" not found")
aspinall@21637
   392
    end;
aspinall@21637
   393
end
aspinall@21637
   394
aspinall@21637
   395
aspinall@21637
   396
aspinall@21637
   397
aspinall@21637
   398
(* Sending commands to Isar *)
aspinall@21637
   399
aspinall@21637
   400
fun isarcmd s =
aspinall@21637
   401
    s |> OuterSyntax.scan |> OuterSyntax.read
aspinall@21885
   402
      (*|> map (Toplevel.position (Position.name "PGIP message") o #3)*)
aspinall@21885
   403
      |> map #3
aspinall@21885
   404
      |> Toplevel.>>>;
aspinall@21637
   405
wenzelm@21940
   406
(* TODO:
aspinall@21885
   407
    - apply a command given a transition function, e.g. IsarCmd.undo.
aspinall@21885
   408
    - fix position from path of currently open file [line numbers risk garbling though].
aspinall@21885
   409
*)
aspinall@21637
   410
aspinall@21637
   411
(* load an arbitrary file (must be .thy or .ML) *)
aspinall@21637
   412
aspinall@21637
   413
fun use_thy_or_ml_file file =
aspinall@21637
   414
    let
wenzelm@21858
   415
        val (path,extn) = Path.split_ext (Path.explode file)
aspinall@21637
   416
    in
aspinall@21637
   417
        case extn of
wenzelm@21940
   418
            "" => isarcmd ("use_thy " ^ quote (Path.implode path))
wenzelm@21940
   419
          | "thy" => isarcmd ("use_thy " ^ quote (Path.implode path))
aspinall@21637
   420
          | "ML" => isarcmd ("use " ^ quote file)
aspinall@21637
   421
          | other => error ("Don't know how to read a file with extension " ^ other)
aspinall@21637
   422
    end
aspinall@21637
   423
aspinall@21637
   424
aspinall@21867
   425
(******* PGIP actions *******)
aspinall@21637
   426
aspinall@21637
   427
wenzelm@21940
   428
(* Responses to each of the PGIP input commands.
aspinall@21637
   429
   These are programmed uniformly for extensibility. *)
aspinall@21637
   430
wenzelm@21940
   431
fun askpgip (Askpgip vs) =
aspinall@21637
   432
    issue_pgip
aspinall@21637
   433
        (Usespgip { version = PgipIsabelle.isabelle_pgip_version_supported,
wenzelm@21940
   434
                    pgipelems = PgipIsabelle.accepted_inputs })
aspinall@21637
   435
wenzelm@21940
   436
fun askpgml (Askpgml vs) =
aspinall@21637
   437
    issue_pgip
wenzelm@21940
   438
        (Usespgml { version = PgipIsabelle.isabelle_pgml_version_supported })
aspinall@21637
   439
haftmann@21902
   440
fun askprefs (Askprefs vs) =
wenzelm@21940
   441
    let
wenzelm@21940
   442
        fun preference_of {name, descr, default, pgiptype, get, set } =
wenzelm@21940
   443
            { name = name, descr = SOME descr, default = SOME default,
wenzelm@21940
   444
              pgiptype = pgiptype }
aspinall@21637
   445
    in
wenzelm@21940
   446
        List.app (fn (prefcat, prefs) =>
wenzelm@21940
   447
                     issue_pgip (Hasprefs {prefcategory=SOME prefcat,
wenzelm@21940
   448
                                           prefs=map preference_of prefs}))
aspinall@21637
   449
                 Preferences.preferences
wenzelm@21940
   450
    end
aspinall@21637
   451
haftmann@21902
   452
fun askconfig (Askconfig vs) = () (* TODO: add config response *)
aspinall@21637
   453
aspinall@21637
   454
local
wenzelm@21940
   455
    fun lookuppref pref =
wenzelm@21940
   456
        case AList.lookup (op =)
wenzelm@21940
   457
                          (map (fn p => (#name p,p))
wenzelm@21940
   458
                               (maps snd Preferences.preferences)) pref of
wenzelm@21940
   459
            NONE => error ("Unknown prover preference: " ^ quote pref)
wenzelm@21940
   460
          | SOME p => p
aspinall@21637
   461
in
wenzelm@21940
   462
fun setpref (Setpref vs) =
wenzelm@21940
   463
    let
wenzelm@21940
   464
        val name = #name vs
wenzelm@21940
   465
        val value = #value vs
wenzelm@21940
   466
        val set = #set (lookuppref name)
aspinall@21637
   467
    in
wenzelm@21940
   468
        set value
aspinall@21637
   469
    end
aspinall@21637
   470
haftmann@21902
   471
fun getpref (Getpref vs) =
wenzelm@21940
   472
    let
wenzelm@21940
   473
        val name = #name vs
wenzelm@21940
   474
        val get = #get (lookuppref name)
wenzelm@21940
   475
    in
aspinall@21637
   476
        issue_pgip (Prefval {name=name, value=get ()})
aspinall@21637
   477
    end
aspinall@21637
   478
end
aspinall@21637
   479
aspinall@21637
   480
fun proverinit vs = restart ()
aspinall@21637
   481
aspinall@21637
   482
fun proverexit vs = isarcmd "quit"
aspinall@21637
   483
aspinall@21637
   484
fun startquiet vs = isarcmd "disable_pr"
aspinall@21637
   485
aspinall@21637
   486
fun stopquiet vs = isarcmd "enable_pr"
aspinall@21637
   487
wenzelm@21940
   488
fun pgmlsymbolson vs =
aspinall@21637
   489
    change print_mode (fn mode =>
wenzelm@21940
   490
                          remove (op =) Symbol.xsymbolsN mode @ [Symbol.xsymbolsN])
aspinall@21637
   491
aspinall@21637
   492
fun pgmlsymbolsoff vs =
aspinall@21637
   493
    change print_mode (remove (op =) Symbol.xsymbolsN)
aspinall@21637
   494
wenzelm@21940
   495
fun dostep (Dostep vs) =
wenzelm@21940
   496
    let
wenzelm@21940
   497
        val text = #text vs
wenzelm@21940
   498
    in
wenzelm@21940
   499
        isarcmd text
aspinall@21637
   500
    end
aspinall@21637
   501
haftmann@21902
   502
fun undostep (Undostep vs) =
wenzelm@21940
   503
    let
wenzelm@21940
   504
        val times = #times vs
wenzelm@21940
   505
    in
wenzelm@21940
   506
        isarcmd ("undos_proof " ^ Int.toString times)
aspinall@21637
   507
    end
aspinall@21637
   508
aspinall@21637
   509
fun redostep vs = isarcmd "redo"
wenzelm@21940
   510
wenzelm@21940
   511
fun abortgoal vs = isarcmd "ProofGeneral.kill_proof"
aspinall@21637
   512
aspinall@21637
   513
aspinall@21867
   514
(*** PGIP identifier tables ***)
aspinall@21867
   515
aspinall@21867
   516
fun setids t = issue_pgip (Setids {idtables = [t]})
aspinall@21867
   517
fun addids t = issue_pgip (Addids {idtables = [t]})
aspinall@21867
   518
fun delids t = issue_pgip (Delids {idtables = [t]})
aspinall@21867
   519
aspinall@21867
   520
(*
wenzelm@21940
   521
 fun delallids ty =
wenzelm@21940
   522
     issue_pgip (Setids {idtables =
wenzelm@21940
   523
                        [{context=NONE,objtype=ty,ids=[]}]}) *)
aspinall@21867
   524
wenzelm@21940
   525
fun askids (Askids vs) =
aspinall@21637
   526
    let
wenzelm@21940
   527
        val url = #url vs            (* ask for identifiers within a file *)
wenzelm@21940
   528
        val thyname = #thyname vs    (* ask for identifiers within a theory *)
wenzelm@21940
   529
        val objtype = #objtype vs    (* ask for identifiers of a particular type *)
aspinall@21867
   530
wenzelm@21940
   531
        fun idtable ty ctx ids = {objtype=ty,context=ctx,ids=ids}
aspinall@21867
   532
wenzelm@21940
   533
        val thms_of_thy = map fst o PureThy.thms_of o ThyInfo.get_theory
wenzelm@21940
   534
    in
wenzelm@21940
   535
(*      case (url_attr,thyname,objtype) of
wenzelm@21940
   536
            (NONE,NONE,NONE) =>
wenzelm@21940
   537
*)          (* top-level: return *)
aspinall@21867
   538
wenzelm@21940
   539
        (* TODO: add askids for "file" here, which returns single theory with same name *)
aspinall@21867
   540
        (* FIXME: objtypes on both sides *)
wenzelm@21940
   541
        case (thyname,objtype) of
aspinall@21867
   542
           (* only files known in top context *)
wenzelm@21940
   543
           (NONE, NONE)               => setids (idtable ObjFile NONE (ThyInfo.names())) (*FIXME: uris?*)
wenzelm@21940
   544
         | (NONE, SOME ObjFile)        => setids (idtable ObjFile NONE (ThyInfo.names())) (* ditto *)
wenzelm@21940
   545
         | (SOME fi, SOME ObjFile)     => setids (idtable ObjTheory (SOME fi) [fi]) (* FIXME: lookup file *)
wenzelm@21940
   546
         | (NONE, SOME ObjTheory)      => setids (idtable ObjTheory NONE (ThyInfo.names()))
wenzelm@21940
   547
         | (SOME thy, SOME ObjTheory)  => setids (idtable ObjTheory (SOME thy) (ThyInfo.get_preds thy))
wenzelm@21940
   548
         | (SOME thy, SOME ObjTheorem) => setids (idtable ObjTheorem (SOME thy) (thms_of_thy thy))
wenzelm@21940
   549
         (* next case is both of above.  FIXME: cleanup this *)
wenzelm@21940
   550
         | (SOME thy, NONE) => (setids (idtable ObjTheory (SOME thy) (ThyInfo.get_preds thy));
wenzelm@21940
   551
                                setids (idtable ObjTheorem (SOME thy) (thms_of_thy thy)))
wenzelm@21940
   552
         | (_, SOME ot) => error ("No objects of type "^(PgipTypes.name_of_objtype ot)^" are available here.")
aspinall@21637
   553
    end
aspinall@21637
   554
aspinall@21637
   555
local
aspinall@21637
   556
  (* accumulate printed output in a single PGIP response (inside <pgmltext>) *)
aspinall@21637
   557
  fun with_displaywrap pgipfn dispfn =
aspinall@21637
   558
      let
wenzelm@21940
   559
          val lines = ref ([]: string list);
wenzelm@21940
   560
          fun wlgrablines s = lines := s :: ! lines;
aspinall@21637
   561
      in
wenzelm@21940
   562
          setmp writeln_fn wlgrablines dispfn ();
wenzelm@21940
   563
          issue_pgip (pgipfn (!lines))
aspinall@21637
   564
      end;
aspinall@21637
   565
in
wenzelm@21940
   566
fun showid (Showid vs) =
aspinall@21637
   567
    let
wenzelm@21940
   568
        val thyname = #thyname vs
wenzelm@21940
   569
        val objtype = #objtype vs
wenzelm@21940
   570
        val name = #name vs
wenzelm@21940
   571
        val topthy = Toplevel.theory_of o Toplevel.get_state
aspinall@21637
   572
wenzelm@21940
   573
        fun idvalue objtype name strings =
wenzelm@21940
   574
            Idvalue { name=name, objtype=objtype,
wenzelm@21940
   575
                      text=[XML.Elem("pgmltext",[],map XML.Text strings)] }
aspinall@21637
   576
wenzelm@21940
   577
        fun pthm thy name = print_thm (get_thm thy (Name name))
wenzelm@21940
   578
    in
wenzelm@21940
   579
        case (thyname, objtype) of
wenzelm@21940
   580
            (_,ObjTheory) =>
wenzelm@21940
   581
            with_displaywrap (idvalue ObjTheory name)
wenzelm@21940
   582
                             (fn ()=>(print_theory (ThyInfo.get_theory name)))
wenzelm@21940
   583
          | (SOME thy, ObjTheorem) =>
wenzelm@21940
   584
            with_displaywrap (idvalue ObjTheorem name)
wenzelm@21940
   585
                             (fn ()=>(pthm (ThyInfo.get_theory thy) name))
wenzelm@21940
   586
          | (NONE, ObjTheorem) =>
wenzelm@21940
   587
            with_displaywrap (idvalue ObjTheorem name)
wenzelm@21940
   588
                             (fn ()=>pthm (topthy()) name)
wenzelm@21940
   589
          | (_, ot) => error ("Cannot show objects of type "^(PgipTypes.name_of_objtype ot))
aspinall@21637
   590
    end
aspinall@21637
   591
aspinall@21867
   592
(*** Inspecting state ***)
aspinall@21867
   593
wenzelm@21940
   594
(* The file which is currently being processed interactively.
aspinall@21637
   595
   In the pre-PGIP code, this was informed to Isabelle and the theory loader
aspinall@21637
   596
   on completion, but that allows for circularity in case we read
aspinall@21637
   597
   ourselves.  So PGIP opens the filename at the start of a script.
aspinall@21637
   598
   We ought to prevent problems by modifying the theory loader to know
wenzelm@21940
   599
   about this special status, but for now we just keep a local reference.
wenzelm@21940
   600
*)
aspinall@21637
   601
aspinall@21637
   602
val currently_open_file = ref (NONE : pgipurl option)
aspinall@21637
   603
wenzelm@21940
   604
fun askguise vs =
aspinall@21637
   605
    (* The "guise" is the PGIP abstraction of the prover's state.
aspinall@21637
   606
       The <informguise> message is merely used for consistency checking. *)
wenzelm@21940
   607
    let
wenzelm@21940
   608
        val openfile = !currently_open_file
aspinall@21637
   609
wenzelm@21940
   610
        val topthy = Toplevel.theory_of o Toplevel.get_state
wenzelm@21940
   611
        val topthy_name = Context.theory_name o topthy
aspinall@21637
   612
wenzelm@21940
   613
        val opentheory = SOME (topthy_name()) handle Toplevel.UNDEF => NONE
aspinall@21637
   614
wenzelm@21940
   615
        fun topproofpos () = try Toplevel.proof_position_of (Isar.state ());
wenzelm@21940
   616
        val openproofpos = topproofpos()
aspinall@21637
   617
    in
aspinall@21637
   618
        issue_pgip (Informguise { file = openfile,
wenzelm@21940
   619
                                  theory = opentheory,
wenzelm@21940
   620
                                  (* would be nice to get thm name... *)
wenzelm@21940
   621
                                  theorem = NONE,
wenzelm@21940
   622
                                  proofpos = openproofpos })
aspinall@21637
   623
    end
aspinall@21637
   624
haftmann@21902
   625
fun parsescript (Parsescript vs) =
aspinall@21637
   626
    let
wenzelm@21940
   627
        val text = #text vs
wenzelm@21940
   628
        val systemdata = #systemdata vs
wenzelm@21940
   629
        val location = #location vs   (* TODO: extract position *)
aspinall@21637
   630
aspinall@21867
   631
        val _ = start_delay_msgs ()   (* gather parsing errs/warns *)
aspinall@21867
   632
        val doc = PgipParser.pgip_parser text
aspinall@21637
   633
        val errs = end_delayed_msgs ()
aspinall@21637
   634
wenzelm@21940
   635
        val sysattrs = PgipTypes.opt_attr "systemdata" systemdata
wenzelm@21940
   636
        val locattrs = PgipTypes.attrs_of_location location
aspinall@21637
   637
     in
aspinall@21637
   638
        issue_pgip (Parseresult { attrs= sysattrs@locattrs,
wenzelm@21940
   639
                                  doc = doc,
wenzelm@21940
   640
                                  errs = map PgipOutput.output errs })
aspinall@21637
   641
    end
aspinall@21637
   642
aspinall@21637
   643
fun showproofstate vs = isarcmd "pr"
aspinall@21637
   644
wenzelm@21969
   645
fun showctxt vs = isarcmd "print_context"
aspinall@21637
   646
haftmann@21902
   647
fun searchtheorems (Searchtheorems vs) =
wenzelm@21940
   648
    let
wenzelm@21940
   649
        val arg = #arg vs
aspinall@21637
   650
    in
wenzelm@21969
   651
        isarcmd ("find_theorems " ^ arg)
aspinall@21637
   652
    end
aspinall@21637
   653
wenzelm@21940
   654
fun setlinewidth (Setlinewidth vs) =
wenzelm@21940
   655
    let
wenzelm@21940
   656
        val width = #width vs
aspinall@21637
   657
    in
wenzelm@21940
   658
        isarcmd ("pretty_setmargin " ^ Int.toString width) (* FIXME: conversion back/forth! *)
aspinall@21637
   659
    end
aspinall@21637
   660
haftmann@21902
   661
fun viewdoc (Viewdoc vs) =
wenzelm@21940
   662
    let
wenzelm@21940
   663
        val arg = #arg vs
wenzelm@21940
   664
    in
wenzelm@21940
   665
        isarcmd ("print_" ^ arg)   (* FIXME: isatool doc?.  Return URLs, maybe? *)
aspinall@21637
   666
    end
aspinall@21637
   667
aspinall@21867
   668
(*** Theory ***)
aspinall@21867
   669
haftmann@21902
   670
fun doitem (Doitem vs) =
aspinall@21637
   671
    let
wenzelm@21940
   672
        val text = #text vs
aspinall@21637
   673
    in
wenzelm@21940
   674
        isarcmd text
aspinall@21637
   675
    end
aspinall@21637
   676
aspinall@21637
   677
fun undoitem vs =
aspinall@21637
   678
    isarcmd "ProofGeneral.undo"
aspinall@21637
   679
aspinall@21637
   680
fun redoitem vs =
aspinall@21637
   681
    isarcmd "ProofGeneral.redo"
aspinall@21637
   682
wenzelm@21940
   683
fun aborttheory vs =
aspinall@21637
   684
    isarcmd "init_toplevel"
aspinall@21637
   685
haftmann@21902
   686
fun retracttheory (Retracttheory vs) =
wenzelm@21940
   687
    let
wenzelm@21940
   688
        val thyname = #thyname vs
aspinall@21637
   689
    in
wenzelm@21940
   690
        isarcmd ("kill_thy " ^ quote thyname)
aspinall@21637
   691
    end
aspinall@21637
   692
aspinall@21867
   693
aspinall@21867
   694
(*** Files ***)
aspinall@21867
   695
aspinall@21867
   696
(* Path management: we allow theory files to have dependencies in
aspinall@21867
   697
   their own directory, but when we change directory for a new file we
aspinall@21867
   698
   remove the path.  Leaving it there can cause confusion with
aspinall@21867
   699
   difference in batch mode.
wenzelm@21940
   700
   NB: PGIP does not assume that the prover has a load path.
aspinall@21867
   701
*)
aspinall@21867
   702
aspinall@21867
   703
local
aspinall@21867
   704
    val current_working_dir = ref (NONE : string option)
aspinall@21867
   705
in
wenzelm@21940
   706
fun changecwd_dir newdirpath =
wenzelm@21940
   707
   let
aspinall@21867
   708
       val newdir = File.platform_path newdirpath
wenzelm@21940
   709
   in
aspinall@21867
   710
       (case (!current_working_dir) of
aspinall@21867
   711
            NONE => ()
aspinall@21867
   712
          | SOME dir => ThyLoad.del_path dir;
aspinall@21867
   713
        ThyLoad.add_path newdir;
aspinall@21867
   714
        current_working_dir := SOME newdir)
aspinall@21867
   715
   end
aspinall@21867
   716
end
aspinall@21867
   717
wenzelm@21940
   718
fun changecwd (Changecwd vs) =
wenzelm@21940
   719
    let
wenzelm@21940
   720
        val url = #url vs
wenzelm@21940
   721
        val newdir = PgipTypes.path_of_pgipurl url
aspinall@21867
   722
    in
wenzelm@21940
   723
        changecwd_dir url
aspinall@21867
   724
    end
aspinall@21867
   725
haftmann@21902
   726
fun openfile (Openfile vs) =
wenzelm@21940
   727
  let
aspinall@21867
   728
      val url = #url vs
aspinall@21867
   729
      val filepath = PgipTypes.path_of_pgipurl url
aspinall@21867
   730
      val filedir = Path.dir filepath
aspinall@21867
   731
      val thy_name = Path.implode o #1 o Path.split_ext o Path.base
aspinall@21867
   732
      val openfile_retract = Output.no_warnings (ThyInfo.if_known_thy ThyInfo.remove_thy) o thy_name;
aspinall@21867
   733
  in
aspinall@21867
   734
      case !currently_open_file of
aspinall@21867
   735
          SOME f => raise PGIP ("<openfile> when a file is already open! ")
aspinall@21867
   736
        | NONE => (openfile_retract filepath;
wenzelm@21940
   737
                   changecwd_dir filedir;
wenzelm@21940
   738
                   currently_open_file := SOME url)
aspinall@21867
   739
  end
aspinall@21867
   740
aspinall@21867
   741
fun closefile vs =
aspinall@21867
   742
    case !currently_open_file of
wenzelm@21940
   743
        SOME f => (proper_inform_file_processed (File.platform_path f)
wenzelm@21940
   744
                                                (Isar.state());
aspinall@21867
   745
                   currently_open_file := NONE)
aspinall@21867
   746
      | NONE => raise PGIP ("<closefile> when no file is open!")
aspinall@21867
   747
wenzelm@21940
   748
fun loadfile (Loadfile vs) =
wenzelm@21940
   749
    let
wenzelm@21940
   750
        val url = #url vs
wenzelm@21940
   751
    in
wenzelm@21940
   752
        case !currently_open_file of
aspinall@21637
   753
            SOME f => raise PGIP ("<loadfile> when a file is open!")
aspinall@21637
   754
          | NONE => use_thy_or_ml_file (File.platform_path url)
aspinall@21637
   755
    end
aspinall@21637
   756
aspinall@21637
   757
fun abortfile vs =
aspinall@21637
   758
    case !currently_open_file of
aspinall@21637
   759
        SOME f => (isarcmd "init_toplevel";
wenzelm@21940
   760
                   currently_open_file := NONE)
aspinall@21637
   761
      | NONE => raise PGIP ("<abortfile> when no file is open!")
aspinall@21637
   762
wenzelm@21940
   763
fun retractfile (Retractfile vs) =
wenzelm@21940
   764
    let
wenzelm@21940
   765
        val url = #url vs
aspinall@21637
   766
    in
wenzelm@21940
   767
        case !currently_open_file of
aspinall@21637
   768
            SOME f => raise PGIP ("<retractfile> when a file is open!")
aspinall@21637
   769
          | NONE => inform_file_retracted (File.platform_path url)
aspinall@21637
   770
    end
aspinall@21637
   771
aspinall@21637
   772
aspinall@21867
   773
(*** System ***)
aspinall@21637
   774
haftmann@21902
   775
fun systemcmd (Systemcmd vs) =
wenzelm@21940
   776
  let
aspinall@21637
   777
      val arg = #arg vs
aspinall@21637
   778
  in
aspinall@21637
   779
      isarcmd arg
aspinall@21637
   780
  end
aspinall@21637
   781
aspinall@21637
   782
exception PGIP_QUIT;
aspinall@21637
   783
fun quitpgip vs = raise PGIP_QUIT
aspinall@21637
   784
haftmann@21902
   785
fun process_input inp = case inp
haftmann@21902
   786
 of Pgip.Askpgip _          => askpgip inp
haftmann@21902
   787
  | Pgip.Askpgml _          => askpgml inp
wenzelm@21940
   788
  | Pgip.Askprefs _         => askprefs inp
haftmann@21902
   789
  | Pgip.Askconfig _        => askconfig inp
haftmann@21902
   790
  | Pgip.Getpref _          => getpref inp
haftmann@21902
   791
  | Pgip.Setpref _          => setpref inp
haftmann@21902
   792
  | Pgip.Proverinit _       => proverinit inp
haftmann@21902
   793
  | Pgip.Proverexit _       => proverexit inp
haftmann@21902
   794
  | Pgip.Startquiet _       => startquiet inp
haftmann@21902
   795
  | Pgip.Stopquiet _        => stopquiet inp
haftmann@21902
   796
  | Pgip.Pgmlsymbolson _    => pgmlsymbolson inp
haftmann@21902
   797
  | Pgip.Pgmlsymbolsoff _   => pgmlsymbolsoff inp
haftmann@21902
   798
  | Pgip.Dostep _           => dostep inp
haftmann@21902
   799
  | Pgip.Undostep _         => undostep inp
haftmann@21902
   800
  | Pgip.Redostep _         => redostep inp
haftmann@21902
   801
  | Pgip.Forget _           => error "<forget> not implemented"
haftmann@21902
   802
  | Pgip.Restoregoal _      => error "<restoregoal> not implemented"
haftmann@21902
   803
  | Pgip.Abortgoal _        => abortgoal inp
haftmann@21902
   804
  | Pgip.Askids _           => askids inp
haftmann@21902
   805
  | Pgip.Showid _           => showid inp
haftmann@21902
   806
  | Pgip.Askguise _         => askguise inp
haftmann@21902
   807
  | Pgip.Parsescript _      => parsescript inp
haftmann@21902
   808
  | Pgip.Showproofstate _   => showproofstate inp
haftmann@21902
   809
  | Pgip.Showctxt _         => showctxt inp
haftmann@21902
   810
  | Pgip.Searchtheorems _   => searchtheorems inp
haftmann@21902
   811
  | Pgip.Setlinewidth _     => setlinewidth inp
haftmann@21902
   812
  | Pgip.Viewdoc _          => viewdoc inp
haftmann@21902
   813
  | Pgip.Doitem _           => doitem inp
haftmann@21902
   814
  | Pgip.Undoitem _         => undoitem inp
haftmann@21902
   815
  | Pgip.Redoitem _         => redoitem inp
haftmann@21902
   816
  | Pgip.Aborttheory _      => aborttheory inp
haftmann@21902
   817
  | Pgip.Retracttheory _    => retracttheory inp
haftmann@21902
   818
  | Pgip.Loadfile _         => loadfile inp
haftmann@21902
   819
  | Pgip.Openfile _         => openfile inp
haftmann@21902
   820
  | Pgip.Closefile _        => closefile inp
haftmann@21902
   821
  | Pgip.Abortfile _        => abortfile inp
haftmann@21902
   822
  | Pgip.Retractfile _      => retractfile inp
haftmann@21902
   823
  | Pgip.Changecwd _        => changecwd inp
haftmann@21902
   824
  | Pgip.Systemcmd _        => systemcmd inp
haftmann@21902
   825
  | Pgip.Quitpgip _         => quitpgip inp
aspinall@21637
   826
aspinall@21637
   827
wenzelm@21940
   828
fun process_pgip_element pgipxml =
aspinall@21637
   829
    case pgipxml of
wenzelm@21969
   830
        xml as (XML.Elem elem) =>
wenzelm@21940
   831
        (case Pgip.input elem of
wenzelm@21940
   832
             NONE => warning ("Unrecognized PGIP command, ignored: \n" ^
wenzelm@21940
   833
                              (XML.string_of_tree xml))
wenzelm@21940
   834
           | SOME inp => (process_input inp)) (* errors later; packet discarded *)
wenzelm@21969
   835
      | XML.Text t => ignored_text_warning t
wenzelm@21969
   836
      | XML.Rawtext t => ignored_text_warning t
aspinall@21637
   837
and ignored_text_warning t =
wenzelm@21940
   838
    if size (Symbol.strip_blanks t) > 0 then
wenzelm@21940
   839
           warning ("Ignored text in PGIP packet: \n" ^ t)
aspinall@21637
   840
    else ()
aspinall@21637
   841
aspinall@21637
   842
fun process_pgip_tree xml =
aspinall@21637
   843
    (pgip_refid := NONE;
aspinall@21637
   844
     pgip_refseq := NONE;
aspinall@21637
   845
     (case xml of
aspinall@21637
   846
          XML.Elem ("pgip", attrs, pgips) =>
aspinall@21637
   847
          (let
aspinall@21637
   848
               val class = PgipTypes.get_attr "class" attrs
aspinall@21637
   849
               val dest  = PgipTypes.get_attr_opt "destid" attrs
wenzelm@21940
   850
               val seq = PgipTypes.read_pgipnat (PgipTypes.get_attr "seq" attrs)
aspinall@21637
   851
               (* Respond to prover broadcasts, or messages for us. Ignore rest *)
wenzelm@21940
   852
               val processit =
wenzelm@21940
   853
                   case dest of
aspinall@21637
   854
                       NONE =>    class = "pa"
wenzelm@21940
   855
                     | SOME id => matching_pgip_id id
wenzelm@21940
   856
           in if processit then
wenzelm@21940
   857
                  (pgip_refid :=  PgipTypes.get_attr_opt "id" attrs;
wenzelm@21940
   858
                   pgip_refseq := SOME seq;
wenzelm@21940
   859
                   List.app process_pgip_element pgips;
wenzelm@21940
   860
                   (* return true to indicate <ready/> *)
wenzelm@21940
   861
                   true)
wenzelm@21940
   862
              else
wenzelm@21940
   863
                  (* no response to ignored messages. *)
wenzelm@21940
   864
                  false
aspinall@21637
   865
           end)
aspinall@21637
   866
        | _ => raise PGIP "Invalid PGIP packet received")
aspinall@21637
   867
     handle PGIP msg =>
aspinall@21637
   868
            (Output.error_msg ((msg ^ "\nPGIP error occured in XML text below:\n") ^
wenzelm@21940
   869
                               (XML.string_of_tree xml));
wenzelm@21940
   870
             true))
aspinall@21637
   871
aspinall@21649
   872
(* External input *)
aspinall@21649
   873
aspinall@21649
   874
val process_pgip_plain = K () o process_pgip_tree o XML.tree_of_string
aspinall@21637
   875
aspinall@21637
   876
end
aspinall@21637
   877
aspinall@21637
   878
aspinall@21637
   879
(* PGIP loop: process PGIP input only *)
aspinall@21637
   880
aspinall@21637
   881
local
aspinall@21637
   882
aspinall@21637
   883
exception XML_PARSE
aspinall@21637
   884
aspinall@21637
   885
fun loop ready src =
aspinall@21637
   886
    let
aspinall@21637
   887
        val _ = if ready then issue_pgip (Ready ()) else ()
wenzelm@21969
   888
        val pgipo =
wenzelm@21969
   889
          (case try Source.get_single src of
wenzelm@21969
   890
            SOME pgipo => pgipo
wenzelm@21969
   891
          | NONE => raise XML_PARSE)
aspinall@21637
   892
    in
aspinall@21637
   893
        case pgipo of
aspinall@21637
   894
             NONE  => ()
aspinall@21637
   895
           | SOME (pgip,src') =>
aspinall@21637
   896
             let
wenzelm@21940
   897
                 val ready' = (process_pgip_tree pgip)
wenzelm@21940
   898
                                handle e => (handler (e,SOME src'); true)
aspinall@21637
   899
             in
aspinall@21637
   900
                 loop ready' src'
aspinall@21637
   901
             end
aspinall@21637
   902
    end handle e => handler (e,SOME src)  (* error in XML parse or Ready issue *)
aspinall@21637
   903
aspinall@21637
   904
and handler (e,srco) =
aspinall@21637
   905
    case (e,srco) of
aspinall@21637
   906
        (XML_PARSE,SOME src) =>
aspinall@21637
   907
        Output.panic "Invalid XML input, aborting"
aspinall@21637
   908
      | (PGIP_QUIT,_) => ()
wenzelm@21940
   909
      | (Interrupt,SOME src) =>
wenzelm@21940
   910
        (Output.error_msg "Interrupt during PGIP processing"; loop true src)
wenzelm@21940
   911
      | (Toplevel.UNDEF,SOME src) =>
wenzelm@21940
   912
        (Output.error_msg "No working context defined"; loop true src)
wenzelm@21940
   913
      | (e,SOME src) =>
wenzelm@21940
   914
        (Output.error_msg (Toplevel.exn_message e); loop true src)
aspinall@21637
   915
      | (_,NONE) => ()
aspinall@21637
   916
in
aspinall@21637
   917
  (* TODO: add socket interface *)
aspinall@21637
   918
aspinall@21637
   919
  val xmlP = XML.scan_comment_whspc |-- XML.parse_elem >> single
aspinall@21637
   920
aspinall@21637
   921
  val tty_src = Source.set_prompt "" (Source.source Symbol.stopper xmlP NONE Source.tty)
aspinall@21637
   922
aspinall@21637
   923
  fun pgip_toplevel x = loop true x
aspinall@21637
   924
end
aspinall@21637
   925
aspinall@21637
   926
wenzelm@21940
   927
(* additional outer syntax for Isar *)
aspinall@21637
   928
(* da: TODO: perhaps we can drop this superfluous syntax now??
aspinall@21637
   929
   Seems cleaner to support the operations directly above in the PGIP actions.
aspinall@21637
   930
 *)
aspinall@21637
   931
aspinall@21637
   932
local structure P = OuterParse and K = OuterKeyword in
aspinall@21637
   933
aspinall@21637
   934
val undoP = (*undo without output*)
aspinall@21637
   935
  OuterSyntax.improper_command "ProofGeneral.undo" "(internal)" K.control
aspinall@21637
   936
    (Scan.succeed (Toplevel.no_timing o IsarCmd.undo));
aspinall@21637
   937
aspinall@21637
   938
val redoP = (*redo without output*)
aspinall@21637
   939
  OuterSyntax.improper_command "ProofGeneral.redo" "(internal)" K.control
aspinall@21637
   940
    (Scan.succeed (Toplevel.no_timing o IsarCmd.redo));
aspinall@21637
   941
aspinall@21637
   942
(* ProofGeneral.kill_proof still used above *)
aspinall@21637
   943
val kill_proofP =
aspinall@21637
   944
  OuterSyntax.improper_command "ProofGeneral.kill_proof" "(internal)" K.control
aspinall@21637
   945
    (Scan.succeed (Toplevel.no_timing o IsarCmd.kill_proof_notify tell_clear_goals));
aspinall@21637
   946
aspinall@21637
   947
(* FIXME: Not quite same as commands used above *)
aspinall@21637
   948
val inform_file_processedP =
aspinall@21637
   949
  OuterSyntax.improper_command "ProofGeneral.inform_file_processed" "(internal)" K.control
aspinall@21637
   950
    (P.name >> (fn file => Toplevel.no_timing o
wenzelm@21959
   951
      Toplevel.init_empty (vacuous_inform_file_processed file) o
aspinall@21637
   952
      Toplevel.kill o
wenzelm@21959
   953
      Toplevel.init_empty (proper_inform_file_processed file)));
aspinall@21637
   954
aspinall@21637
   955
val inform_file_retractedP =
aspinall@21637
   956
  OuterSyntax.improper_command "ProofGeneral.inform_file_retracted" "(internal)" K.control
aspinall@21637
   957
    (P.name >> (Toplevel.no_timing oo
aspinall@21637
   958
      (fn file => Toplevel.imperative (fn () => inform_file_retracted file))));
aspinall@21637
   959
aspinall@21637
   960
(* This one can actually be used for Daniel's interface scripting idea: generically!! *)
aspinall@21637
   961
val process_pgipP =
aspinall@21637
   962
  OuterSyntax.improper_command "ProofGeneral.process_pgip" "(internal)" K.control
aspinall@21637
   963
    (P.text >> (Toplevel.no_timing oo
aspinall@21649
   964
      (fn txt => Toplevel.imperative (fn () => process_pgip_plain txt))));
aspinall@21637
   965
aspinall@21637
   966
fun init_outer_syntax () = OuterSyntax.add_parsers
wenzelm@21949
   967
 [undoP, redoP, kill_proofP, inform_file_processedP, inform_file_retractedP, process_pgipP];
aspinall@21637
   968
aspinall@21637
   969
end;
aspinall@21637
   970
aspinall@21637
   971
aspinall@21637
   972
(* init *)
aspinall@21637
   973
aspinall@21637
   974
val initialized = ref false;
aspinall@21637
   975
wenzelm@21969
   976
fun init_pgip false =
wenzelm@21969
   977
      Output.panic "No Proof General interface support for Isabelle/classic mode."
wenzelm@21969
   978
  | init_pgip true =
wenzelm@21969
   979
      (! initialized orelse
wenzelm@21969
   980
        (setmp warning_fn (K ()) init_outer_syntax ();
wenzelm@21969
   981
          setup_xsymbols_output ();
wenzelm@21969
   982
          setup_pgml_output ();
wenzelm@21969
   983
          setup_messages ();
wenzelm@21969
   984
          setup_state ();
wenzelm@21969
   985
          setup_thy_loader ();
wenzelm@21969
   986
          setup_present_hook ();
wenzelm@21969
   987
          init_pgip_session_id ();
wenzelm@21969
   988
          welcome ();
wenzelm@21969
   989
          set initialized);
wenzelm@21969
   990
        sync_thy_loader ();
wenzelm@21969
   991
       change print_mode (cons proof_generalN o remove (op =) proof_generalN);
wenzelm@21969
   992
       change print_mode (append [pgmlN, pgmlatomsN] o subtract (op =) [pgmlN, pgmlatomsN]);
wenzelm@21969
   993
       pgip_toplevel tty_src);
aspinall@21637
   994
aspinall@21649
   995
aspinall@21649
   996
aspinall@21649
   997
(** Out-of-loop PGIP commands (for Emacs hybrid mode) **)
aspinall@21649
   998
aspinall@21649
   999
local
aspinall@21649
  1000
    val pgip_output_channel = ref writeln_default
aspinall@21649
  1001
in
aspinall@21649
  1002
aspinall@21649
  1003
(* Set recipient for PGIP results *)
aspinall@21649
  1004
fun init_pgip_channel writefn =
wenzelm@21940
  1005
    (init_pgip_session_id();
wenzelm@21940
  1006
     pgip_output_channel := writefn)
aspinall@21649
  1007
wenzelm@21940
  1008
(* Process a PGIP command.
wenzelm@21940
  1009
   This works for preferences but not generally guaranteed
aspinall@21649
  1010
   because we haven't done full setup here (e.g., no pgml mode)  *)
aspinall@21649
  1011
fun process_pgip str =
aspinall@21649
  1012
     setmp output_xml_fn (!pgip_output_channel) process_pgip_plain str
aspinall@21649
  1013
aspinall@21649
  1014
end
aspinall@21637
  1015
aspinall@21637
  1016
end;
aspinall@21637
  1017