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