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