src/Pure/Tools/simplifier_trace.ML
author Lars Hupel <lars.hupel@mytum.de>
Thu Mar 06 17:55:39 2014 +0100 (2014-03-06)
changeset 55946 5163ed3a38f5
parent 55611 8ae36527c2a6
child 56333 38f1422ef473
permissions -rw-r--r--
tuned
wenzelm@54730
     1
(*  Title:      Pure/Tools/simplifier_trace.ML
lars@55316
     2
    Author:     Lars Hupel
wenzelm@54730
     3
wenzelm@54730
     4
Interactive Simplifier trace.
wenzelm@54730
     5
*)
wenzelm@54730
     6
wenzelm@54730
     7
signature SIMPLIFIER_TRACE =
wenzelm@54730
     8
sig
lars@55316
     9
  val add_term_breakpoint: term -> Context.generic -> Context.generic
lars@55316
    10
  val add_thm_breakpoint: thm -> Context.generic -> Context.generic
wenzelm@54730
    11
end
wenzelm@54730
    12
wenzelm@54730
    13
structure Simplifier_Trace: SIMPLIFIER_TRACE =
wenzelm@54730
    14
struct
wenzelm@54730
    15
wenzelm@55552
    16
(** context data **)
lars@55316
    17
lars@55316
    18
datatype mode = Disabled | Normal | Full
lars@55316
    19
lars@55316
    20
fun merge_modes Disabled m = m
lars@55316
    21
  | merge_modes Normal Full = Full
lars@55316
    22
  | merge_modes Normal _ = Normal
lars@55316
    23
  | merge_modes Full _ = Full
lars@55316
    24
lars@55316
    25
