src/Pure/ProofGeneral/proof_general_pgip.ML
author wenzelm
Mon, 14 Jul 2008 11:19:42 +0200
changeset 27565 4bb03d4509e2
parent 27353 71c4dd53d4cb
child 27578 75945c883672
permissions -rw-r--r--
command 'redo' no longer available;
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@22042
    16
aspinall@23435
    17
  (* More message functions... *)
aspinall@23435
    18
  val nonfatal_error : string -> unit     (* recoverable (batch) error: carry on scripting *)
wenzelm@22228
    19
  val log_msg : string -> unit            (* for internal log messages *)
aspinall@23759
    20
  val error_with_pos : PgipTypes.displayarea -> PgipTypes.fatality -> Position.T -> string -> unit
aspinall@22159
    21
aspinall@22163
    22
  val get_currently_open_file : unit -> Path.T option  (* interface focus *)
aspinall@21637
    23
end
aspinall@21637
    24
aspinall@21637
    25
structure ProofGeneralPgip : PROOF_GENERAL_PGIP  =
aspinall@21637
    26
struct
aspinall@21637
    27
aspinall@21637
    28
open Pgip;
aspinall@21637
    29
wenzelm@21949
    30
wenzelm@23641
    31
(** print mode **)
aspinall@21637
    32
aspinall@22408
    33
val proof_generalN = "ProofGeneral";
aspinall@22408
    34
val pgmlsymbols_flag = ref true;
aspinall@21637
    35
wenzelm@23641
    36
wenzelm@23641
    37
(* symbol output *)
wenzelm@23641
    38
aspinall@21637
    39
local
aspinall@21637
    40
aspinall@21637
    41
fun xsym_output "\\" = "\\\\"
aspinall@21637
    42
  | xsym_output s = if Symbol.is_raw s then Symbol.decode_raw s else s;
aspinall@21637
    43
aspinall@21637
    44
fun pgml_sym s =
aspinall@21637
    45
  (case Symbol.decode s of
aspinall@21637
    46
    Symbol.Char s => XML.text s
wenzelm@26706
    47
  | Symbol.Sym sn =>
aspinall@22408
    48
    let val ascii = implode (map xsym_output (Symbol.explode s))
aspinall@22408
    49
    in if !pgmlsymbols_flag then XML.element "sym" [("name", sn)] [XML.text ascii]
aspinall@22408
    50
       else  ascii end
aspinall@22408
    51
  | Symbol.Ctrl sn => XML.element "ctrl" [("name", sn)] [XML.text sn] (* FIXME: no such PGML *)
aspinall@22408
    52
  | Symbol.Raw raw => raw);
aspinall@21637
    53
aspinall@21637
    54
fun pgml_output str =
aspinall@21637
    55
  let val syms = Symbol.explode str
wenzelm@23621
    56
  in (implode (map pgml_sym syms), Symbol.length syms) end;
wenzelm@23621
    57
aspinall@21637
    58
in
aspinall@21637
    59
aspinall@22408
    60
fun setup_proofgeneral_output () =
wenzelm@23641
    61
  Output.add_mode proof_generalN pgml_output Symbol.encode_raw;
aspinall@21637
    62
aspinall@21637
    63
end;
aspinall@21637
    64
aspinall@21637
    65
wenzelm@23641
    66
(* assembling and issuing PGIP packets *)
aspinall@21637
    67
aspinall@21637
    68
val pgip_refid  = ref NONE: string option ref;
aspinall@21637
    69
val pgip_refseq = ref NONE: int option ref;
aspinall@21637
    70
aspinall@21637
    71
local
aspinall@21637
    72
  val pgip_class  = "pg"
aspinall@21637
    73
  val pgip_tag = "Isabelle/Isar"
aspinall@21637
    74
  val pgip_id = ref ""
aspinall@21637
    75
  val pgip_seq = ref 0
aspinall@21637
    76
  fun pgip_serial () = inc pgip_seq
aspinall@21637
    77
aspinall@21637
    78
  fun assemble_pgips pgips =
wenzelm@21940
    79
    Pgip { tag = SOME pgip_tag,
wenzelm@21940
    80
           class = pgip_class,
wenzelm@21940
    81
           seq = pgip_serial(),
wenzelm@21940
    82
           id = !pgip_id,
wenzelm@21940
    83
           destid = !pgip_refid,
wenzelm@21940
    84
           (* destid=refid since Isabelle only communicates back to sender *)
wenzelm@21940
    85
           refid  = !pgip_refid,
wenzelm@21940
    86
           refseq = !pgip_refseq,
wenzelm@21940
    87
           content = pgips }
aspinall@21637
    88
in
aspinall@21637
    89
aspinall@21637
    90
fun init_pgip_session_id () =
aspinall@21637
    91
    pgip_id := getenv "HOSTNAME" ^ "/" ^ getenv "USER" ^ "/" ^
aspinall@21637
    92
               getenv "ISABELLE_PID" ^ "/" ^ Time.toString (Time.now ())
aspinall@21637
    93
aspinall@21637
    94
fun matching_pgip_id id = (id = !pgip_id)
aspinall@21637
    95
wenzelm@22590
    96
val output_xml_fn = ref Output.writeln_default
wenzelm@26541
    97
fun output_xml s = (!output_xml_fn) (XML.string_of s);  (* TODO: string buffer *)
aspinall@21637
    98
wenzelm@23641
    99
val output_pgips =
wenzelm@26541
   100
  XML.string_of o PgipOutput.output o assemble_pgips o map PgipOutput.output;
wenzelm@23641
   101
wenzelm@26706
   102
val output_pgmlterm =
wenzelm@26541
   103
  XML.string_of o Pgml.pgmlterm_to_xml;
aspinall@23759
   104
wenzelm@26706
   105
val output_pgmltext =
wenzelm@26541
   106
  XML.string_of o Pgml.pgml_to_xml;
aspinall@23759
   107
aspinall@23759
   108
wenzelm@21940
   109
fun issue_pgip_rawtext str =
wenzelm@23723
   110
    output_xml (PgipOutput.output (assemble_pgips [XML.Output str]))
aspinall@21637
   111
aspinall@21637
   112
fun issue_pgips pgipops =
aspinall@21637
   113
    output_xml (PgipOutput.output (assemble_pgips (map PgipOutput.output pgipops)));
aspinall@21637
   114
aspinall@21637
   115
fun issue_pgip pgipop =
aspinall@21637
   116
    output_xml (PgipOutput.output (assemble_pgips [PgipOutput.output pgipop]));
aspinall@21637
   117
aspinall@21637
   118
end;
aspinall@21637
   119
aspinall@21637
   120
aspinall@23759
   121
fun pgml area terms = Pgml.Pgml { version=NONE,systemid=NONE,
wenzelm@23801
   122
                                  area=SOME area, content=terms }
wenzelm@23641
   123
aspinall@21637
   124
(** messages and notification **)
aspinall@21637
   125
aspinall@21637
   126
local
aspinall@21637
   127
    val delay_msgs = ref false   (*true: accumulate messages*)
aspinall@21637
   128
    val delayed_msgs = ref []
aspinall@21637
   129
aspinall@21637
   130
    fun queue_or_issue pgip =
wenzelm@21940
   131
        if ! delay_msgs then
wenzelm@21940
   132
            delayed_msgs := pgip :: ! delayed_msgs
wenzelm@21940
   133
        else issue_pgip pgip
aspinall@23759
   134
wenzelm@26706
   135
    fun wrap_pgml area s =
wenzelm@26706
   136
        if String.isPrefix "<pgml" s then
wenzelm@23801
   137
            XML.Output s  (* already pgml outermost *)
wenzelm@26706
   138
        else
wenzelm@23801
   139
            Pgml.pgml_to_xml (pgml area [Pgml.Raw (XML.Output s)]) (* mixed *)
aspinall@23759
   140
aspinall@21637
   141
in
aspinall@23759
   142
    fun normalmsg area s =
wenzelm@21940
   143
        let
aspinall@23759
   144
            val content = wrap_pgml area s
aspinall@23759
   145
            val pgip = Normalresponse { content=[content] }
wenzelm@21940
   146
        in
wenzelm@21940
   147
            queue_or_issue pgip
wenzelm@21940
   148
        end
aspinall@21637
   149
aspinall@23759
   150
    fun errormsg area fatality s =
wenzelm@21940
   151
        let
aspinall@23759
   152
            val content = wrap_pgml area s
aspinall@23759
   153
            val pgip = Errorresponse { fatality=fatality,
aspinall@23759
   154
                                       location=NONE,
aspinall@23759
   155
                                       content=[content] }
wenzelm@21940
   156
        in
wenzelm@21940
   157
            queue_or_issue pgip
wenzelm@21940
   158
        end
aspinall@21637
   159
