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