-
Notifications
You must be signed in to change notification settings - Fork 14
/
debug.scala
455 lines (422 loc) · 21 KB
/
debug.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
* Copyright 2020 Parsley Contributors <https://github.com/j-mie6/Parsley/graphs/contributors>
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package parsley
import scala.annotation.tailrec
import scala.collection.mutable
import parsley.errors.ErrorBuilder
import parsley.state.Ref
import parsley.internal.deepembedding.frontend
/** This module contains the very useful debugging combinator, as well as breakpoints.
*
* @groupprio comb 0
* @groupname comb Debug Combinator Extension Methods
* @groupdesc comb
* These are the debugging combinators, which are enabled by bringing these implicit classes
* into scope.
*
* @groupprio break 10
* @groupname break Breakpoints
* @groupdesc break
* These can be used to control how the `debug` combinator operates: when a breakpoint is used
* it can halt the execution of the combinator and print out information about the parsers state.
*
* @groupprio ctrl 5
* @groupname ctrl Debug Control
* @groupdesc ctrl
* These methods can control how the debug mechanism functions in a general way.
*/
object debug {
// $COVERAGE-OFF$
/** Base trait for breakpoints.
*
* @group break
*/
sealed trait Breakpoint
/** Indicates that no breaking should occur.
*
* @group break
*/
case object NoBreak extends Breakpoint
/** Break on entry to the combinator, require user input to advance.
*
* @group break
*/
case object EntryBreak extends Breakpoint
/** Break on exit to the combinator, require user input to advance.
*
* @group break
*/
case object ExitBreak extends Breakpoint
/** Break on both entry and exit to the combinator, require user input to advance in both cases.
*
* @group break
*/
case object FullBreak extends Breakpoint
private [parsley] var renderAscii = false
/** This method can be used to disable the colored debug output for terminals that don't support it.
*
* @group ctrl
*/
def disableColorRendering(): Unit = renderAscii = true
/** This class enables the `debug` combinator on parsers.
*
* This extension class operates on values that are convertible to parsers. It enables the use of
* the `debug` combinator, which can be used to trace the execution through a parser.
*
* @constructor This constructor should not be called manually, it is designed to be used via Scala's implicit resolution.
* @param p the value that this class is enabling methods on.
* @param con a conversion that allows values convertible to parsers to be used.
* @tparam P the type of base value that this class is used on (the conversion to `Parsley`) is summoned automatically.
* @group comb
*
* @define debug This combinator allows this parser to be debugged by providing a trace through the execution.
*
* When this combinator is entered, it will print the name assigned to the parser,
* as well as the current input context for a few characters on either side.
* This parser is then executed. If it succeeded, this combinator again reports the
* name along with "`Good`" and the input context. If it failed, it reports the name
* along with "`Bad`" and the input context.
*
* When breakpoints are used, the execution of the combinator will pause on either entry,
* exit, or both. The parse is resumed by entering a newline on standard input. Breakpoints
* will cause additional information about the internal state of the parser to be reported.
*/
implicit class DebugCombinators[P, A](p: P)(implicit con: P => Parsley[A]) {
/** $debug
*
* @example {{{
* scala> import parsley.debug.DebugCombinators, parsley.character.string, parsley.Parsley.attempt
* scala> val abc = attempt(string("abc").debug("string abc")).debug("attempt")
* scala> val abd = string("abd").debug("string abd")
* scala> val p = (abc <|> abd).debug("or")
* scala> p.parse("abd")
* >or> (1, 1): abd•
* ^
* >attempt> (1, 1): abd•
* ^
* >string abc> (1, 1): abd•
* ^
* <string abc< (1, 3): abd• Fail
* ^
* <attempt< (1, 1): abd• Fail
* ^
* >string abd> (1, 1): abd•
* ^
* <string abd< (1, 4): abd• Good
* ^
* <or< (1, 4): abd• Good
* ^
* val res0 = Success("abd")
* }}}
*
* @param name The name to be assigned to this parser
* @param break The breakpoint properties of this parser, defaults to NoBreak
* @param colored Whether to render with (default true: render colours)
* @param watchedRefs Which references to also track the values of and their names, if any
*/
def debug(name: String, break: Breakpoint, colored: Boolean, watchedRefs: (Ref[_], String)*): Parsley[A] = {
new Parsley(new frontend.Debug[A](con(p).internal, name, !colored, break, watchedRefs))
}
private [parsley] def debug(name: String, break: Breakpoint, colored: Boolean): Parsley[A] = {
debug(name, break, colored, Seq.empty[(Ref[_], String)]: _*): @org.typelevel.scalaccompat.annotation.nowarn3
}
/** $debug
*
* @example {{{
* scala> import parsley.debug.DebugCombinators, parsley.character.string, parsley.Parsley.attempt
* scala> val abc = attempt(string("abc").debug("string abc")).debug("attempt")
* scala> val abd = string("abd").debug("string abd")
* scala> val p = (abc <|> abd).debug("or")
* scala> p.parse("abd")
* >or> (1, 1): abd•
* ^
* >attempt> (1, 1): abd•
* ^
* >string abc> (1, 1): abd•
* ^
* <string abc< (1, 3): abd• Fail
* ^
* <attempt< (1, 1): abd• Fail
* ^
* >string abd> (1, 1): abd•
* ^
* <string abd< (1, 4): abd• Good
* ^
* <or< (1, 4): abd• Good
* ^
* val res0 = Success("abd")
* }}}
*
* Renders in colour.
*
* @param name The name to be assigned to this parser
* @param break The breakpoint properties of this parser, defaults to NoBreak
* @param watchedRefs Which references to also track the values of and their names, if any
*/
def debug(name: String, break: Breakpoint, watchedRefs: (Ref[_], String)*): Parsley[A] =
debug(name, break, colored = true, watchedRefs: _*): @org.typelevel.scalaccompat.annotation.nowarn3
private [parsley] def debug(name: String, break: Breakpoint): Parsley[A] =
debug(name, break, Seq.empty[(Ref[_], String)]: _*): @org.typelevel.scalaccompat.annotation.nowarn3
/** $debug
*
* @example {{{
* scala> import parsley.debug.DebugCombinators, parsley.character.string, parsley.Parsley.attempt
* scala> val abc = attempt(string("abc").debug("string abc")).debug("attempt")
* scala> val abd = string("abd").debug("string abd")
* scala> val p = (abc <|> abd).debug("or")
* scala> p.parse("abd")
* >or> (1, 1): abd•
* ^
* >attempt> (1, 1): abd•
* ^
* >string abc> (1, 1): abd•
* ^
* <string abc< (1, 3): abd• Fail
* ^
* <attempt< (1, 1): abd• Fail
* ^
* >string abd> (1, 1): abd•
* ^
* <string abd< (1, 4): abd• Good
* ^
* <or< (1, 4): abd• Good
* ^
* val res0 = Success("abd")
* }}}
*
* No break-points.
*
* @param name The name to be assigned to this parser
* @param colored Whether to render with colour
* @param watchedRefs Which references to also track the values of and their names, if any
*/
def debug(name: String, colored: Boolean, watchedRefs: (Ref[_], String)*): Parsley[A] =
debug(name, break = NoBreak, colored, watchedRefs: _*): @org.typelevel.scalaccompat.annotation.nowarn3
private [parsley] def debug(name: String, colored: Boolean): Parsley[A] =
debug(name, colored, Seq.empty[(Ref[_], String)]: _*): @org.typelevel.scalaccompat.annotation.nowarn3
/** $debug
*
* @example {{{
* scala> import parsley.debug.DebugCombinators, parsley.character.string, parsley.Parsley.attempt
* scala> val abc = attempt(string("abc").debug("string abc")).debug("attempt")
* scala> val abd = string("abd").debug("string abd")
* scala> val p = (abc <|> abd).debug("or")
* scala> p.parse("abd")
* >or> (1, 1): abd•
* ^
* >attempt> (1, 1): abd•
* ^
* >string abc> (1, 1): abd•
* ^
* <string abc< (1, 3): abd• Fail
* ^
* <attempt< (1, 1): abd• Fail
* ^
* >string abd> (1, 1): abd•
* ^
* <string abd< (1, 4): abd• Good
* ^
* <or< (1, 4): abd• Good
* ^
* val res0 = Success("abd")
* }}}
*
* Renders in colour with no break-point.
*
* @param name The name to be assigned to this parser
* @param watchedRefs Which references to also track the values of and their names, if any
*/
def debug(name: String, watchedRefs: (Ref[_], String)*): Parsley[A] =
debug(name, break = NoBreak, colored = true, watchedRefs: _*): @org.typelevel.scalaccompat.annotation.nowarn3
private [parsley] def debug(name: String): Parsley[A] = debug(name, Seq.empty[(Ref[_], String)]: _*): @org.typelevel.scalaccompat.annotation.nowarn3
/** Display information about the error messages generated by this parser.
*
* This is an experimental debugger that provides internal information about error messages.
* This provides more detail than one might normally see inside a regular error message, but
* may help isolate the root cause of an error message not being as expected: this can form the
* bulk of a specific question on the discussion board.
*
* @param name The name to be assigned to this parser
* @param colored Whether the output should be colourful
* @param errBuilder The error builder used for formatting messages in the "real parser",
* which is used to help format information in the debugger.
* @since 4.0.0
*/
def debugError(name: String, colored: Boolean)(implicit errBuilder: ErrorBuilder[_]): Parsley[A] = {
new Parsley(new frontend.DebugError[A](con(p).internal, name, !colored, errBuilder))
}
/** Display information about the error messages generated by this parser.
*
* This is an experimental debugger that provides internal information about error messages.
* This provides more detail than one might normally see inside a regular error message, but
* may help isolate the root cause of an error message not being as expected: this can form the
* bulk of a specific question on the discussion board.
*
* @param name The name to be assigned to this parser
* @param colored Whether the output should be colourful
* @param errBuilder The error builder used for formatting messages in the "real parser",
* which is used to help format information in the debugger.
* @since 4.0.0
*/
def debugError(name: String)(implicit errBuilder: ErrorBuilder[_]): Parsley[A] = debugError(name, colored = true)
/** This combinator allows for the runtime of this parser to be measured.
*
* When this parser executes, its start and end times will be logged using `System.nanoTime()`,
* which has a resolution of 100ns. These will be logged into the given `Profiler` object.
*
* @param name the ''unique'' name of this parser, which will represent it in the table
* @param profiler the profiling object that will collect and process the data
* @note usual disclaimers about profiling apply: results are just data; use your judgement
* @see [[Profiler `Profiler`]]
* @since 4.4.0
*/
def profile(name: String)(implicit profiler: Profiler): Parsley[A] = new Parsley(new frontend.Profile[A](con(p).internal, name, profiler))
}
// $COVERAGE-ON$
/** This class is used to store the profile data for a specific group of sub-parsers.
*
* It records the start and end timestamps of the parsers that interact with it. It is possible
* to use multiple different profilers if you want to establish the cumulative time for a sub-parser
* instead of the self-time.
*
* This class is mutable, so care must be taken to call `reset()` between runs, unless you want to
* accumulate the data.
*
* @since 4.4.0
*/
class Profiler {
private val entries = mutable.Map.empty[String, mutable.Buffer[Long]]
private val exits = mutable.Map.empty[String, mutable.Buffer[Long]]
private var lastTime: Long = 0
private var lastTimeCount: Long = 0
// $COVERAGE-OFF$
/** Prints a summary of the data sampled by this profiler.
*
* After the run(s) of the parser are complete, this method can be used to
* generate the summary of the sampled data. It will print a table where the
* total "self-time", number of invocations and average "self-time" are displayed
* for each profiled sub-parser.
*
* * '''self-time''': this is the amount of time spend in a specific parser, removing
* the times from within the child parsers.
*
* @note to measure cumulative time of a parser, consider using a separate `Profiler`
* object for it instead.
* @since 4.4.0
*/
def summary(): Unit = {
val (selfTotals, invocations) = process
render(selfTotals, invocations)
}
// $COVERAGE-ON$
/** Clears the data within this profiler.
* @since 4.4.0
*/
def reset(): Unit = {
// can't clear the maps, because the instructions may have already captured the lists
for ((_, timings) <- entries) timings.clear()
for ((_, timings) <- exits) timings.clear()
lastTime = 0
lastTimeCount = 0
}
private [parsley] def entriesFor(name: String): mutable.Buffer[Long] = entries.getOrElseUpdate(name, mutable.ListBuffer.empty)
private [parsley] def exitsFor(name: String): mutable.Buffer[Long] = exits.getOrElseUpdate(name, mutable.ListBuffer.empty)
private [parsley] def monotone(n: Long) = {
if (n == lastTime) {
lastTimeCount += 1
n + lastTimeCount
}
else {
lastTime = n
lastTimeCount = 0
n
}
}
private [parsley] def process: (Map[String, Long], Map[String, Int]) = {
val allEntries = collapse(entries).sortBy(_._2)
val allExits = collapse(exits).sortBy(_._2)
require((allEntries ::: allExits).toSet.size == (allExits.length + allExits.length),
"recorded times must all be monotonically increasing")
val selfTotals = mutable.Map.empty[String, Long]
val invocations = mutable.Map.empty[String, Int]
@tailrec
def go(entries: List[(String, Long)], exits: List[(String, Long)], stack: List[((String, Long), Long)], cum: Long): Unit = {
(entries, exits, stack) match {
case (Nil, Nil, Nil) =>
// final unwinding or stuff to clear on the stack (cum here is for the children)
case (ens, (n2, t2)::exs, ((n1, t1), oldCum)::stack) if ens.headOption.forall(t2 < _._2) =>
assert(n1 == n2, "unwinding should result in matching values")
add(invocations, n1)(1)
add(selfTotals, n1)(t2 - t1 - cum)
go(ens, exs, stack, oldCum + t2 - t1)
// in this case, the scope closes quickly (cum here is for your siblings)
case ((n1, t1)::ens, (n2, t2)::exs, stack) if ens.headOption.forall(t2 < _._2) && n1 == n2 =>
assert(ens.nonEmpty || n1 == n2, "unwinding should result in matching values")
add(invocations, n1)(1)
add(selfTotals, n1)(t2 - t1)
go(ens, exs, stack, cum + t2 - t1)
// the next one opens first, or the entry and exit don't match
// in either case, this isn't our exit, push ourselves onto the stack (cum here is for your siblings)
case (nt::ens, exs@(_ :: _), stack) => go(ens, exs, (nt, cum)::stack, 0)
// $COVERAGE-OFF$
case (Nil, Nil, _::_)
| (Nil, _::_, Nil)
| (_ ::_, Nil, _) => assert(false, "something has gone very wrong")
case (Nil, _::_, _::_) => ??? // deadcode from case 2
// $COVERAGE-ON$
}
}
//println(allEntries.map { case (name, t) => (name, t - allEntries.head._2) })
//println(allExits.map { case (name, t) => (name, t - allEntries.head._2) })
go(allEntries, allExits, Nil, 0)
(selfTotals.toMap, invocations.toMap)
}
private def collapse(timings: Iterable[(String, Iterable[Long])]): List[(String, Long)] = timings.flatMap {
case (name, times) => times.map(t => (name, t))
}.toList
private def add[A: Numeric](m: mutable.Map[String, A], name: String)(n: A): Unit = m.get(name) match {
case Some(x) => m(name) = implicitly[Numeric[A]].plus(x, n)
case None => m(name) = n
}
// $COVERAGE-OFF$
private def render(selfTimes: Map[String, Long], invocations: Map[String, Int]): Unit = {
val combined = selfTimes.map {
case (name, selfTime) =>
val invokes = invocations(name)
(name, (f"${selfTime/1000.0}%.1fμs", invocations(name), f"${selfTime/invokes/1000.0}%.3fμs"))
}
val head1 = "name"
val head2 = "self time"
val head3 = "num calls"
val head4 = "average self time"
val (names, data) = combined.unzip
val (selfs, invokes, avs) = data.unzip3
val col1Width = (head1.length :: names.map(_.length).toList).max
val col2Width = (head2.length :: selfs.map(_.length).toList).max
val col3Width = (head3.length :: invokes.map(digits(_)).toList).max
val col4Width = (head4.length :: avs.map(_.length).toList).max
val header = List(pad(head1, col1Width), tab(col1Width),
pad(head2, col2Width), tab(col2Width),
pad(head3, col3Width), tab(col3Width),
pad(head4, col4Width)).mkString
val hline = header.map(_ => '-')
println(header)
println(hline)
for ((name, (selfTime, invokes, avSelfTime)) <- combined) {
println(List(pad(name, col1Width), tab(col1Width),
prePad(selfTime, col2Width), tab(col2Width),
prePad(invokes.toString, col3Width), tab(col3Width),
prePad(avSelfTime, col4Width)).mkString)
}
println(hline)
}
private def pad(str: String, n: Int) = str + " " * (n - str.length)
private def prePad(str: String, n: Int) = " " * (n - str.length) + str
private def digits[A: Numeric](n: A): Int = Math.log10(implicitly[Numeric[A]].toDouble(n)).toInt + 1
private def tab(n: Int) = " " * (4 - n % 4)
// $COVERAGE-ON$
}
}