0 | ||| Specialisation task type and functions using it
  1 | module Deriving.SpecialiseData.Task
  2 |
  3 | import public Control.Monad.Error.Interface
  4 | import public Data.DPair -- workaround for idris-lang/Idris2#2439
  5 | import Deriving.SpecialiseData.Common
  6 | import Deriving.SpecialiseData.Helpers
  7 | import Deriving.SpecialiseData.Utils.TypeInfo
  8 | import Language.Reflection.Compat
  9 | import public Language.Reflection.Compat.TypeInfo
 10 | import Language.Reflection.Expr
 11 | import Language.Reflection.Expr.VarSubst
 12 | import public Language.Reflection.Logging
 13 |
 14 | --------------------------------
 15 | --- SPECIALISATION TASK TYPE ---
 16 | --------------------------------
 17 |
 18 | ||| Specialisation task
 19 | public export
 20 | record SpecTask where
 21 |   constructor MkSpecTask
 22 |   ||| Full unification task
 23 |   tqLambda            : TTImp
 24 |   tqArgs              : List Arg
 25 |   tqRet               : TTImp
 26 |   {auto 0 tqArgsNamed : All IsNamedArg tqArgs}
 27 |   ||| Unification task type
 28 |   ttArgs              : List Arg
 29 |   {auto 0 ttArgsNamed : All IsNamedArg ttArgs}
 30 |   ||| Namespace in which specialiseData was called
 31 |   currentNs           : Namespace
 32 |   ||| Name of specialised type
 33 |   resultName          : Name
 34 |   ||| Invocation of polymorphic type extracted from unification task
 35 |   fullInvocation      : TTImp
 36 |   ||| Invocation of specialised type given default arguents
 37 |   specInvocation      : TTImp
 38 |   ||| Polymorphic type's TypeInfo
 39 |   polyTy              : TypeInfo
 40 |   ||| Proof that all the constructors of the polymorphic type are named
 41 |   {auto 0 polyTyNamed : AllTyArgsNamed polyTy}
 42 |
 43 | export
 44 | Show SpecTask where
 45 |   showPrec p t =
 46 |     showCon p "SpecTask" $ joinBy "" $
 47 |       [ showArg t.tqLambda
 48 |       , showArg t.tqArgs
 49 |       , showArg t.tqRet
 50 |       , showArg t.ttArgs
 51 |       , showArg t.currentNs
 52 |       , showArg t.resultName
 53 |       , showArg t.fullInvocation
 54 |       , showArg t.specInvocation
 55 |       , showArg "<polyTy>"
 56 |       ]
 57 |
 58 | export
 59 | LogPosition SpecTask where
 60 |   logPosition st = "(\{show st.tqLambda})"
 61 |
 62 | ---------------------
 63 | --- TASK ANALYSIS ---
 64 | ---------------------
 65 |
 66 | ||| Given a list of arguments and a sorted set of names,
 67 | ||| assert that every argument's name is in that set
 68 | checkArgsUse : MonadError SpecialisationError m => List Arg -> SortedSet Name -> m ()
 69 | checkArgsUse [] _ = pure ()
 70 | checkArgsUse (x :: xs) t = do
 71 |   let Just n = x.name
 72 |   | _ => checkArgsUse xs t
 73 |   if contains n t
 74 |     then checkArgsUse xs t
 75 |     else throwError UnusedVarError
 76 |
 77 | ||| Given a list of arguments and a list of their aliases, apply aliases to then
 78 | applyArgAliases :
 79 |   (as : List Arg) ->
 80 |   (0 _ : All IsNamedArg as) =>
 81 |   List (Name, Name) ->
 82 |   SortedMap Name TTImp ->
 83 |   Subset (List Arg) (All IsNamedArg)
 84 | applyArgAliases []        @{[]}     _  _   = Element [] []
 85 | applyArgAliases (x :: xs) @{_ :: _} ys ins = do
 86 |   let (newIns, newName, ys) : (SortedMap _ _, Name, List (Name, Name)) =
 87 |     case ys of
 88 |        []              => (ins                  , argName x, [])
 89 |        ((y, y') :: ys) => (insert y (var y') ins, y'       , ys)
 90 |   let Element rec prec = applyArgAliases xs ys newIns
 91 |   Element
 92 |     (MkArg x.count x.piInfo (Just newName) (substituteVariables newIns x.type) :: rec)
 93 |     (ItIsNamed :: prec)
 94 |
 95 | ||| Given a list of arguments, generate a list of aliased arguments
 96 | ||| and a list of aliases
 97 | transformArgNames :
 98 |   (f : Name -> Name) ->
 99 |   (as : List Arg) ->
100 |   (0 _ : All IsNamedArg as) =>
101 |   (Subset (List Arg) (All IsNamedArg), List (Name, Name))
102 | transformArgNames f as = do
103 |   let aliases = pushIn as %search <&> \(x `Element` xN) => (argName x, f $ Expr.argName x @{xN})
104 |   (applyArgAliases as aliases empty, aliases)
105 |
106 | inGenNSImpl : Namespace -> Name -> Name -> Name
107 | inGenNSImpl (MkNS strs) p n = do
108 |   let newNS =
109 |     case n of
110 |         (NS (MkNS subs) n) => subs
111 |         n => []
112 |   NS (MkNS $ newNS ++ show p :: strs) $ dropNS n
113 |
114 | ||| Prepend namespace into which everything is generated to name
115 | export
116 | inGenNS : SpecTask -> Name -> Name
117 | inGenNS task = inGenNSImpl task.currentNs task.resultName
118 |
119 |
120 | ||| Get all the information needed for specialisation from task
121 | export
122 | getTask :
123 |   Monad m =>
124 |   NamespaceProvider m =>
125 |   MonadError SpecialisationError m =>
126 |   NamesInfoInTypes =>
127 |   (resultName : Name) ->
128 |   (resultKind : TTImp) ->
129 |   (resultContent : TTImp) ->
130 |   m SpecTask
131 | getTask resultName resultKind resultContent = do
132 |   let (tqArgs, tqRet) = unLambda resultContent
133 |   -- Check for unused arguments
134 |   checkArgsUse tqArgs $ usesVariables tqRet
135 |   -- Extract name of polymorphic type
136 |   let (IVar _ typeName, _) = Expr.unAppAny tqRet
137 |   | _ => throwError TaskTypeExtractionError
138 |   -- Prove that all spec lambda arguments are named
139 |   let Yes tqArgsNamed = all isNamedArg tqArgs
140 |   | _ => throwError UnnamedArgInLambdaError
141 |   -- Create aliases for spec lambda's arguments and perform substitution
142 |   let (Element tqArgs tqArgsNamed, tqAlias) = transformArgNames (prependS "fv^\{resultName}^") tqArgs
143 |   let tqRet = substituteVariables (fromList $ mapSnd var <$> tqAlias) tqRet
144 |   let (ttArgs, _) = unPi resultKind
145 |   -- Check for partial application in spec
146 |   let True = (length tqArgs == length ttArgs)
147 |   | _ => throwError PartialSpecError
148 |   -- Prove that all spec lambda type's arguments are named
149 |   let Yes ttArgsNamed = all isNamedArg ttArgs
150 |   | _ => throwError UnnamedArgInLambdaError
151 |   -- Apply aliasing to spec lambda type's info
152 |   let Element ttArgs ttArgsNamed = applyArgAliases ttArgs tqAlias empty
153 |   -- Get current namespace
154 |   currentNs <- provideNS
155 |   -- Get polymorphic type's info
156 |   let Just polyTy = lookupType typeName
157 |   | _ => throwError $ MissingTypeInfoError typeName
158 |   -- Prove all its arguments/constructors/constructor arguments are named
159 |   let Yes polyTyNamed = areAllTyArgsNamed polyTy
160 |     | No _ => throwError $ UnnamedArgInPolyTyError polyTy.name
161 |   let specInvocation = reAppAny
162 |           (var (inGenNSImpl currentNs (snd $ unNS $ resultName) (snd $ unNS $ resultName))) $
163 |             ttArgs.appsWith @{ttArgsNamed} var empty
164 |   pure $ MkSpecTask
165 |     { tqLambda = resultContent
166 |     , tqArgs
167 |     , tqRet
168 |     , tqArgsNamed
169 |     , ttArgs
170 |     , ttArgsNamed
171 |     , currentNs
172 |     , resultName = snd $ unNS resultName
173 |     , fullInvocation = tqRet --- TODO: intelligent full invocation
174 |     , specInvocation
175 |     , polyTy
176 |     , polyTyNamed
177 |     }
178 |
179 |
180 | ||| Generate IPi with implicit type arguments and given return
181 | export
182 | forallMTArgs : SpecTask -> TTImp -> TTImp
183 | forallMTArgs t = flip (foldr pi) $ makeTypeArgM0 . hideExplicitArg <$> t.ttArgs
184 |
185 | export
186 | applyMTArgs : SpecTask -> TTImp -> TTImp
187 | applyMTArgs t =
188 |   flip (foldl (\x,arg => x .! (fromMaybe "" arg.name, var $ fromMaybe "" arg.name))) $
189 |     makeTypeArgM0 . hideExplicitArg <$> t.ttArgs
190 |