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