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