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