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