Skip to content

macros.md: Documentation does not match example #12110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions docs/docs/reference/metaprogramming/macros.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,22 +186,24 @@ Expr.betaReduce(_): Expr[(T1, ..., Tn) => R] => ((Expr[T1], ..., Expr[Tn]) => Ex
Types are not directly affected by the phase consistency principle.
It is possible to use types defined at any level in any other level.
But, if a type is used in a subsequent stage it will need to be lifted to a `Type`.
The resulting value of `Type` will be subject to PCP.
Indeed, the definition of `to` above uses `T` in the next stage, there is a
quote but no splice between the parameter binding of `T` and its
usage. But the code can be rewritten by adding a binding of a `Type[T]` tag:
usage. But the code can be rewritten by adding an explicit binding of a `Type[T]`:

```scala
def to[T, R](f: Expr[T] => Expr[R])(using Type[T], Type[R], Quotes): Expr[T => R] =
'{ (x: T) => ${ f('x) } }
def to[T, R](f: Expr[T] => Expr[R])(using t: Type[T])(using Type[R], Quotes): Expr[T => R] =
'{ (x: t.Underlying) => ${ f('x) } }
```

In this version of `to`, the type of `x` is now the result of
splicing the `Type` value `t`. This operation _is_ splice correct -- there
is one quote and one splice between the use of `t` and its definition.
inserting the type `Type[T]` and selecting its `Underlying`.

To avoid clutter, the compiler converts any type reference to
a type `T` in subsequent phases to `summon[Type[T]].Underlying`.

And to avoid duplication it does it once per type, and creates
an alias for that type at the start of the quote.

To avoid clutter, the Scala implementation tries to convert any type
reference to a type `T` in subsequent phases to a type-splice, by rewriting `T` to `summon[Type[T]].Underlying`.
For instance, the user-level definition of `to`:

```scala
Expand All @@ -213,7 +215,10 @@ would be rewritten to

```scala
def to[T, R](f: Expr[T] => Expr[R])(using t: Type[T], r: Type[R])(using Quotes): Expr[T => R] =
'{ (x: t.Underlying) => ${ f('x) } }
'{
type T = t.Underlying
(x: T) => ${ f('x) }
}
```

The `summon` query succeeds because there is a given instance of
Expand Down