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