File tree 4 files changed +70
-0
lines changed
4 files changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ import scala .quoted .*
2
+
3
+ object Macros :
4
+
5
+ inline def power (x : Double , inline n : Int ) = $ { powerCode(' x , ' n ) }
6
+
7
+ private def powerCode (x : Expr [Double ], n : Expr [Int ])(using Quotes ): Expr [Double ] =
8
+ unrolledPowerCode(x, n.valueOrError)
9
+
10
+ private def unrolledPowerCode (x : Expr [Double ], n : Int )(using Quotes ): Expr [Double ] =
11
+ if n == 0 then ' { 1.0 } // tests simple quotes without splices
12
+ else if n % 2 == 1 then ' { $x * $ { unrolledPowerCode(x, n - 1 ) } } // tests simple splices
13
+ else ' { val y = $x * $x; $ { unrolledPowerCode(' y , n / 2 ) } } // tests splice with term capture
14
+
15
+
16
+ inline def let [T , U ](x : T )(inline body : T => U ): U = $ { letCode(' x , ' body ) }
17
+
18
+ private def letCode [T : Type , U : Type ](x : Expr [T ], body : Expr [T => U ])(using Quotes ): Expr [U ] =
19
+ // tests use of Type
20
+ ' { val y : T = $x; $body(y): U }
Original file line number Diff line number Diff line change
1
+ import Macros .*
2
+
3
+ def powerTest (x : Double ): Unit =
4
+ power(x, 0 )
5
+ power(x, 1 )
6
+ power(x, 5 )
7
+ power(x, 10 )
8
+
9
+ def letTest : Unit =
10
+ let(0 ) { _ + 1 }
11
+ let(0 ) { _.toString }
12
+ let((4 , 'a' )) { _.swap }
13
+ let(new Foo ) { _.hashCode }
14
+
15
+ class Foo
Original file line number Diff line number Diff line change
1
+ import scala .quoted .*
2
+
3
+ object Macros :
4
+
5
+ inline def power (x : Double , inline n : Int ) = $ { powerCode(' x , ' n ) }
6
+
7
+ private def powerCode (x : Expr [Double ], n : Expr [Int ])(using Quotes ): Expr [Double ] =
8
+ unrolledPowerCode(x, n.valueOrError)
9
+
10
+ private def unrolledPowerCode (x : Expr [Double ], n : Int )(using Quotes ): Expr [Double ] =
11
+ if n == 0 then ' { 1.0 } // tests simple quotes without splices
12
+ else if n % 2 == 1 then ' { $x * $ { unrolledPowerCode(x, n - 1 ) } } // tests simple splices
13
+ else ' { val y = $x * $x; $ { unrolledPowerCode(' y , n / 2 ) } } // tests splice with term capture
14
+
15
+
16
+ inline def let [T , U ](x : T )(inline body : T => U ): U = $ { letCode(' x , ' body ) }
17
+
18
+ private def letCode [T : Type , U : Type ](x : Expr [T ], body : Expr [T => U ])(using Quotes ): Expr [U ] =
19
+ // tests use of Type
20
+ ' { val y : T = $x; $body(y): U }
Original file line number Diff line number Diff line change
1
+ import Macros .*
2
+
3
+ def powerTest (x : Double ): Unit =
4
+ power(x, 0 )
5
+ power(x, 1 )
6
+ power(x, 5 )
7
+ power(x, 10 )
8
+
9
+ def letTest : Unit =
10
+ let(0 ) { _ + 1 }
11
+ let(0 ) { _.toString }
12
+ let((4 , 'a' )) { _.swap }
13
+ let(new Foo ) { _.hashCode }
14
+
15
+ class Foo
You can’t perform that action at this time.
0 commit comments