ekmett / ekmett/reflection

Use `withDict` for `reify` & co.

Open
#44 7 comments 0 reactions 0 assignees View on GitHub
Dominant language
Haskell
Stars
105
Forks
24
PR merge metrics
No merged PRs in 30d

Description

I've found out today that ghc (since version 7.8) implements dictionary reification for type literals with the help of some compiler magic. For example (see [GHC.TypeLits](https://github.com/ghc/ghc/blob/4549cadf855d14a6b737ceddf4e474faf8e343ff/libraries/base/GHC/TypeLits.hs#L203-L210)):

```haskell
newtype SSymbol (s :: Symbol) = SSymbol String

data WrapS a b = WrapS (KnownSymbol a => Proxy a -> b)

-- See Note [magicDictId magic] in "basicType/MkId.hs"
withSSymbol :: (KnownSymbol a => Proxy a -> b)
-> SSymbol a -> Proxy a -> b
withSSymbol f x y = magicDict (WrapS f) x y
```
In a nutshell, the compiler magic is that there's a builtin rewrite rule that turns `magicDict (WrapS f) x y` into the moral equivalent of `f (coerce x) y` on the Core level, where dictionaries are represented as values (see [MkId:Note [magicDictId magic]](https://github.com/ghc/ghc/blob/4549cadf855d14a6b737ceddf4e474faf8e343ff/compiler/basicTypes/MkId.hs#L1630)). This is actually better than what we get with the `unsafeCoerce` trick: rather than coercing `f`, it merely coerces the dictionary itself, so `f` can potentially be optimized more.

In light of this advantage, would it make sense for `Data.Reflection` to use `magicDict` as well?

It should be possible to tackle this together with #26.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.