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