aspinall@22159
   160
    (* Error responses with useful locations *)
aspinall@23759
   161
    fun error_with_pos area fatality pos s =
aspinall@22159
   162
        let
aspinall@23759
   163
              val content = wrap_pgml area s
aspinall@23759
   164
              val pgip = Errorresponse { fatality=fatality,
aspinall@23759
   165
                                         location=SOME (PgipIsabelle.location_of_position pos),
aspinall@23759
   166
                                         content=[content] }
aspinall@22159
   167
        in
aspinall@22159
   168
            queue_or_issue pgip
aspinall@22159
   169
        end
aspinall@22159
   170
aspinall@21637
   171
    fun start_delay_msgs () = (set delay_msgs; delayed_msgs := [])
aspinall@21637
   172
    fun end_delayed_msgs () = (reset delay_msgs; ! delayed_msgs)
aspinall@21637
   173
end;
aspinall@21637
   174
aspinall@21637
   175
(* NB: all of the standard error/message functions now expect already-escaped text.
aspinall@21637
   176
   FIXME: this may cause us problems now we're generating trees; on the other
wenzelm@21940
   177
   hand the output functions were tuned some time ago, so it ought to be
aspinall@23759
   178
   enough to use XML.Output always above. *)
aspinall@22042
   179
(* NB 2: all of standard functions print strings terminated with new lines, but we don't
wenzelm@22228
   180
   add new lines explicitly in PGIP: they are left implicit.  It means that PGIP messages
aspinall@22042
   181
   can't be written without newlines. *)
aspinall@21637
   182
aspinall@21637
   183
fun setup_messages () =
aspinall@23759
   184
 (Output.writeln_fn := (fn s => normalmsg Message s);
aspinall@23840
   185
  Output.priority_fn := (fn s => normalmsg Status s);
aspinall@23840
   186
  Output.tracing_fn := (fn s => normalmsg  Tracing s);
aspinall@23759
   187
  Output.warning_fn := (fn s => errormsg Message Warning s);
aspinall@23759
   188
  Output.error_fn := (fn s => errormsg Message Fatal s);
aspinall@23759
   189
  Output.debug_fn := (fn s => errormsg Message Debug s));
aspinall@22042
   190
aspinall@23759
   191
fun panic s = (errormsg Message Panic ("## SYSTEM EXIT ##\n" ^ s); exit 1);
aspinall@23759
   192
fun nonfatal_error s = errormsg Message Nonfatal s;
aspinall@23759
   193
fun log_msg s = errormsg Message Log s;
aspinall@21983
   194
aspinall@21637
   195
aspinall@21637
   196
(* immediate messages *)
aspinall@21637
   197
wenzelm@26706
   198
fun tell_clear_goals () =
aspinall@23759
   199
    issue_pgip (Normalresponse { content = [Pgml.pgml_to_xml (pgml Display [])] })
wenzelm@26706
   200
fun tell_clear_response () =
aspinall@23759
   201
    issue_pgip (Normalresponse { content = [Pgml.pgml_to_xml (pgml Message [])] })
aspinall@22042
   202
wenzelm@22228
   203
fun tell_file_loaded completed path   =
aspinall@22042
   204
    issue_pgip (Informfileloaded {url=PgipTypes.pgipurl_of_path path,
wenzelm@22228
   205
                                  completed=completed})
wenzelm@22228
   206
fun tell_file_outdated completed path   =
aspinall@22042
   207
    issue_pgip (Informfileoutdated {url=PgipTypes.pgipurl_of_path path,
wenzelm@22228
   208
                                    completed=completed})
wenzelm@22228
   209
fun tell_file_retracted completed path =
aspinall@22042
   210
    issue_pgip (Informfileretracted {url=PgipTypes.pgipurl_of_path path,
wenzelm@22228
   211
                                     completed=completed})
aspinall@21637
   212
aspinall@21637
   213
wenzelm@23641
   214
(* common markup *)
aspinall@21637
   215
aspinall@21637
   216
local
aspinall@21637
   217
wenzelm@23641
   218
val no_text = chr 0;
wenzelm@23641
   219
aspinall@23759
   220
val pgmlterms_no_text= [Pgml.Raw (XML.Output no_text)]
aspinall@23759
   221
wenzelm@23641
   222
fun split_markup text =
wenzelm@23641
   223
  (case space_explode no_text text of
wenzelm@23641
   224
    [bg, en] => (bg, en)
aspinall@23759
   225
  | _ => (error ("Internal error: failed to split XML markup:\n" ^ text); ("", "")));
wenzelm@23641
   226
aspinall@23759
   227
wenzelm@23801
   228
fun block_markup markup =
wenzelm@26706
   229
    let
wenzelm@26706
   230
      val pgml = Pgml.Box { orient = NONE,
wenzelm@23801
   231
                            indent = Markup.get_int markup Markup.indentN,
wenzelm@23801
   232
                            content = pgmlterms_no_text }
aspinall@23759
   233
    in split_markup (output_pgmlterm pgml) end;
aspinall@23759
   234
wenzelm@23801
   235
fun break_markup markup =
wenzelm@26706
   236
    let
wenzelm@23801
   237
      val pgml = Pgml.Break { mandatory = NONE,
wenzelm@23801
   238
                              indent = Markup.get_int markup Markup.widthN }
aspinall@23759
   239
    in (output_pgmlterm pgml, "") end;
aspinall@23759
   240
wenzelm@23801
   241
fun fbreak_markup markup =
wenzelm@26706
   242
    let
wenzelm@23801
   243
      val pgml = Pgml.Break { mandatory = SOME true, indent = NONE }
aspinall@23759
   244
    in (output_pgmlterm pgml, "") end;
aspinall@23759
   245
aspinall@23759
   246
val state_markup =
aspinall@23759
   247
    split_markup (output_pgmltext (pgml PgipTypes.Display pgmlterms_no_text))
aspinall@21637
   248
wenzelm@26706
   249
val token_markups =
wenzelm@26706
   250
 [Markup.classN, Markup.tfreeN, Markup.tvarN, Markup.freeN,
wenzelm@26706
   251
  Markup.boundN, Markup.varN, Markup.skolemN];
aspinall@21637
   252
aspinall@21637
   253
in
aspinall@21637
   254
wenzelm@26706
   255
val _ = Markup.add_mode proof_generalN (fn (markup as (name, _)) =>
wenzelm@26706
   256
   if name = Markup.blockN then block_markup markup
wenzelm@26706
   257
   else if name = Markup.breakN then break_markup markup
wenzelm@26706
   258
   else if name = Markup.fbreakN then fbreak_markup markup
wenzelm@26706
   259
   else if name = Markup.stateN then state_markup
wenzelm@26706
   260
   else if member (op =) token_markups name then XML.output_markup ("atom", [("kind", name)])
wenzelm@26706
   261
   else ("", ""));
aspinall@21637
   262
aspinall@21637
   263
end;
aspinall@21637
   264
aspinall@21637
   265
aspinall@21637
   266
(* theory loader actions *)
aspinall@21637
   267
aspinall@21637
   268
local
wenzelm@22228
   269
  (* da: TODO: PGIP has a completed flag so the prover can indicate to the
wenzelm@22228
   270
     interface which files are busy performing a particular action.
aspinall@22042
   271
     To make use of this we need to adjust the hook in thy_info.ML
wenzelm@22228
   272
     (may actually be difficult to tell the interface *which* action is in
aspinall@22042
   273
      progress, but we could add a generic "Lock" action which uses
aspinall@22042
   274
      informfileloaded: the broker/UI should not infer too much from incomplete
aspinall@22042
   275
      operations).
wenzelm@22228
   276
   *)
aspinall@21637
   277
fun trace_action action name =
aspinall@21637
   278
  if action = ThyInfo.Update then
wenzelm@22228
   279
    List.app (tell_file_loaded true) (ThyInfo.loaded_files name)
aspinall@22042
   280
  else if action = ThyInfo.Outdate then
aspinall@22042
   281
    List.app (tell_file_outdated true) (ThyInfo.loaded_files name)
aspinall@22042
   282
  else if action = ThyInfo.Remove then
wenzelm@22228
   283
      List.app (tell_file_retracted true) (ThyInfo.loaded_files name)
aspinall@22042
   284
  else ()
aspinall@22042
   285
aspinall@21637
   286
aspinall@21637
   287
in
aspinall@21637
   288
  fun setup_thy_loader () = ThyInfo.add_hook trace_action;
wenzelm@26613
   289
  fun sync_thy_loader () = List.app (trace_action ThyInfo.Update) (ThyInfo.get_names ());
aspinall@21637
   290
end;
aspinall@21637
   291
aspinall@21637
   292
wenzelm@21949
   293
(* get informed about files *)
aspinall@21637
   294
aspinall@22042
   295
val thy_name = Path.implode o #1 o Path.split_ext o Path.base;
aspinall@21637
   296
aspinall@21637
   297
val inform_file_retracted = ThyInfo.if_known_thy ThyInfo.remove_thy o thy_name;
aspinall@21637
   298
val inform_file_processed = ThyInfo.if_known_thy ThyInfo.touch_child_thys o thy_name;
aspinall@21637
   299
aspinall@22042
   300
fun proper_inform_file_processed path state =
aspinall@22042
   301
  let val name = thy_name path in
aspinall@21637
   302
    if Toplevel.is_toplevel state andalso ThyInfo.known_thy name then
aspinall@21637
   303
     (ThyInfo.touch_child_thys name;
wenzelm@24079
   304
      ThyInfo.register_thy name handle ERROR msg =>
wenzelm@23913
   305
       (warning (cat_lines [msg, "Failed to register theory: " ^ quote name]);
aspinall@22042
   306
        tell_file_retracted true (Path.base path)))
aspinall@21637
   307
    else raise Toplevel.UNDEF
aspinall@21637
   308
  end;
aspinall@21637
   309
aspinall@21637
   310
aspinall@21637
   311
(* restart top-level loop (keeps most state information) *)
aspinall@21637
   312
aspinall@21637
   313
val welcome = priority o Session.welcome;
aspinall@21637
   314
aspinall@21637
   315
fun restart () =
aspinall@21637
   316
    (sync_thy_loader ();
aspinall@21637
   317
     tell_clear_goals ();
aspinall@21637
   318
     tell_clear_response ();
aspinall@21637
   319
     welcome ();
aspinall@21637
   320
     raise Toplevel.RESTART)
aspinall@21637
   321
aspinall@21637
   322
aspinall@21637
   323
(* theorem dependency output *)
aspinall@22408
   324
aspinall@22408
   325
val show_theorem_dependencies = ref false;
aspinall@22408
   326
aspinall@21637
   327
local
aspinall@21637
   328
aspinall@21637
   329
val spaces_quote = space_implode " " o map quote;
aspinall@21637
   330
aspinall@21637
   331
fun thm_deps_message (thms, deps) =
wenzelm@21940
   332
    let
wenzelm@21940
   333
        val valuethms = XML.Elem("value",[("name", "thms")],[XML.Text thms])
wenzelm@21940
   334
        val valuedeps = XML.Elem("value",[("name", "deps")],[XML.Text deps])
aspinall@21637
   335
    in
wenzelm@21940
   336
        issue_pgip (Metainforesponse {attrs=[("infotype", "isabelle_theorem_dependencies")],
wenzelm@21940
   337
                                      content=[valuethms,valuedeps]})
aspinall@21637
   338
    end
aspinall@21637
   339
wenzelm@21969
   340
fun tell_thm_deps ths =
aspinall@22408
   341
  if !show_theorem_dependencies then
wenzelm@22228
   342
      let
wenzelm@22228
   343
        val names = map PureThy.get_name_hint (filter PureThy.has_name_hint ths);
wenzelm@22228
   344
        val deps = (Symtab.keys (fold Proofterm.thms_of_proof'
wenzelm@22228
   345
                                        (map Thm.proof_of ths) Symtab.empty))
wenzelm@22228
   346
      in
wenzelm@22228
   347
          if null names orelse null deps then ()
wenzelm@22228
   348
          else thm_deps_message (spaces_quote names, spaces_quote deps)
aspinall@22225
   349
      end
aspinall@22225
   350
  else ()
aspinall@21637
   351
aspinall@21637
   352
in
aspinall@21637
   353
aspinall@21637
   354
fun setup_present_hook () =
aspinall@21637
   355
  Present.add_hook (fn _ => fn res => tell_thm_deps (maps #2 res));
aspinall@21637
   356
aspinall@21637
   357
end;
aspinall@21637
   358
aspinall@21637
   359
(** lexicalstructure element with keywords (PGIP version of elisp keywords file) **)
aspinall@21637
   360
wenzelm@21940
   361
fun lexicalstructure_keywords () =
wenzelm@27353
   362
    let val keywords = OuterKeyword.dest_keywords ()
wenzelm@27353
   363
        val commands = OuterKeyword.dest_commands ()
wenzelm@27353
   364
        fun keyword_elt kind keyword =
wenzelm@27353
   365
            XML.Elem("keyword", [("word", keyword), ("category", kind)], [])
wenzelm@21940
   366
        in
aspinall@21637
   367
            (* Also, note we don't call init_outer_syntax here to add interface commands,
aspinall@21637
   368
            but they should never appear in scripts anyway so it shouldn't matter *)
wenzelm@27353
   369
            Lexicalstructure
wenzelm@27353
   370
              {content = map (keyword_elt "minor") keywords @ map (keyword_elt "major") commands}
aspinall@21637
   371
        end
aspinall@21637
   372
aspinall@21637
   373
(* TODO: we can issue a lexicalstructure/keyword when the syntax gets extended dynamically;
aspinall@21637
   374
   hooks needed in outer_syntax.ML to do that. *)
aspinall@21637
   375
aspinall@21637
   376
aspinall@21637
   377
(* Configuration: GUI config, proverinfo messages *)
aspinall@21637
   378
aspinall@21637
   379
local
aspinall@21637
   380
    val isabellewww = "http://isabelle.in.tum.de/"
aspinall@21637
   381
    val staticconfig = "~~/lib/ProofGeneral/pgip_isar.xml"
wenzelm@21940
   382
    fun orenv v d = case getenv v of "" => d  | s => s
aspinall@21637
   383
    fun config_file()  = orenv "ISABELLE_PGIPCONFIG" staticconfig
aspinall@21637
   384
    fun isabelle_www() = orenv "ISABELLE_HOMEPAGE" isabellewww
aspinall@21637
   385
in
aspinall@21637
   386
fun send_pgip_config () =
aspinall@21637
   387
    let
wenzelm@21858
   388
        val path = Path.explode (config_file())
wenzelm@21940
   389
        val ex = File.exists path
aspinall@21637
   390
wenzelm@21940
   391
        val wwwpage =
wenzelm@21940
   392
            (Url.explode (isabelle_www()))
wenzelm@21969
   393
            handle ERROR _ =>
wenzelm@22699
   394
                   (panic ("Error in URL in environment variable ISABELLE_HOMEPAGE.");
wenzelm@21940
   395
                        Url.explode isabellewww)
wenzelm@21940
   396
wenzelm@21940
   397
        val proverinfo =
aspinall@21637
   398
            Proverinfo { name = "Isabelle",
wenzelm@26109
   399
                         version = Distribution.version,
wenzelm@21940
   400
                         instance = Session.name(),
wenzelm@21940
   401
                         descr = "The Isabelle/Isar theorem prover",
wenzelm@21940
   402
                         url = wwwpage,
wenzelm@21940
   403
                         filenameextns = ".thy;" }
aspinall@21637
   404
    in
wenzelm@21940
   405
        if ex then
wenzelm@21940
   406
            (issue_pgip proverinfo;
wenzelm@21940
   407
             issue_pgip_rawtext (File.read path);
wenzelm@21940
   408
             issue_pgip (lexicalstructure_keywords()))
wenzelm@22699
   409
        else panic ("PGIP configuration file \"" ^ config_file() ^ "\" not found")
aspinall@21637
   410
    end;
aspinall@21637
   411
end
aspinall@21637
   412
aspinall@21637
   413
aspinall@22216
   414
(* Preferences: tweak for PGIP interfaces *)
aspinall@22216
   415
aspinall@22216
   416
val preferences = ref Preferences.preferences;
aspinall@22216
   417
aspinall@22216
   418
fun setup_preferences_tweak() =
aspinall@22216
   419
    preferences :=
aspinall@22216
   420
     (!preferences |> Preferences.set_default ("show-question-marks","false")
aspinall@22408
   421
                   |> Preferences.remove "show-question-marks"    (* we use markup, not ?s *)
wenzelm@22590
   422
                   |> Preferences.remove "theorem-dependencies"   (* set internally *)
wenzelm@22590
   423
                   |> Preferences.remove "full-proofs")           (* set internally *)
wenzelm@22228
   424
aspinall@21637
   425
aspinall@21637
   426
aspinall@21637
   427
(* Sending commands to Isar *)
aspinall@21637
   428
wenzelm@26622
   429
fun isarcmd s = Isar.>>> (OuterSyntax.parse Position.none s);
aspinall@21637
   430
wenzelm@21940
   431
(* TODO:
wenzelm@27565
   432
    - apply a command given a transition function;
aspinall@21885
   433
    - fix position from path of currently open file [line numbers risk garbling though].
aspinall@21885
   434
*)
aspinall@21637
   435
aspinall@21637
   436
(* load an arbitrary file (must be .thy or .ML) *)
aspinall@21637
   437
aspinall@21637
   438
fun use_thy_or_ml_file file =
aspinall@21637
   439
    let
wenzelm@21858
   440
        val (path,extn) = Path.split_ext (Path.explode file)
aspinall@21637
   441
    in
aspinall@21637
   442
        case extn of
wenzelm@21940
   443
            "" => isarcmd ("use_thy " ^ quote (Path.implode path))
wenzelm@21940
   444
          | "thy" => isarcmd ("use_thy " ^ quote (Path.implode path))
aspinall@21637
   445
          | "ML" => isarcmd ("use " ^ quote file)
aspinall@22028
   446
          | other => error ("Don't know how to read a file with extension " ^ quote other)
aspinall@21637
   447
    end
aspinall@21637
   448
aspinall@21637
   449
aspinall@21867
   450
(******* PGIP actions *******)
aspinall@21637
   451
aspinall@21637
   452
wenzelm@21940
   453
(* Responses to each of the PGIP input commands.
aspinall@21637
   454
   These are programmed uniformly for extensibility. *)
aspinall@21637
   455
wenzelm@23834
   456
fun askpgip (Askpgip _) =
aspinall@23435
   457
    (issue_pgip
aspinall@23435
   458
         (Usespgip { version = PgipIsabelle.isabelle_pgip_version_supported,
aspinall@23435
   459
                     pgipelems = PgipIsabelle.accepted_inputs });
aspinall@23435
   460
     send_pgip_config())
aspinall@21637
   461
wenzelm@23834
   462
fun askpgml (Askpgml _) =
aspinall@21637
   463
    issue_pgip
wenzelm@21940
   464
        (Usespgml { version = PgipIsabelle.isabelle_pgml_version_supported })
aspinall@21637
   465
wenzelm@23834
   466
fun askprefs (Askprefs _) =
wenzelm@21940
   467
    let
wenzelm@21940
   468
        fun preference_of {name, descr, default, pgiptype, get, set } =
wenzelm@21940
   469
            { name = name, descr = SOME descr, default = SOME default,
wenzelm@21940
   470
              pgiptype = pgiptype }
aspinall@21637
   471
    in
wenzelm@21940
   472
        List.app (fn (prefcat, prefs) =>
wenzelm@21940
   473
                     issue_pgip (Hasprefs {prefcategory=SOME prefcat,
wenzelm@21940
   474
                                           prefs=map preference_of prefs}))
aspinall@22216
   475
                 (!preferences)
wenzelm@21940
   476
    end
aspinall@21637
   477
wenzelm@23834
   478
fun askconfig (Askconfig _) = () (* TODO: add config response *)
aspinall@21637
   479
aspinall@21637
   480
local
wenzelm@21940
   481
    fun lookuppref pref =
wenzelm@21940
   482
        case AList.lookup (op =)
wenzelm@21940
   483
                          (map (fn p => (#name p,p))
aspinall@22216
   484
                               (maps snd (!preferences))) pref of
wenzelm@21940
   485
            NONE => error ("Unknown prover preference: " ^ quote pref)
wenzelm@21940
   486
          | SOME p => p
aspinall@21637
   487
in
wenzelm@21940
   488
fun setpref (Setpref vs) =
wenzelm@21940
   489
    let
wenzelm@21940
   490
        val name = #name vs
wenzelm@21940
   491
        val value = #value vs
wenzelm@21940
   492
        val set = #set (lookuppref name)
aspinall@21637
   493
    in
wenzelm@21940
   494
        set value
aspinall@21637
   495
    end
aspinall@21637
   496
haftmann@21902
   497
fun getpref (Getpref vs) =
wenzelm@21940
   498
    let
wenzelm@21940
   499
        val name = #name vs
wenzelm@21940
   500
        val get = #get (lookuppref name)
wenzelm@21940
   501
    in
aspinall@21637
   502
        issue_pgip (Prefval {name=name, value=get ()})
aspinall@21637
   503
    end
aspinall@21637
   504
end
aspinall@21637
   505
wenzelm@23834
   506
fun proverinit _ = restart ()
aspinall@21637
   507
wenzelm@23834
   508
fun proverexit _ = isarcmd "quit"
aspinall@21637
   509
wenzelm@26706
   510
fun set_proverflag_quiet b =
aspinall@22408
   511
    isarcmd (if b then "disable_pr" else "enable_pr")
aspinall@21637
   512
aspinall@22408
   513
fun set_proverflag_pgmlsymbols b =
aspinall@22408
   514
    (pgmlsymbols_flag := b;
wenzelm@24614
   515
      NAMED_CRITICAL "print_mode" (fn () =>
wenzelm@26706
   516
        change print_mode
wenzelm@22590
   517
            (fn mode =>
wenzelm@24614
   518
                remove (op =) Symbol.xsymbolsN mode @ (if b then [Symbol.xsymbolsN] else []))))
aspinall@21637
   519
aspinall@22408
   520
fun set_proverflag_thmdeps b =
aspinall@22408
   521
    (show_theorem_dependencies := b;
wenzelm@25223
   522
     Proofterm.proofs := (if b then 1 else 2))
aspinall@21637
   523
aspinall@22408
   524
fun setproverflag (Setproverflag vs) =
wenzelm@26706
   525
    let
wenzelm@22590
   526
        val flagname = #flagname vs
wenzelm@22590
   527
        val value = #value vs
aspinall@22408
   528
    in
wenzelm@22590
   529
        (case flagname of
wenzelm@22590
   530
             "quiet"            => set_proverflag_quiet value
wenzelm@22590
   531
           | "pgmlsymbols"      => set_proverflag_pgmlsymbols value
wenzelm@26706
   532
           | "metainfo:thmdeps" => set_proverflag_thmdeps value
wenzelm@26706
   533
           | _ => log_msg ("Unrecognised prover control flag: " ^
wenzelm@23801
   534
                           (quote flagname) ^ " ignored."))
wenzelm@26706
   535
    end
aspinall@22408
   536
aspinall@21637
   537
wenzelm@21940
   538
fun dostep (Dostep vs) =
wenzelm@21940
   539
    let
wenzelm@21940
   540
        val text = #text vs
wenzelm@21940
   541
    in
wenzelm@21940
   542
        isarcmd text
aspinall@21637
   543
    end
aspinall@21637
   544
haftmann@21902
   545
fun undostep (Undostep vs) =
wenzelm@21940
   546
    let
wenzelm@21940
   547
        val times = #times vs
wenzelm@21940
   548
    in
wenzelm@21940
   549
        isarcmd ("undos_proof " ^ Int.toString times)
aspinall@21637
   550
    end
aspinall@21637
   551
wenzelm@27565
   552
fun redostep _ = sys_error "redo unavailable"
wenzelm@21940
   553
wenzelm@23834
   554
fun abortgoal _ = isarcmd "kill" (* was: ProofGeneral.kill_proof *)
aspinall@21637
   555
aspinall@21637
   556
aspinall@21867
   557
(*** PGIP identifier tables ***)
aspinall@21867
   558
wenzelm@22228
   559
(* TODO: these ones should be triggered by hooks after a
aspinall@22159
   560
   declaration addition/removal, to be sent automatically. *)
aspinall@21867
   561
aspinall@22159
   562
fun addids t  = issue_pgip (Addids {idtables = [t]})
aspinall@22159
   563
fun delids t  = issue_pgip (Delids {idtables = [t]})
aspinall@21867
   564
wenzelm@27177
   565
wenzelm@27177
   566
local
wenzelm@27177
   567
wenzelm@27177
   568
fun theory_facts name =
wenzelm@27177
   569
  let val thy = ThyInfo.get_theory name
wenzelm@27177
   570
  in (map PureThy.facts_of (Theory.parents_of thy), PureThy.facts_of thy) end;
wenzelm@27177
   571
wenzelm@27177
   572
fun thms_of_thy name = map fst (theory_facts name |-> Facts.extern_static);
wenzelm@27177
   573
fun qualified_thms_of_thy name = map fst (theory_facts name |-> Facts.dest_static);
wenzelm@27177
   574
wenzelm@27177
   575
in
wenzelm@27177
   576
wenzelm@21940
   577
fun askids (Askids vs) =
aspinall@21637
   578
    let
wenzelm@21940
   579
        val url = #url vs            (* ask for identifiers within a file *)
wenzelm@21940
   580
        val thyname = #thyname vs    (* ask for identifiers within a theory *)
wenzelm@21940
   581
        val objtype = #objtype vs    (* ask for identifiers of a particular type *)
aspinall@21867
   582
wenzelm@21940
   583
        fun idtable ty ctx ids = {objtype=ty,context=ctx,ids=ids}
aspinall@21867
   584
wenzelm@22228
   585
        fun setids t = issue_pgip (Setids {idtables = [t]})
aspinall@22159
   586
aspinall@22225
   587
        (* fake one-level nested "subtheories" by picking apart names. *)
wenzelm@22243
   588
        val immed_thms_of_thy = filter_out NameSpace.is_qualified o thms_of_thy
aspinall@22225
   589
        fun thy_prefix s = case space_explode NameSpace.separator s of
wenzelm@22228
   590
                                    x::_::_ => SOME x  (* String.find? *)
wenzelm@22228
   591
                                  | _ => NONE
wenzelm@22228
   592
        fun subthys_of_thy s =
wenzelm@23178
   593
            List.foldl  (fn (NONE,xs) => xs | (SOME x,xs) => insert op= x xs) []
wenzelm@22228
   594
                   (map thy_prefix (thms_of_thy s))
wenzelm@22228
   595
        fun subthms_of_thy thy =
wenzelm@22228
   596
            (case thy_prefix thy of
wenzelm@22228
   597
                 NONE => immed_thms_of_thy thy
wenzelm@22228
   598
               | SOME prf => filter (String.isPrefix (unprefix (prf ^ NameSpace.separator) thy))
wenzelm@22228
   599
                                    (thms_of_thy prf))
wenzelm@26706
   600
    in
wenzelm@21940
   601
        case (thyname,objtype) of
wenzelm@22228
   602
           (NONE, NONE) =>
wenzelm@26613
   603
           setids (idtable ObjFile NONE (ThyInfo.get_names())) (*FIXME: uris*)
wenzelm@22228
   604
         | (NONE, SOME ObjFile) =>
wenzelm@26613
   605
           setids (idtable ObjFile NONE (ThyInfo.get_names())) (*FIXME: uris*)
wenzelm@22228
   606
         | (SOME fi, SOME ObjFile) =>
wenzelm@22228
   607
           setids (idtable ObjTheory (SOME fi) [fi])       (* TODO: check exists *)
aspinall@22225
   608
         | (NONE, SOME ObjTheory) =>
wenzelm@26613
   609
           setids (idtable ObjTheory NONE (ThyInfo.get_names()))
aspinall@22225
   610
         | (SOME thy, SOME ObjTheory) =>
wenzelm@22228
   611
           setids (idtable ObjTheory (SOME thy) (subthys_of_thy thy))
wenzelm@22228
   612
         | (SOME thy, SOME ObjTheorem) =>
wenzelm@22228
   613
           setids (idtable ObjTheorem (SOME thy) (subthms_of_thy thy))
wenzelm@22228
   614
         | (NONE, SOME ObjTheorem) =>
wenzelm@22228
   615
           (* A large query, but not unreasonable. ~5000 results for HOL.*)
wenzelm@22228
   616
           (* Several setids should be allowed, but Eclipse code is currently broken:
wenzelm@23226
   617
              List.app (fn thy => setids (idtable ObjTheorem (SOME thy) (subthms_of_thy thy)))
wenzelm@26613
   618
                         (ThyInfo.get_names()) *)
aspinall@22225
   619
           setids (idtable ObjTheorem NONE (* this one gives ~7000 for HOL *)
wenzelm@26613
   620
                           (maps qualified_thms_of_thy (ThyInfo.get_names())))
aspinall@22225
   621
         | _ => warning ("askids: ignored argument combination")
aspinall@21637
   622
    end
aspinall@21637
   623
wenzelm@27177
   624
end;
wenzelm@27177
   625
aspinall@22159
   626
fun askrefs (Askrefs vs) =
aspinall@22159
   627
    let
aspinall@22159
   628
        val url = #url vs            (* ask for references of a file (i.e. immediate pre-requisites) *)
aspinall@22159
   629
        val thyname = #thyname vs    (* ask for references of a theory (other theories) *)
aspinall@22159
   630
        val objtype = #objtype vs    (* ask for references of a particular type... *)
aspinall@22159
   631
        val name = #name vs          (*   ... with this name *)
aspinall@22159
   632
aspinall@22159
   633
        fun idtable ty ctx ids = {objtype=ty,context=ctx,ids=ids}
aspinall@22159
   634
wenzelm@22228
   635
        val thy_name = Path.implode o #1 o Path.split_ext o Path.base
aspinall@22159
   636
wenzelm@22228
   637
        fun filerefs f =
wenzelm@22228
   638
            let val thy = thy_name f
wenzelm@24189
   639
                val filerefs = #uses (ThyLoad.deps_thy (Path.dir f) thy)
wenzelm@22228
   640
            in
wenzelm@22228
   641
                issue_pgip (Setrefs {url=url, thyname=NONE, objtype=SOME PgipTypes.ObjFile,
wenzelm@22228
   642
                                     name=NONE, idtables=[], fileurls=filerefs})
wenzelm@22228
   643
            end
aspinall@22159
   644
wenzelm@22228
   645
        fun thyrefs thy =
wenzelm@24189
   646
            let val thyrefs = #imports (ThyLoad.deps_thy Path.current thy)
wenzelm@22228
   647
            in
wenzelm@22228
   648
                issue_pgip (Setrefs {url=url, thyname=thyname, objtype=SOME PgipTypes.ObjTheory,
wenzelm@22228
   649
                                     name=NONE, idtables=[{context=NONE, objtype=PgipTypes.ObjTheory,
wenzelm@22228
   650
                                                           ids=thyrefs}], fileurls=[]})
wenzelm@22228
   651
            end
aspinall@22159
   652
wenzelm@22228
   653
        fun thmrefs thmname =
wenzelm@22228
   654
            let
wenzelm@22228
   655
                (* TODO: interim: this is probably not right.
wenzelm@22228
   656
                   What we want is mapping onto simple PGIP name/context model. *)
wenzelm@26603
   657
                val ctx = Toplevel.context_of (Isar.state ()) (* NB: raises UNDEF *)
wenzelm@22228
   658
                val thy = Context.theory_of_proof ctx
wenzelm@26343
   659
                val ths = [PureThy.get_thm thy thmname]
wenzelm@22228
   660
                val deps = filter_out (equal "")
wenzelm@22228
   661
                                      (Symtab.keys (fold Proofterm.thms_of_proof
wenzelm@22228
   662
                                                         (map Thm.proof_of ths) Symtab.empty))
wenzelm@22228
   663
            in
wenzelm@22228
   664
                if null deps then ()
wenzelm@22228
   665
                else issue_pgip (Setrefs {url=url, thyname=thyname, name=name,
wenzelm@22228
   666
                                          objtype=SOME PgipTypes.ObjTheorem,
wenzelm@22228
   667
                                          idtables=[{context=NONE, objtype=PgipTypes.ObjTheorem,
wenzelm@22228
   668
                                                     ids=deps}], fileurls=[]})
wenzelm@22228
   669
            end
aspinall@22159
   670
    in
aspinall@22159
   671
        case (url,thyname,objtype,name) of
wenzelm@22228
   672
            (SOME file, NONE, _, _)  => filerefs file
wenzelm@22228
   673
          | (_,SOME thy,_,_)         => thyrefs thy
wenzelm@22228
   674
          | (_,_,SOME PgipTypes.ObjTheorem,SOME thmname) => thmrefs thmname
aspinall@22159
   675
          | _  => error ("Unimplemented/invalid case of <askrefs>")
aspinall@22159
   676
    end
aspinall@22159
   677
aspinall@22159
   678
aspinall@22159
   679
wenzelm@21940
   680
fun showid (Showid vs) =
aspinall@21637
   681
    let
wenzelm@21940
   682
        val thyname = #thyname vs
wenzelm@21940
   683
        val objtype = #objtype vs
wenzelm@21940
   684
        val name = #name vs
aspinall@22337
   685
wenzelm@26603
   686
        val topthy = Toplevel.theory_of o Isar.state
aspinall@21637
   687
wenzelm@22590
   688
        fun splitthy id =
wenzelm@22590
   689
            let val comps = NameSpace.explode id
wenzelm@22590
   690
            in case comps of
wenzelm@22590
   691
                   (thy::(rest as _::_)) => (ThyInfo.get_theory thy, space_implode "." rest)
wenzelm@22590
   692
                 | [plainid] => (topthy(),plainid)
wenzelm@22590
   693
                 | _ => raise Toplevel.UNDEF (* assert false *)
wenzelm@26706
   694
            end
wenzelm@26706
   695
aspinall@21637
   696
aspinall@22337
   697
        fun idvalue strings =
wenzelm@26706
   698
            issue_pgip (Idvalue { thyname=thyname, objtype=objtype, name=name,
aspinall@23759
   699
                                  text=[XML.Elem("pgml",[],
wenzelm@23723
   700
                                                 map XML.Output strings)] })
aspinall@22337
   701
wenzelm@22590
   702
        fun string_of_thm th = Output.output
wenzelm@22590
   703
                               (Pretty.string_of
wenzelm@22590
   704
                                   (Display.pretty_thm_aux
wenzelm@26939
   705
                                        (Syntax.pp_global (Thm.theory_of_thm th))
wenzelm@22590
   706
                                        false (* quote *)
wenzelm@22590
   707
                                        false (* show hyps *)
wenzelm@22590
   708
                                        [] (* asms *)
wenzelm@22590
   709
                                        th))
aspinall@22337
   710
wenzelm@26343
   711
        fun strings_of_thm (thy, name) = map string_of_thm (PureThy.get_thms thy name)
aspinall@22337
   712
wenzelm@22590
   713
        val string_of_thy = Output.output o
wenzelm@22590
   714
                                Pretty.string_of o (ProofDisplay.pretty_full_theory false)
wenzelm@21940
   715
    in
wenzelm@21940
   716
        case (thyname, objtype) of
aspinall@22337
   717
            (_,ObjTheory) => idvalue [string_of_thy (ThyInfo.get_theory name)]
aspinall@22337
   718
          | (SOME thy, ObjTheorem) => idvalue (strings_of_thm (ThyInfo.get_theory thy, name))
aspinall@22337
   719
          | (NONE, ObjTheorem) => idvalue (strings_of_thm (splitthy name))
wenzelm@21940
   720
          | (_, ot) => error ("Cannot show objects of type "^(PgipTypes.name_of_objtype ot))
aspinall@21637
   721
    end
aspinall@21637
   722
aspinall@21867
   723
(*** Inspecting state ***)
aspinall@21867
   724
wenzelm@21940
   725
(* The file which is currently being processed interactively.
aspinall@21637
   726
   In the pre-PGIP code, this was informed to Isabelle and the theory loader
aspinall@21637
   727
   on completion, but that allows for circularity in case we read
aspinall@21637
   728
   ourselves.  So PGIP opens the filename at the start of a script.
aspinall@21637
   729
   We ought to prevent problems by modifying the theory loader to know
wenzelm@21940
   730
   about this special status, but for now we just keep a local reference.
wenzelm@21940
   731
*)
aspinall@21637
   732
aspinall@21637
   733
val currently_open_file = ref (NONE : pgipurl option)
aspinall@21637
   734
aspinall@22163
   735
fun get_currently_open_file () = ! currently_open_file;
aspinall@22163
   736
wenzelm@23834
   737
fun askguise _ =
aspinall@21637
   738
    (* The "guise" is the PGIP abstraction of the prover's state.
aspinall@21637
   739
       The <informguise> message is merely used for consistency checking. *)
wenzelm@21940
   740
    let
wenzelm@21940
   741
        val openfile = !currently_open_file
aspinall@21637
   742
wenzelm@26603
   743
        val topthy = Toplevel.theory_of o Isar.state
wenzelm@21940
   744
        val topthy_name = Context.theory_name o topthy
aspinall@21637
   745
wenzelm@21940
   746
        val opentheory = SOME (topthy_name()) handle Toplevel.UNDEF => NONE
aspinall@21637
   747
wenzelm@21940
   748
        fun topproofpos () = try Toplevel.proof_position_of (Isar.state ());
wenzelm@21940
   749
        val openproofpos = topproofpos()
aspinall@21637
   750
    in
aspinall@21637
   751
        issue_pgip (Informguise { file = openfile,
wenzelm@21940
   752
                                  theory = opentheory,
wenzelm@21940
   753
                                  (* would be nice to get thm name... *)
wenzelm@21940
   754
                                  theorem = NONE,
wenzelm@21940
   755
                                  proofpos = openproofpos })
aspinall@21637
   756
    end
aspinall@21637
   757
haftmann@21902
   758
fun parsescript (Parsescript vs) =
aspinall@21637
   759
    let
wenzelm@21940
   760
        val text = #text vs
wenzelm@21940
   761
        val systemdata = #systemdata vs
wenzelm@21940
   762
        val location = #location vs   (* TODO: extract position *)
aspinall@21637
   763
aspinall@21867
   764
        val _ = start_delay_msgs ()   (* gather parsing errs/warns *)
wenzelm@25274
   765
		    val doc = PgipParser.pgip_parser Position.none text
aspinall@21637
   766
        val errs = end_delayed_msgs ()
aspinall@21637
   767
wenzelm@21940
   768
        val sysattrs = PgipTypes.opt_attr "systemdata" systemdata
wenzelm@21940
   769
        val locattrs = PgipTypes.attrs_of_location location
aspinall@21637
   770
     in
aspinall@21637
   771
        issue_pgip (Parseresult { attrs= sysattrs@locattrs,
wenzelm@21940
   772
                                  doc = doc,
wenzelm@21940
   773
                                  errs = map PgipOutput.output errs })
aspinall@21637
   774
    end
aspinall@21637
   775
wenzelm@23834
   776
fun showproofstate _ = isarcmd "pr"
aspinall@21637
   777
wenzelm@23834
   778
fun showctxt _ = isarcmd "print_context"
aspinall@21637
   779
haftmann@21902
   780
fun searchtheorems (Searchtheorems vs) =
wenzelm@21940
   781
    let
wenzelm@21940
   782
        val arg = #arg vs
aspinall@21637
   783
    in
wenzelm@21969
   784
        isarcmd ("find_theorems " ^ arg)
aspinall@21637
   785
    end
aspinall@21637
   786
wenzelm@21940
   787
fun setlinewidth (Setlinewidth vs) =
wenzelm@21940
   788
    let
wenzelm@21940
   789
        val width = #width vs
aspinall@21637
   790
    in
wenzelm@21940
   791
        isarcmd ("pretty_setmargin " ^ Int.toString width) (* FIXME: conversion back/forth! *)
aspinall@21637
   792
    end
aspinall@21637
   793
haftmann@21902
   794
fun viewdoc (Viewdoc vs) =
wenzelm@21940
   795
    let
wenzelm@21940
   796
        val arg = #arg vs
wenzelm@21940
   797
    in
wenzelm@21940
   798
        isarcmd ("print_" ^ arg)   (* FIXME: isatool doc?.  Return URLs, maybe? *)
aspinall@21637
   799
    end
aspinall@21637
   800
aspinall@21867
   801
(*** Theory ***)
aspinall@21867
   802
haftmann@21902
   803
fun doitem (Doitem vs) =
aspinall@21637
   804
    let
wenzelm@21940
   805
        val text = #text vs
aspinall@21637
   806
    in
wenzelm@21940
   807
        isarcmd text
aspinall@21637
   808
    end
aspinall@21637
   809
wenzelm@23834
   810
fun undoitem _ =
aspinall@21972
   811
    isarcmd "undo"
aspinall@21637
   812
wenzelm@23834
   813
fun redoitem _ =
aspinall@21972
   814
    isarcmd "redo"
aspinall@21637
   815
wenzelm@23834
   816
fun aborttheory _ =
aspinall@21972
   817
    isarcmd "kill"  (* was: "init_toplevel" *)
aspinall@21637
   818
haftmann@21902
   819
fun retracttheory (Retracttheory vs) =
wenzelm@21940
   820
    let
wenzelm@21940
   821
        val thyname = #thyname vs
aspinall@21637
   822
    in
wenzelm@21940
   823
        isarcmd ("kill_thy " ^ quote thyname)
aspinall@21637
   824
    end
aspinall@21637
   825
aspinall@21867
   826
aspinall@21867
   827
(*** Files ***)
aspinall@21867
   828
aspinall@21867
   829
(* Path management: we allow theory files to have dependencies in
aspinall@21867
   830
   their own directory, but when we change directory for a new file we
aspinall@21867
   831
   remove the path.  Leaving it there can cause confusion with
aspinall@21867
   832
   difference in batch mode.
wenzelm@21940
   833
   NB: PGIP does not assume that the prover has a load path.
aspinall@21867
   834
*)
aspinall@21867
   835
aspinall@21867
   836
local
aspinall@21867
   837
    val current_working_dir = ref (NONE : string option)
aspinall@21867
   838
in
wenzelm@21940
   839
fun changecwd_dir newdirpath =
wenzelm@21940
   840
   let
aspinall@21867
   841
       val newdir = File.platform_path newdirpath
wenzelm@21940
   842
   in
aspinall@21867
   843
       (case (!current_working_dir) of
aspinall@21867
   844
            NONE => ()
aspinall@21867
   845
          | SOME dir => ThyLoad.del_path dir;
aspinall@21867
   846
        ThyLoad.add_path newdir;
aspinall@21867
   847
        current_working_dir := SOME newdir)
aspinall@21867
   848
   end
aspinall@21867
   849
end
aspinall@21867
   850
wenzelm@21940
   851
fun changecwd (Changecwd vs) =
wenzelm@21940
   852
    let
wenzelm@21940
   853
        val url = #url vs
wenzelm@21940
   854
        val newdir = PgipTypes.path_of_pgipurl url
aspinall@21867
   855
    in
wenzelm@21940
   856
        changecwd_dir url
aspinall@21867
   857
    end
aspinall@21867
   858
haftmann@21902
   859
fun openfile (Openfile vs) =
wenzelm@21940
   860
  let
aspinall@21867
   861
      val url = #url vs
aspinall@21867
   862
      val filepath = PgipTypes.path_of_pgipurl url
aspinall@21867
   863
      val filedir = Path.dir filepath
aspinall@21867
   864
      val thy_name = Path.implode o #1 o Path.split_ext o Path.base
aspinall@21867
   865
      val openfile_retract = Output.no_warnings (ThyInfo.if_known_thy ThyInfo.remove_thy) o thy_name;
aspinall@21867
   866
  in
aspinall@21867
   867
      case !currently_open_file of
aspinall@22028
   868
          SOME f => raise PGIP ("<openfile> when a file is already open!\nCurrently open file: " ^
wenzelm@22228
   869
                                PgipTypes.string_of_pgipurl url)
aspinall@21867
   870
        | NONE => (openfile_retract filepath;
wenzelm@21940
   871
                   changecwd_dir filedir;
wenzelm@22228
   872
                   priority ("Working in file: " ^ PgipTypes.string_of_pgipurl url);
wenzelm@21940
   873
                   currently_open_file := SOME url)
aspinall@21867
   874
  end
aspinall@21867
   875
wenzelm@23834
   876
fun closefile _ =
aspinall@21867
   877
    case !currently_open_file of
aspinall@22042
   878
        SOME f => (proper_inform_file_processed f (Isar.state());
wenzelm@22228
   879
                   priority ("Finished working in file: " ^ PgipTypes.string_of_pgipurl f);
aspinall@21867
   880
                   currently_open_file := NONE)
aspinall@21867
   881
      | NONE => raise PGIP ("<closefile> when no file is open!")
aspinall@21867
   882
wenzelm@21940
   883
fun loadfile (Loadfile vs) =
wenzelm@21940
   884
    let
wenzelm@21940
   885
        val url = #url vs
wenzelm@21940
   886
    in
aspinall@22171
   887
        (* da: this doesn't seem to cause a problem, batch loading uses
aspinall@22171
   888
           a different state context.  Of course confusion is still possible,
aspinall@22171
   889
           e.g. file loaded depends on open file which is not yet saved. *)
aspinall@22171
   890
        (* case !currently_open_file of
aspinall@22028
   891
            SOME f => raise PGIP ("<loadfile> when a file is open!\nCurrently open file: " ^
wenzelm@22228
   892
                                  PgipTypes.string_of_pgipurl url)
aspinall@22171
   893
          | NONE => *)
wenzelm@22228
   894
        use_thy_or_ml_file (File.platform_path url)
aspinall@21637
   895
    end
aspinall@21637
   896
wenzelm@23834
   897
fun abortfile _ =
aspinall@21637
   898
    case !currently_open_file of
aspinall@21637
   899
        SOME f => (isarcmd "init_toplevel";
wenzelm@22228
   900
                   priority ("Aborted working in file: " ^
wenzelm@22228
   901
                             PgipTypes.string_of_pgipurl f);
wenzelm@21940
   902
                   currently_open_file := NONE)
aspinall@21637
   903
      | NONE => raise PGIP ("<abortfile> when no file is open!")
aspinall@21637
   904
wenzelm@21940
   905
fun retractfile (Retractfile vs) =
wenzelm@21940
   906
    let
wenzelm@21940
   907
        val url = #url vs
aspinall@21637
   908
    in
wenzelm@21940
   909
        case !currently_open_file of
aspinall@21637
   910
            SOME f => raise PGIP ("<retractfile> when a file is open!")
aspinall@22028
   911
          | NONE => (priority ("Retracting file: " ^ PgipTypes.string_of_pgipurl url);
wenzelm@22228
   912
                     (* TODO: next should be in thy loader, here just for testing *)
wenzelm@22228
   913
                     let
wenzelm@22228
   914
                         val name = thy_name url
wenzelm@22228
   915
                     in List.app (tell_file_retracted false) (ThyInfo.loaded_files name) end;
wenzelm@22228
   916
                     inform_file_retracted url)
aspinall@21637
   917
    end
aspinall@21637
   918
aspinall@21637
   919
aspinall@21867
   920
(*** System ***)
aspinall@21637
   921
haftmann@21902
   922
fun systemcmd (Systemcmd vs) =
wenzelm@21940
   923
  let
aspinall@21637
   924
      val arg = #arg vs
aspinall@21637
   925
  in
aspinall@21637
   926
      isarcmd arg
aspinall@21637
   927
  end
aspinall@21637
   928
aspinall@21637
   929
exception PGIP_QUIT;
wenzelm@23834
   930
fun quitpgip _ = raise PGIP_QUIT
aspinall@21637
   931
haftmann@21902
   932
fun process_input inp = case inp
haftmann@21902
   933
 of Pgip.Askpgip _          => askpgip inp
haftmann@21902
   934
  | Pgip.Askpgml _          => askpgml inp
wenzelm@21940
   935
  | Pgip.Askprefs _         => askprefs inp
haftmann@21902
   936
  | Pgip.Askconfig _        => askconfig inp
haftmann@21902
   937
  | Pgip.Getpref _          => getpref inp
haftmann@21902
   938
  | Pgip.Setpref _          => setpref inp
haftmann@21902
   939
  | Pgip.Proverinit _       => proverinit inp
haftmann@21902
   940
  | Pgip.Proverexit _       => proverexit inp
aspinall@22408
   941
  | Pgip.Setproverflag _    => setproverflag inp
haftmann@21902
   942
  | Pgip.Dostep _           => dostep inp
haftmann@21902
   943
  | Pgip.Undostep _         => undostep inp
haftmann@21902
   944
  | Pgip.Redostep _         => redostep inp
aspinall@23435
   945
  | Pgip.Forget _           => error "<forget> not implemented by Isabelle"
aspinall@23435
   946
  | Pgip.Restoregoal _      => error "<restoregoal> not implemented by Isabelle"
haftmann@21902
   947
  | Pgip.Abortgoal _        => abortgoal inp
haftmann@21902
   948
  | Pgip.Askids _           => askids inp
aspinall@22159
   949
  | Pgip.Askrefs _          => askrefs inp
haftmann@21902
   950
  | Pgip.Showid _           => showid inp
haftmann@21902
   951
  | Pgip.Askguise _         => askguise inp
haftmann@21902
   952
  | Pgip.Parsescript _      => parsescript inp
haftmann@21902
   953
  | Pgip.Showproofstate _   => showproofstate inp
haftmann@21902
   954
  | Pgip.Showctxt _         => showctxt inp
haftmann@21902
   955
  | Pgip.Searchtheorems _   => searchtheorems inp
haftmann@21902
   956
  | Pgip.Setlinewidth _     => setlinewidth inp
haftmann@21902
   957
  | Pgip.Viewdoc _          => viewdoc inp
haftmann@21902
   958
  | Pgip.Doitem _           => doitem inp
haftmann@21902
   959
  | Pgip.Undoitem _         => undoitem inp
haftmann@21902
   960
  | Pgip.Redoitem _         => redoitem inp
haftmann@21902
   961
  | Pgip.Aborttheory _      => aborttheory inp
haftmann@21902
   962
  | Pgip.Retracttheory _    => retracttheory inp
haftmann@21902
   963
  | Pgip.Loadfile _         => loadfile inp
haftmann@21902
   964
  | Pgip.Openfile _         => openfile inp
haftmann@21902
   965
  | Pgip.Closefile _        => closefile inp
haftmann@21902
   966
  | Pgip.Abortfile _        => abortfile inp
haftmann@21902
   967
  | Pgip.Retractfile _      => retractfile inp
haftmann@21902
   968
  | Pgip.Changecwd _        => changecwd inp
haftmann@21902
   969
  | Pgip.Systemcmd _        => systemcmd inp
haftmann@21902
   970
  | Pgip.Quitpgip _         => quitpgip inp
aspinall@21637
   971
aspinall@21637
   972
wenzelm@21940
   973
fun process_pgip_element pgipxml =
aspinall@21637
   974
    case pgipxml of
wenzelm@21969
   975
        xml as (XML.Elem elem) =>
wenzelm@21940
   976
        (case Pgip.input elem of
wenzelm@21940
   977
             NONE => warning ("Unrecognized PGIP command, ignored: \n" ^
wenzelm@26541
   978
                              (XML.string_of xml))
wenzelm@21940
   979
           | SOME inp => (process_input inp)) (* errors later; packet discarded *)
wenzelm@21969
   980
      | XML.Text t => ignored_text_warning t
wenzelm@23723
   981
      | XML.Output t => ignored_text_warning t
aspinall@21637
   982
and ignored_text_warning t =
wenzelm@21940
   983
    if size (Symbol.strip_blanks t) > 0 then
wenzelm@21940
   984
           warning ("Ignored text in PGIP packet: \n" ^ t)
aspinall@21637
   985
    else ()
aspinall@21637
   986
aspinall@21637
   987
fun process_pgip_tree xml =
aspinall@21637
   988
    (pgip_refid := NONE;
aspinall@21637
   989
     pgip_refseq := NONE;
aspinall@21637
   990
     (case xml of
aspinall@21637
   991
          XML.Elem ("pgip", attrs, pgips) =>
aspinall@21637
   992
          (let
aspinall@21637
   993
               val class = PgipTypes.get_attr "class" attrs
aspinall@21637
   994
               val dest  = PgipTypes.get_attr_opt "destid" attrs
wenzelm@21940
   995
               val seq = PgipTypes.read_pgipnat (PgipTypes.get_attr "seq" attrs)
aspinall@21637
   996
               (* Respond to prover broadcasts, or messages for us. Ignore rest *)
wenzelm@21940
   997
               val processit =
wenzelm@21940
   998
                   case dest of
aspinall@21637
   999
                       NONE =>    class = "pa"
wenzelm@21940
  1000
                     | SOME id => matching_pgip_id id
wenzelm@21940
  1001
           in if processit then
wenzelm@21940
  1002
                  (pgip_refid :=  PgipTypes.get_attr_opt "id" attrs;
wenzelm@21940
  1003
                   pgip_refseq := SOME seq;
wenzelm@21940
  1004
                   List.app process_pgip_element pgips;
wenzelm@21940
  1005
                   (* return true to indicate <ready/> *)
wenzelm@21940
  1006
                   true)
wenzelm@21940
  1007
              else
wenzelm@21940
  1008
                  (* no response to ignored messages. *)
wenzelm@21940
  1009
                  false
aspinall@21637
  1010
           end)
aspinall@21637
  1011
        | _ => raise PGIP "Invalid PGIP packet received")
aspinall@21637
  1012
     handle PGIP msg =>
aspinall@21637
  1013
            (Output.error_msg ((msg ^ "\nPGIP error occured in XML text below:\n") ^
wenzelm@26541
  1014
                               (XML.string_of xml));
wenzelm@21940
  1015
             true))
aspinall@21637
  1016
aspinall@21649
  1017
(* External input *)
aspinall@21649
  1018
wenzelm@26541
  1019
val process_pgip_plain = K () o process_pgip_tree o XML.parse
aspinall@21637
  1020
aspinall@21637
  1021
(* PGIP loop: process PGIP input only *)
aspinall@21637
  1022
aspinall@21637
  1023
local
aspinall@21637
  1024
aspinall@21637
  1025
exception XML_PARSE
aspinall@21637
  1026
aspinall@21637
  1027
fun loop ready src =
aspinall@21637
  1028
    let
aspinall@21637
  1029
        val _ = if ready then issue_pgip (Ready ()) else ()
wenzelm@21969
  1030
        val pgipo =
wenzelm@21969
  1031
          (case try Source.get_single src of
wenzelm@21969
  1032
            SOME pgipo => pgipo
wenzelm@21969
  1033
          | NONE => raise XML_PARSE)
aspinall@21637
  1034
    in
aspinall@21637
  1035
        case pgipo of
aspinall@21637
  1036
             NONE  => ()
aspinall@21637
  1037
           | SOME (pgip,src') =>
aspinall@21637
  1038
             let
wenzelm@21940
  1039
                 val ready' = (process_pgip_tree pgip)
aspinall@22337
  1040
                                handle PGIP_QUIT => raise PGIP_QUIT
wenzelm@22590
  1041
                                     | e => (handler (e,SOME src'); true)
aspinall@21637
  1042
             in
aspinall@21637
  1043
                 loop ready' src'
aspinall@21637
  1044
             end
aspinall@21637
  1045
    end handle e => handler (e,SOME src)  (* error in XML parse or Ready issue *)
aspinall@21637
  1046
aspinall@21637
  1047
and handler (e,srco) =
aspinall@21637
  1048
    case (e,srco) of
aspinall@21637
  1049
        (XML_PARSE,SOME src) =>
wenzelm@22699
  1050
        panic "Invalid XML input, aborting" (* TODO: attempt recovery  *)
wenzelm@21940
  1051
      | (Interrupt,SOME src) =>
wenzelm@21940
  1052
        (Output.error_msg "Interrupt during PGIP processing"; loop true src)
wenzelm@21940
  1053
      | (Toplevel.UNDEF,SOME src) =>
wenzelm@21940
  1054
        (Output.error_msg "No working context defined"; loop true src)
wenzelm@21940
  1055
      | (e,SOME src) =>
wenzelm@21940
  1056
        (Output.error_msg (Toplevel.exn_message e); loop true src)
aspinall@22337
  1057
      | (PGIP_QUIT,_) => ()
aspinall@21637
  1058
      | (_,NONE) => ()
aspinall@21637
  1059
in
aspinall@21637
  1060
  (* TODO: add socket interface *)
aspinall@21637
  1061
wenzelm@26552
  1062
  val xmlP = XML.parse_comments |-- XML.parse_element >> single
aspinall@21637
  1063
aspinall@21637
  1064
  val tty_src = Source.set_prompt "" (Source.source Symbol.stopper xmlP NONE Source.tty)
aspinall@21637
  1065
aspinall@21637
  1066
  fun pgip_toplevel x = loop true x
aspinall@21637
  1067
end
aspinall@21637
  1068
aspinall@21637
  1069
aspinall@21972
  1070
(* Extra command for embedding prover-control inside document (obscure/debug usage). *)
aspinall@21637
  1071
wenzelm@24867
  1072
fun init_outer_syntax () =
aspinall@21972
  1073
  OuterSyntax.improper_command "ProofGeneral.process_pgip" "(internal)" OuterKeyword.control
aspinall@21972
  1074
    (OuterParse.text >> (Toplevel.no_timing oo
aspinall@21649
  1075
      (fn txt => Toplevel.imperative (fn () => process_pgip_plain txt))));
aspinall@21637
  1076
aspinall@21637
  1077
aspinall@21637
  1078
(* init *)
aspinall@21637
  1079
aspinall@21637
  1080
val initialized = ref false;
aspinall@21637
  1081
wenzelm@22699
  1082
fun init_pgip false = panic "No Proof General interface support for Isabelle/classic mode."
wenzelm@21969
  1083
  | init_pgip true =
wenzelm@21969
  1084
      (! initialized orelse
aspinall@25445
  1085
        (setup_preferences_tweak ();
aspinall@25445
  1086
         setup_proofgeneral_output ();
aspinall@25445
  1087
         setup_messages ();
aspinall@25445
  1088
         Output.no_warnings init_outer_syntax ();
aspinall@25445
  1089
         setup_thy_loader ();
aspinall@25445
  1090
         setup_present_hook ();
aspinall@25445
  1091
         init_pgip_session_id ();
aspinall@25445
  1092
         welcome ();
aspinall@25445
  1093
         set initialized);
wenzelm@21969
  1094
        sync_thy_loader ();
wenzelm@21969
  1095
       change print_mode (cons proof_generalN o remove (op =) proof_generalN);
wenzelm@21969
  1096
       pgip_toplevel tty_src);
aspinall@21637
  1097
aspinall@21649
  1098
aspinall@21649
  1099
aspinall@21649
  1100
(** Out-of-loop PGIP commands (for Emacs hybrid mode) **)
aspinall@21649
  1101
aspinall@21649
  1102
local
wenzelm@22590
  1103
    val pgip_output_channel = ref Output.writeln_default
aspinall@21649
  1104
in
aspinall@21649
  1105
aspinall@21649
  1106
(* Set recipient for PGIP results *)
aspinall@21649
  1107
fun init_pgip_channel writefn =
wenzelm@21940
  1108
    (init_pgip_session_id();
wenzelm@21940
  1109
     pgip_output_channel := writefn)
aspinall@21649
  1110
wenzelm@21940
  1111
(* Process a PGIP command.
wenzelm@21940
  1112
   This works for preferences but not generally guaranteed
aspinall@21649
  1113
   because we haven't done full setup here (e.g., no pgml mode)  *)
aspinall@21649
  1114
fun process_pgip str =
aspinall@21649
  1115
     setmp output_xml_fn (!pgip_output_channel) process_pgip_plain str
aspinall@21649
  1116
aspinall@21649
  1117
end
aspinall@21637
  1118
aspinall@21637
  1119
end;
wenzelm@26706
  1120