Skip to content

Commit 31459de

Browse files
committed
Add debug macro
1 parent 3a77ac2 commit 31459de

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

core/src/main/scala/ox/util.scala

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package ox
33
import scala.concurrent.{Await, Future}
44
import scala.concurrent.duration.*
55
import scala.util.control.NonFatal
6+
import scala.quoted.*
67

78
extension [T](inline t: T)
89
/** Discard the result of the computation, to avoid discarded non-unit value warnings.
@@ -113,3 +114,19 @@ inline def timed[T](operation: => T): (FiniteDuration, T) =
113114
val after = System.nanoTime()
114115
val duration = (after - before).nanos
115116
(duration, result)
117+
118+
/** Prints the code and result of the expression to the standard output. Equivalent to `println(xAsCode + " = " + x)`.
119+
*
120+
* @example
121+
* {{{
122+
* val a = "x"
123+
* debug(a.toUpperCase + "y")
124+
*
125+
* // prints: a.toUpperCase().+("y") = Xy
126+
* }}}
127+
*/
128+
inline def debug[T](inline x: T): Unit = ${ debugImpl('x) }
129+
private def debugImpl[T: Type](x: Expr[T])(using qctx: Quotes): Expr[Unit] =
130+
import qctx.reflect.*
131+
val xAsCode = x.asTerm.show(using Printer.TreeShortCode)
132+
'{ println(${ Expr(xAsCode) } + " = " + $x) }

doc/utils/utility.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ Top-level methods:
99
* `uninterruptible { ... }` evaluates the given code block making sure it can't be interrupted
1010
* `sleep(scala.concurrent.Duration)` blocks the current thread/fork for the given duration; same as `Thread.sleep`, but
1111
using's Scala's `Duration`
12+
* `debug(expression)` prints the code representing the expression, and the value of the expression to standard output,
13+
using `println`
1214

1315
Extension functions on arbitrary expressions:
1416

0 commit comments

Comments
 (0)