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