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