Skip to content

Commit 5f0d35e

Browse files
committed
Fixes to the assertImpl example
Make sure `assertImpl` prints the tested expression rather than its result.
1 parent 26682ab commit 5f0d35e

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

docs/docs/reference/symmetric-meta-programming.md

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ prints it again in an error message if it evaluates to `false`.
3232
~ assertImpl(’(expr))
3333

3434
def assertImpl(expr: Expr[Boolean]) =
35-
’{ if !(~expr) then throw new AssertionError(s"failed assertion: ${~expr.toString}") }
36-
35+
’{ if !(~expr) then throw new AssertionError(s"failed assertion: ${~showExpr(expr)}") }
3736

3837
If `e` is an expression, then `’(e)` or `’{e}` represent the typed
3938
abstract syntax tree representing `e`. If `T` is a type, then `’[T]`
@@ -532,15 +531,12 @@ In the end, `Liftable` resembles very much a serialization
532531
framework. Like the latter it can be derived systematically for all
533532
collections, case classes and enums.
534533

535-
In fact, the initial example of assertions also uses a lifting conversion under the hood.
536-
Recall the failure clause:
534+
Using lifting, we can now give the missing definition of `showExpr` in the introductory example:
537535

538-
throw new AssertionError(s"failed assertion: ${~expr.toString}") }
536+
def showExpr[T](expr: Expr[T]): Expr[String] = expr.toString
539537

540-
Here, `expr.toString` yields `expr`'s representation in String form. That string
541-
is lifted to an `Expr[String]` since the required type of a splice argument is an `Expr`.
542-
The lifted result is then spliced in into the `AssertionError` argument, giving
543-
back again the original string representation of `expr`.
538+
That is, the `showExpr` method converts its `Expr` argument to a string, and lifts
539+
the result back to an `Expr[String]` using the implicit `toExpr` conversion.
544540

545541
## Implementation
546542

tests/pos/quote-0.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ class Test {
99
~ assertImpl('(expr))
1010

1111
def assertImpl(expr: Expr[Boolean]) =
12-
'{ if !(~expr) then throw new AssertionError(s"failed assertion: ${~expr}") }
12+
'{ if !(~expr) then throw new AssertionError(s"failed assertion: ${~showExpr(expr)}") }
13+
14+
def showExpr[T](expr: Expr[T]): Expr[String] = expr.toString
1315

1416
inline def power(inline n: Int, x: Double) = ~powerCode(n, '(x))
1517

0 commit comments

Comments
 (0)