summaryrefslogtreecommitdiff
path: root/testsuite/tests/tcplugins/ArgsPlugin.hs
blob: cb193db05b909de0e79e9cb21cf890f2bf4a8919 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
{-# LANGUAGE RecordWildCards #-}

module ArgsPlugin where

-- base
import Data.Maybe
  ( catMaybes )

-- ghc
import GHC.Builtin.Types
  ( integerTy )
import GHC.Core
  ( Expr(Type) )
import GHC.Core.Class
  ( Class(..) )
import GHC.Core.DataCon
  ( classDataCon )
import GHC.Core.Make
  ( mkCoreConApps, mkIntegerExpr )
import GHC.Core.Type
  ( eqType )
import GHC.Plugins
  ( Plugin )
import GHC.Tc.Plugin
  ( TcPluginM, getTargetPlatform )
import GHC.Tc.Types
  ( TcPluginSolveResult(..) )
import GHC.Tc.Types.Constraint
  ( Ct(..) )
import GHC.Tc.Types.Evidence
  ( EvBindsVar, EvTerm(EvExpr) )
import GHC.Platform
  ( Platform )

-- common
import Common
  ( PluginDefs(..)
  , mkPlugin, don'tRewrite
  )

--------------------------------------------------------------------------------

-- This plugin solves Wanted constraints of the form "MyClass Integer",
-- and supplies evidence that depends on the arguments to the plugin.
--
-- To find such constraints, we traverse through the Wanteds provided
-- to the plugin to find those whose name matches that of "MyClass",
-- and check that it is applied to the type "Integer".
--
-- We then construct a dictionary which is the integer that was passed
-- as an argument to the plugin.

plugin :: Plugin
plugin = mkPlugin solver don'tRewrite

-- Solve "MyClass Integer" with a class dictionary that depends on
-- a plugin argument.
solver :: [String]
       -> PluginDefs -> EvBindsVar -> [Ct] -> [Ct]
       -> TcPluginM TcPluginSolveResult
solver args defs _ev _gs ws = do
  let
    argsVal :: Integer
    argsVal = case args of
      arg : _ -> read arg
      _       -> error "ArgsPlugin: expected at least one argument"
  platform <- getTargetPlatform
  solved <- catMaybes <$> traverse ( solveCt platform defs argsVal ) ws
  pure $ TcPluginOk solved []

solveCt :: Platform -> PluginDefs -> Integer -> Ct -> TcPluginM ( Maybe (EvTerm, Ct) )
solveCt platform ( PluginDefs {..} ) i ct@( CDictCan { cc_class, cc_tyargs } )
  | className cc_class == className myClass
  , [tyArg] <- cc_tyargs
  , tyArg `eqType` integerTy
  , let
      evTerm :: EvTerm
      evTerm = EvExpr $
        mkCoreConApps ( classDataCon cc_class )
         [ Type integerTy, mkIntegerExpr platform i ]
  = pure $ Just ( evTerm, ct )
solveCt _ _ _ ct = pure Nothing