val empty_breakpoints =
wenzelm@55560
    26
  (Item_Net.init (op aconv) single,
lars@55316
    27
   Item_Net.init eq_rrule (single o Thm.full_prop_of o #thm))
lars@55316
    28
lars@55316
    29
fun merge_breakpoints ((term_bs1, thm_bs1), (term_bs2, thm_bs2)) =
lars@55316
    30
  (Item_Net.merge (term_bs1, term_bs2),
lars@55316
    31
   Item_Net.merge (thm_bs1, thm_bs2))
lars@55316
    32
lars@55316
    33
structure Data = Generic_Data
lars@55316
    34
(
lars@55316
    35
  type T =
lars@55316
    36
    {max_depth: int,
lars@55316
    37
     mode: mode,
lars@55316
    38
     interactive: bool,
lars@55390
    39
     memory: bool,
lars@55316
    40
     parent: int,
lars@55316
    41
     breakpoints: term Item_Net.T * rrule Item_Net.T}
lars@55316
    42
  val empty =
lars@55316
    43
    {max_depth = 10,
lars@55316
    44
     mode = Disabled,
lars@55316
    45
     interactive = false,
lars@55390
    46
     memory = true,
lars@55316
    47
     parent = 0,
lars@55316
    48
     breakpoints = empty_breakpoints}
lars@55316
    49
  val extend = I
wenzelm@55552
    50
  fun merge
wenzelm@55552
    51
    ({max_depth = max_depth1, mode = mode1, interactive = interactive1,
wenzelm@55552
    52
      memory = memory1, breakpoints = breakpoints1, ...}: T,
wenzelm@55552
    53
     {max_depth = max_depth2, mode = mode2, interactive = interactive2,
wenzelm@55552
    54
      memory = memory2, breakpoints = breakpoints2, ...}: T) =
lars@55316
    55
    {max_depth = Int.max (max_depth1, max_depth2),
lars@55316
    56
     mode = merge_modes mode1 mode2,
lars@55316
    57
     interactive = interactive1 orelse interactive2,
lars@55390
    58
     memory = memory1 andalso memory2,
lars@55316
    59
     parent = 0,
lars@55335
    60
     breakpoints = merge_breakpoints (breakpoints1, breakpoints2)}: T
lars@55316
    61
)
lars@55316
    62
lars@55316
    63
fun map_breakpoints f_term f_thm =
lars@55390
    64
  Data.map
lars@55946
    65
    (fn {max_depth, mode, interactive, parent, memory, breakpoints = (term_bs, thm_bs)} =>
lars@55390
    66
      {max_depth = max_depth,
lars@55390
    67
       mode = mode,
lars@55390
    68
       interactive = interactive,
lars@55390
    69
       memory = memory,
lars@55390
    70
       parent = parent,
lars@55390
    71
       breakpoints = (f_term term_bs, f_thm thm_bs)})
lars@55316
    72
lars@55316
    73
fun add_term_breakpoint term =
lars@55316
    74
  map_breakpoints (Item_Net.update term) I
lars@55316
    75
lars@55316
    76
fun add_thm_breakpoint thm context =
lars@55316
    77
  let
lars@55316
    78
    val rrules = mk_rrules (Context.proof_of context) [thm]
lars@55316
    79
  in
lars@55316
    80
    map_breakpoints I (fold Item_Net.update rrules) context
lars@55316
    81
  end
lars@55316
    82
lars@55316
    83
fun is_breakpoint (term, rrule) context =
lars@55316
    84
  let
lars@55316
    85
    val {breakpoints, ...} = Data.get context
lars@55316
    86
lars@55316
    87
    fun matches pattern = Pattern.matches (Context.theory_of context) (pattern, term)
lars@55316
    88
    val term_matches = filter matches (Item_Net.retrieve_matching (fst breakpoints) term)
lars@55316
    89
lars@55316
    90
    val {thm = thm, ...} = rrule
lars@55316
    91
    val thm_matches = exists (eq_rrule o pair rrule)
lars@55316
    92
      (Item_Net.retrieve_matching (snd breakpoints) (Thm.full_prop_of thm))
lars@55316
    93
  in
lars@55316
    94
    (term_matches, thm_matches)
lars@55316
    95
  end
lars@55316
    96
wenzelm@55552
    97
wenzelm@55552
    98
lars@55316
    99
(** config and attributes **)
lars@55316
   100
lars@55390
   101
fun config raw_mode interactive max_depth memory =
lars@55316
   102
  let
wenzelm@55552
   103
    val mode =
wenzelm@55552
   104
      (case raw_mode of
wenzelm@55552
   105
        "normal" => Normal
wenzelm@55552
   106
      | "full" => Full
wenzelm@55552
   107
      | _ => error ("Simplifier_Trace.config: unknown mode " ^ raw_mode))
lars@55316
   108
lars@55946
   109
    val update = Data.map (fn {parent, breakpoints, ...} =>
lars@55316
   110
      {max_depth = max_depth,
lars@55316
   111
       mode = mode,
lars@55316
   112
       interactive = interactive,
lars@55390
   113
       memory = memory,
lars@55316
   114
       parent = parent,
lars@55316
   115
       breakpoints = breakpoints})
lars@55316
   116
  in Thm.declaration_attribute (K update) end
lars@55316
   117
lars@55316
   118
fun term_breakpoint terms =
lars@55316
   119
  Thm.declaration_attribute (K (fold add_term_breakpoint terms))
lars@55316
   120
lars@55316
   121
val thm_breakpoint =
lars@55316
   122
  Thm.declaration_attribute add_thm_breakpoint
lars@55316
   123
wenzelm@55552
   124
wenzelm@55552
   125
lars@55316
   126
(** tracing state **)
lars@55316
   127
lars@55316
   128
val futures =
lars@55316
   129
  Synchronized.var "Simplifier_Trace.futures" (Inttab.empty: string future Inttab.table)
lars@55316
   130
wenzelm@55552
   131
wenzelm@55552
   132
lars@55316
   133
(** markup **)
lars@55316
   134
lars@55316
   135
fun output_result (id, data) =
lars@55316
   136
  Output.result (Markup.serial_properties id) data
lars@55316
   137
lars@55316
   138
val parentN = "parent"
lars@55316
   139
val textN = "text"
lars@55390
   140
val memoryN = "memory"
lars@55316
   141
val successN = "success"
lars@55316
   142
lars@55316
   143
type payload =
lars@55316
   144
  {props: Properties.T,
lars@55316
   145
   pretty: Pretty.T}
lars@55316
   146
lars@55316
   147
fun empty_payload () : payload =
lars@55316
   148
  {props = [], pretty = Pretty.str ""}
lars@55316
   149
lars@55316
   150
fun mk_generic_result markup text triggered (payload : unit -> payload) ctxt =
lars@55316
   151
  let
lars@55946
   152
    val {mode, interactive, memory, parent, ...} = Data.get (Context.Proof ctxt)
lars@55316
   153
lars@55316
   154
    val eligible =
wenzelm@55552
   155
      (case mode of
lars@55316
   156
        Disabled => false
lars@55316
   157
      | Normal => triggered
wenzelm@55552
   158
      | Full => true)
lars@55316
   159
wenzelm@55553
   160
    val markup' =
wenzelm@55553
   161
      if markup = Markup.simp_trace_stepN andalso not interactive
wenzelm@55553
   162
      then Markup.simp_trace_logN
wenzelm@55553
   163
      else markup
lars@55316
   164
  in
lars@55946
   165
    if not eligible then NONE
lars@55316
   166
    else
lars@55316
   167
      let
lars@55316
   168
        val {props = more_props, pretty} = payload ()
lars@55316
   169
        val props =
lars@55316
   170
          [(textN, text),
lars@55390
   171
           (memoryN, Markup.print_bool memory),
lars@55316
   172
           (parentN, Markup.print_int parent)]
lars@55316
   173
        val data =
lars@55316
   174
          Pretty.string_of (Pretty.markup (markup', props @ more_props) [pretty])
lars@55316
   175
      in
lars@55316
   176
        SOME (serial (), data)
lars@55316
   177
      end
lars@55316
   178
  end
lars@55316
   179
wenzelm@55552
   180
wenzelm@55552
   181
lars@55316
   182
(** tracing output **)
lars@55316
   183
lars@55316
   184
fun send_request (result_id, content) =
lars@55316
   185
  let
lars@55316
   186
    fun break () =
wenzelm@55553
   187
      (Output.protocol_message (Markup.simp_trace_cancel result_id) "";
lars@55316
   188
       Synchronized.change futures (Inttab.delete_safe result_id))
lars@55316
   189
    val promise = Future.promise break : string future
lars@55316
   190
  in
lars@55316
   191
    Synchronized.change futures (Inttab.update_new (result_id, promise));
lars@55316
   192
    output_result (result_id, content);
lars@55316
   193
    promise
lars@55316
   194
  end
lars@55316
   195
lars@55316
   196
lars@55335
   197
type data = {term: term, thm: thm, unconditional: bool, ctxt: Proof.context, rrule: rrule}
lars@55335
   198
lars@55335
   199
fun step ({term, thm, unconditional, ctxt, rrule}: data) =
lars@55316
   200
  let
lars@55316
   201
    val (matching_terms, thm_triggered) = is_breakpoint (term, rrule) (Context.Proof ctxt)
lars@55316
   202
lars@55316
   203
    val {name, ...} = rrule
lars@55316
   204
    val term_triggered = not (null matching_terms)
wenzelm@54730
   205
lars@55316
   206
    val text =
wenzelm@55552
   207
      if unconditional then "Apply rewrite rule?"
wenzelm@55552
   208
      else "Apply conditional rewrite rule?"
lars@55316
   209
lars@55316
   210
    fun payload () =
lars@55316
   211
      let
lars@55316
   212
        (* FIXME pretty printing via Proof_Context.pretty_fact *)
lars@55316
   213
        val pretty_thm = Pretty.block
lars@55316
   214
          [Pretty.str ("Instance of " ^ name ^ ":"),
lars@55316
   215
           Pretty.brk 1,
lars@55316
   216
           Syntax.pretty_term ctxt (Thm.prop_of thm)]
lars@55316
   217
lars@55316
   218
        val pretty_term = Pretty.block
lars@55316
   219
          [Pretty.str "Trying to rewrite:",
lars@55316
   220
           Pretty.brk 1,
lars@55316
   221
           Syntax.pretty_term ctxt term]
lars@55316
   222
lars@55316
   223
        val pretty_matchings =
lars@55316
   224
          let
lars@55316
   225
            val items = map (Pretty.item o single o Syntax.pretty_term ctxt) matching_terms
lars@55316
   226
          in
lars@55316
   227
            if not (null matching_terms) then
lars@55316
   228
              [Pretty.block (Pretty.fbreaks (Pretty.str "Matching terms:" :: items))]
wenzelm@55552
   229
            else []
lars@55316
   230
          end
lars@55316
   231
lars@55316
   232
        val pretty =
lars@55316
   233
          Pretty.chunks ([pretty_thm, pretty_term] @ pretty_matchings)
lars@55316
   234
      in
lars@55316
   235
        {props = [], pretty = pretty}
lars@55316
   236
      end
lars@55316
   237
lars@55946
   238
    val {max_depth, mode, interactive, memory, breakpoints, ...} =
lars@55316
   239
      Data.get (Context.Proof ctxt)
lars@55316
   240
lars@55316
   241
    fun mk_promise result =
lars@55316
   242
      let
lars@55316
   243
        val result_id = #1 result
lars@55316
   244
lars@55316
   245
        fun put mode' interactive' = Data.put
lars@55316
   246
          {max_depth = max_depth,
lars@55316
   247
           mode = mode',
lars@55316
   248
           interactive = interactive',
lars@55390
   249
           memory = memory,
lars@55316
   250
           parent = result_id,
lars@55316
   251
           breakpoints = breakpoints} (Context.Proof ctxt) |>
lars@55316
   252
          Context.the_proof
lars@55316
   253
lars@55316
   254
        fun to_response "skip" = NONE
lars@55316
   255
          | to_response "continue" = SOME (put mode true)
lars@55316
   256
          | to_response "continue_trace" = SOME (put Full true)
lars@55316
   257
          | to_response "continue_passive" = SOME (put mode false)
lars@55316
   258
          | to_response "continue_disable" = SOME (put Disabled false)
lars@55316
   259
          | to_response _ = raise Fail "Simplifier_Trace.step: invalid message"
lars@55316
   260
      in
lars@55316
   261
        if not interactive then
lars@55316
   262
          (output_result result; Future.value (SOME (put mode false)))
wenzelm@55552
   263
        else Future.map to_response (send_request result)
lars@55316
   264
      end
lars@55316
   265
lars@55316
   266
  in
wenzelm@55553
   267
    (case mk_generic_result Markup.simp_trace_stepN text
wenzelm@55553
   268
        (thm_triggered orelse term_triggered) payload ctxt of
lars@55316
   269
      NONE => Future.value (SOME ctxt)
wenzelm@55552
   270
    | SOME res => mk_promise res)
lars@55316
   271
  end
lars@55316
   272
lars@55946
   273
fun recurse text depth term ctxt =
lars@55316
   274
  let
lars@55316
   275
    fun payload () =
lars@55316
   276
      {props = [],
lars@55316
   277
       pretty = Syntax.pretty_term ctxt term}
lars@55316
   278
lars@55946
   279
    val {max_depth, mode, interactive, memory, breakpoints, ...} =
lars@55390
   280
      Data.get (Context.Proof ctxt)
lars@55316
   281
lars@55316
   282
    fun put result_id = Data.put
lars@55316
   283
      {max_depth = max_depth,
lars@55316
   284
       mode = if depth >= max_depth then Disabled else mode,
lars@55316
   285
       interactive = interactive,
lars@55390
   286
       memory = memory,
lars@55316
   287
       parent = result_id,
lars@55316
   288
       breakpoints = breakpoints} (Context.Proof ctxt)
lars@55316
   289
lars@55316
   290
    val context' =
wenzelm@55553
   291
      (case mk_generic_result Markup.simp_trace_recurseN text true payload ctxt of
wenzelm@55552
   292
        NONE => put 0
wenzelm@55552
   293
      | SOME res => (output_result res; put (#1 res)))
lars@55316
   294
  in Context.the_proof context' end
lars@55316
   295
lars@55335
   296
fun indicate_failure ({term, ctxt, thm, rrule, ...}: data) ctxt' =
lars@55316
   297
  let
lars@55316
   298
    fun payload () =
lars@55316
   299
      let
lars@55316
   300
        val {name, ...} = rrule
lars@55316
   301
        val pretty_thm =
lars@55316
   302
          (* FIXME pretty printing via Proof_Context.pretty_fact *)
lars@55316
   303
          Pretty.block
lars@55316
   304
            [Pretty.str ("In an instance of " ^ name ^ ":"),
lars@55316
   305
             Pretty.brk 1,
lars@55316
   306
             Syntax.pretty_term ctxt (Thm.prop_of thm)]
lars@55316
   307
lars@55316
   308
        val pretty_term =
lars@55316
   309
          Pretty.block
lars@55316
   310
            [Pretty.str "Was trying to rewrite:",
lars@55316
   311
             Pretty.brk 1,
lars@55316
   312
             Syntax.pretty_term ctxt term]
lars@55316
   313
lars@55316
   314
        val pretty =
lars@55316
   315
          Pretty.chunks [pretty_thm, pretty_term]
lars@55316
   316
      in
lars@55316
   317
        {props = [(successN, "false")], pretty = pretty}
lars@55316
   318
      end
lars@55316
   319
lars@55316
   320
    val {interactive, ...} = Data.get (Context.Proof ctxt)
lars@55316
   321
lars@55316
   322
    fun mk_promise result =
lars@55316
   323
      let
wenzelm@55552
   324
        fun to_response "exit" = false
lars@55316
   325
          | to_response "redo" =
lars@55316
   326
              (Option.app output_result
wenzelm@55553
   327
                (mk_generic_result Markup.simp_trace_ignoreN "Ignore" true empty_payload ctxt');
lars@55316
   328
               true)
wenzelm@55552
   329
          | to_response _ = raise Fail "Simplifier_Trace.indicate_failure: invalid message"
lars@55316
   330
      in
lars@55316
   331
        if not interactive then
lars@55316
   332
          (output_result result; Future.value false)
wenzelm@55552
   333
        else Future.map to_response (send_request result)
lars@55316
   334
      end
lars@55316
   335
  in
wenzelm@55553
   336
    (case mk_generic_result Markup.simp_trace_hintN "Step failed" true payload ctxt' of
lars@55316
   337
      NONE => Future.value false
wenzelm@55552
   338
    | SOME res => mk_promise res)
lars@55316
   339
  end
lars@55316
   340
lars@55316
   341
fun indicate_success thm ctxt =
lars@55316
   342
  let
lars@55316
   343
    fun payload () =
lars@55316
   344
      {props = [(successN, "true")],
lars@55316
   345
       pretty = Syntax.pretty_term ctxt (Thm.prop_of thm)}
lars@55316
   346
  in
wenzelm@55553
   347
    Option.app output_result
wenzelm@55553
   348
      (mk_generic_result Markup.simp_trace_hintN "Successfully rewrote" true payload ctxt)
lars@55316
   349
  end
lars@55316
   350
wenzelm@55552
   351
wenzelm@55552
   352
lars@55316
   353
(** setup **)
lars@55316
   354
lars@55390
   355
fun simp_apply args ctxt cont =
lars@55316
   356
  let
lars@55316
   357
    val {unconditional: bool, term: term, thm: thm, rrule: rrule} = args
lars@55316
   358
    val data =
lars@55316
   359
      {term = term,
lars@55316
   360
       unconditional = unconditional,
lars@55316
   361
       ctxt = ctxt,
lars@55316
   362
       thm = thm,
lars@55316
   363
       rrule = rrule}
lars@55316
   364
  in
wenzelm@55552
   365
    (case Future.join (step data) of
wenzelm@55552
   366
      NONE => NONE
lars@55316
   367
    | SOME ctxt' =>
lars@55316
   368
        let val res = cont ctxt' in
wenzelm@55552
   369
          (case res of
lars@55316
   370
            NONE =>
lars@55316
   371
              if Future.join (indicate_failure data ctxt') then
lars@55390
   372
                simp_apply args ctxt cont
wenzelm@55552
   373
              else NONE
wenzelm@55552
   374
          | SOME (thm, _) => (indicate_success thm ctxt'; res))
wenzelm@55552
   375
        end)
lars@55316
   376
  end
lars@55316
   377
lars@55316
   378
val _ = Session.protocol_handler "isabelle.Simplifier_Trace$Handler"
wenzelm@54730
   379
wenzelm@54730
   380
val _ = Theory.setup
wenzelm@54731
   381
  (Simplifier.set_trace_ops
lars@55946
   382
    {trace_invoke = fn {depth, term} => recurse "Simplifier invoked" depth term,
lars@55390
   383
     trace_apply = simp_apply})
lars@55316
   384
lars@55316
   385
val _ =
wenzelm@55553
   386
  Isabelle_Process.protocol_command "Simplifier_Trace.reply"
lars@55316
   387
    (fn [s, r] =>
lars@55316
   388
      let
lars@55316
   389
        val serial = Markup.parse_int s
lars@55316
   390
        fun lookup_delete tab =
lars@55316
   391
          (Inttab.lookup tab serial, Inttab.delete_safe serial tab)
lars@55316
   392
        fun apply_result (SOME promise) = Future.fulfill promise r
lars@55316
   393
          | apply_result NONE = () (* FIXME handle protocol failure, just like in active.ML? *)
lars@55316
   394
      in
lars@55316
   395
        (Synchronized.change_result futures lookup_delete |> apply_result)
lars@55316
   396
          handle exn => if Exn.is_interrupt exn then () (*sic!*) else reraise exn
lars@55316
   397
      end)
lars@55316
   398
wenzelm@55552
   399
wenzelm@55552
   400
lars@55316
   401
(** attributes **)
lars@55316
   402
wenzelm@55560
   403
val mode_parser =
lars@55316
   404
  Scan.optional
lars@55316
   405
    (Args.$$$ "mode" |-- Args.$$$ "=" |-- (Args.$$$ "normal" || Args.$$$ "full"))
lars@55316
   406
    "normal"
wenzelm@54730
   407
wenzelm@55560
   408
val interactive_parser =
lars@55316
   409
  Scan.optional (Args.$$$ "interactive" >> K true) false
lars@55316
   410
wenzelm@55560
   411
val memory_parser =
lars@55390
   412
  Scan.optional (Args.$$$ "no_memory" >> K false) true
lars@55390
   413
lars@55316
   414
val depth_parser =
lars@55316
   415
  Scan.optional (Args.$$$ "depth" |-- Args.$$$ "=" |-- Parse.nat) 10
lars@55316
   416
lars@55316
   417
val config_parser =
lars@55390
   418
  (interactive_parser -- mode_parser -- depth_parser -- memory_parser) >>
lars@55390
   419
    (fn (((interactive, mode), depth), memory) => config mode interactive depth memory)
wenzelm@54730
   420
lars@55316
   421
val _ = Theory.setup
lars@55316
   422
  (Attrib.setup @{binding break_term}
wenzelm@55560
   423
    (Scan.repeat1 Args.term_pattern >> term_breakpoint)
lars@55316
   424
    "declaration of a term breakpoint" #>
lars@55316
   425
   Attrib.setup @{binding break_thm}
lars@55316
   426
    (Scan.succeed thm_breakpoint)
lars@55316
   427
    "declaration of a theorem breakpoint" #>
lars@55316
   428
   Attrib.setup @{binding simplifier_trace} (Scan.lift config_parser)
lars@55316
   429
    "simplifier trace configuration")
wenzelm@54730
   430
wenzelm@54730
   431
end