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