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