0 | module Language.Reflection.Expr
  1 |
  2 | import public Control.Applicative.Const -- public due to compiler's bug #2439
  3 |
  4 | import public Data.Bits -- public due to compiler's bug #2439
  5 | import public Data.Cozippable -- public due to compiler's bug #2439
  6 | import public Data.Fin.Set
  7 | import public Data.Fin.ToFin -- public due to compiler's bug #2439
  8 | import public Data.List.Ex -- public due to compiler's bug #2439
  9 | import public Data.List.Quantifiers
 10 | import public Data.SortedSet
 11 | import public Data.These -- public due to compiler's bug #2439
 12 | import public Data.Vect.Dependent
 13 |
 14 | import public Language.Reflection
 15 | import public Language.Reflection.Syntax
 16 | import Language.Reflection.Syntax.Ops
 17 |
 18 | import public Syntax.IHateParens.List
 19 |
 20 | %default total
 21 |
 22 | --------------------------
 23 | --- Namedness property ---
 24 | --------------------------
 25 |
 26 | public export
 27 | data IsNamedArg : Arg -> Type where
 28 |   ItIsNamed : IsNamedArg $ MkArg cnt pii (Just n) ty
 29 |
 30 | public export
 31 | isNamedArg : (arg : Arg) -> Dec $ IsNamedArg arg
 32 | isNamedArg (MkArg count piInfo (Just x) type) = Yes ItIsNamed
 33 | isNamedArg (MkArg count piInfo Nothing type)  = No $ \case ItIsNamed impossible
 34 |
 35 | ------------------------------------
 36 | --- General pure transformations ---
 37 | ------------------------------------
 38 |
 39 | public export
 40 | stname : Maybe Name -> Name
 41 | stname = fromMaybe $ UN Underscore
 42 |
 43 | public export
 44 | argName : (a : Arg) -> (0 _ : IsNamedArg a) => Name
 45 | argName (MkArg _ _ Nothing _) impossible
 46 | argName (MkArg _ _ (Just x) _) = x
 47 |
 48 | public export
 49 | argName' : Arg -> Name
 50 | argName' = stname . (.name)
 51 |
 52 | export
 53 | cleanupNamedHoles : TTImp -> TTImp
 54 | cleanupNamedHoles = mapTTImp substHoles . mapTTImp cleanApps where
 55 |                     -- There are two traversals because the second one contains a subexpr of the first, so they interfere.
 56 |   cleanApps : TTImp -> TTImp
 57 |   cleanApps $ IAutoApp  _ e   $ IHole {} = e
 58 |   cleanApps $ INamedApp _ e _ $ IHole {} = e
 59 |   cleanApps e = e
 60 |
 61 |   substHoles : TTImp -> TTImp
 62 |   substHoles $ IHole {} = implicitFalse
 63 |   substHoles e = e
 64 |
 65 | ||| Run `cleanupNamedHoles` over all `Arg`'s `TTImp`s
 66 | public export
 67 | cleanupArg : Arg -> Arg
 68 | cleanupArg = { type $= cleanupNamedHoles, piInfo $= map cleanupNamedHoles }
 69 |
 70 | export
 71 | argNames : (l : List Arg) -> (0 _ : All IsNamedArg l) => List Name
 72 | argNames [] = []
 73 | argNames (x :: xs) @{_ :: _} = Expr.argName x :: argNames xs
 74 |
 75 | ----------------------------------------------
 76 | --- Compiler-based `TTImp` transformations ---
 77 | ----------------------------------------------
 78 |
 79 | export
 80 | normaliseAs' : Elaboration m =>
 81 |                (0 expected : Type) ->
 82 |                (preProcess : TTImp -> TTImp) ->
 83 |                {0 resulting : _} -> (0 postProcess : (x : expected) -> resulting x) ->
 84 |                TTImp -> m TTImp
 85 | normaliseAs' expected pre post expr = do
 86 |   let expr = cleanupNamedHoles expr
 87 |   expr' <- quote $ post !(check {expected} $ pre expr)
 88 |   let (args, _) = unPi expr
 89 |   let (args', ty) = unPi expr'
 90 |   let args'' = comergeWith (\pre => {name := pre.name}) args args'
 91 |   pure $ piAll ty args''
 92 |
 93 | public export %inline
 94 | normaliseAs : Elaboration m => (0 expected : Type) -> TTImp -> m TTImp
 95 | normaliseAs ty = normaliseAs' ty id id
 96 |
 97 | -- Normalises expression of any type; it is known to struggle with `let`s
 98 | public export %inline
 99 | normalise : Elaboration m => TTImp -> m TTImp
100 | normalise = normaliseAs' (ty ** ty) (\expr => `((_ ** ~expr))) snd
101 |
102 | -- More precise normalisation of type expressions
103 | public export %inline
104 | normaliseAsType : Elaboration m => TTImp -> m TTImp
105 | normaliseAsType = normaliseAs Type
106 |
107 | ------------------------------------------------------------------------
108 | --- Facilities for managing any kind of function application at once ---
109 | ------------------------------------------------------------------------
110 |
111 | public export
112 | data AnyApp
113 |   = PosApp TTImp
114 |   | NamedApp Name TTImp
115 |   | AutoApp TTImp
116 |   | WithApp TTImp
117 |
118 | public export
119 | appArg : Arg -> TTImp -> AnyApp
120 | appArg (MkArg {piInfo=ExplicitArg, _})         expr = PosApp expr
121 | appArg (MkArg {piInfo=ImplicitArg, name, _})   expr = NamedApp (stname name) expr
122 | appArg (MkArg {piInfo=DefImplicit _, name, _}) expr = NamedApp (stname name) expr
123 | appArg (MkArg {piInfo=AutoImplicit, _})        expr = AutoApp expr
124 |
125 | public export
126 | getExpr : AnyApp -> TTImp
127 | getExpr $ PosApp e     = e
128 | getExpr $ NamedApp _ e = e
129 | getExpr $ AutoApp e    = e
130 | getExpr $ WithApp e    = e
131 |
132 | -- Shallow expression mapping
133 | public export
134 | mapExpr : (TTImp -> TTImp) -> AnyApp -> AnyApp
135 | mapExpr f $ PosApp e     = PosApp $ f e
136 | mapExpr f $ NamedApp n e = NamedApp n $ f e
137 | mapExpr f $ AutoApp e    = AutoApp $ f e
138 | mapExpr f $ WithApp e    = WithApp $ f e
139 |
140 | public export
141 | unAppAny : TTImp -> (TTImp, List AnyApp)
142 | unAppAny = runTR [] where
143 |   runTR : List AnyApp -> TTImp -> (TTImp, List AnyApp)
144 |   runTR curr $ IApp      _ lhs   rhs = runTR (PosApp rhs     :: curr) lhs
145 |   runTR curr $ INamedApp _ lhs n rhs = runTR (NamedApp n rhs :: curr) lhs
146 |   runTR curr $ IAutoApp  _ lhs   rhs = runTR (AutoApp rhs    :: curr) lhs
147 |   runTR curr $ IWithApp  _ lhs   rhs = runTR (WithApp rhs    :: curr) lhs
148 |   runTR curr lhs                     = (lhs, curr)
149 |
150 | public export
151 | reAppAny1 : TTImp -> AnyApp -> TTImp
152 | reAppAny1 l $ PosApp e     = app l e
153 | reAppAny1 l $ NamedApp n e = namedApp l n e
154 | reAppAny1 l $ AutoApp e    = autoApp l e
155 | reAppAny1 l $ WithApp e    = IWithApp EmptyFC l e
156 |
157 | public export %inline
158 | reAppAny : Foldable f => TTImp -> f AnyApp -> TTImp
159 | reAppAny = foldl reAppAny1
160 |
161 | ----------------------------------------------------------------------------
162 | --- Facilities for managing argument values in function application expr ---
163 | ----------------------------------------------------------------------------
164 |
165 | ||| All argument values applied in an expression
166 | |||
167 | ||| Used for convenience when traversing given arguments and their types
168 | public export
169 | record AllApps where
170 |   constructor MkAllApps
171 |   explicitArgs : List TTImp
172 |   autoArgs : List TTImp
173 |   namedArgs : SortedMap Name TTImp
174 |
175 | ||| Insert an `AnyApp` into `AllApps`
176 | public export
177 | addApp : AnyApp -> AllApps -> AllApps
178 | addApp (PosApp s) = {explicitArgs $= (s ::)}
179 | addApp (NamedApp nm s) = {namedArgs $= insert nm s}
180 | addApp (AutoApp s) = {autoArgs $= (s ::)}
181 | addApp (WithApp s) = id
182 |
183 | ||| Make an `AllApps` out of a list of `AnyApp`
184 | |||
185 | ||| Used in conjunction with `unAppAny`
186 | public export
187 | mkAllApps : List AnyApp -> AllApps
188 | mkAllApps laa = foldl (flip addApp) (MkAllApps [] [] empty) $ reverse laa
189 |
190 | ||| Pop a value from `AllApps` by argument name
191 | |||
192 | ||| The argument/value is returned from `AllApps`
193 | public export
194 | popNamed : Maybe Name -> AllApps -> Maybe (TTImp, AllApps)
195 | popNamed Nothing ap = Nothing
196 | popNamed (Just x) ap =
197 |   case lookup x ap.namedArgs of
198 |     Nothing => Nothing
199 |     Just t => Just (t, {namedArgs $= delete x} ap)
200 |
201 | ||| Pop an argument value from `AllApps`, returning Nothing if no value is given
202 | |||
203 | ||| The argument/value is returned from `AllApps`
204 | public export
205 | popArgVal : Arg -> AllApps -> Maybe (TTImp, AllApps)
206 | popArgVal (MkArg _ ImplicitArg name _) ap = popNamed name ap
207 | popArgVal (MkArg _ ExplicitArg name _) (MkAllApps (x :: xs) autoArgs namedArgs) = Just (x, MkAllApps xs autoArgs namedArgs)
208 | popArgVal (MkArg _ ExplicitArg name _) ap = popNamed name ap
209 | popArgVal (MkArg _ AutoImplicit name _) (MkAllApps explicitArgs (x :: xs) namedArgs) = Just (x, MkAllApps explicitArgs xs namedArgs)
210 | popArgVal (MkArg _ AutoImplicit name _) ap = popNamed name ap
211 | popArgVal (MkArg _ (DefImplicit x) Nothing _) ap = Just (x, ap)
212 | popArgVal (MkArg _ (DefImplicit x) (Just n) _) ap =
213 |   case lookup n ap.namedArgs of
214 |     Nothing => Just (x, ap)
215 |     Just t => Just (t , {namedArgs $= delete n} ap)
216 |
217 | ||| Extract given values of arguments from `AllApps`
218 | public export
219 | popArgVals : List Arg -> AllApps -> List (Maybe TTImp)
220 | popArgVals [] aa = []
221 | popArgVals (x :: xs) aa = do
222 |   let pav = popArgVal x aa
223 |   let mr = fst <$> pav
224 |   let aa = fromMaybe aa $ snd <$> pav
225 |   mr :: popArgVals xs aa
226 |
227 | ---------------------------------------
228 | --- Building of special expressions ---
229 | ---------------------------------------
230 |
231 | ||| Lifts the given foldable of elements to an expression of a list-like data type
232 | public export
233 | liftList : Foldable f => f TTImp -> TTImp
234 | liftList = foldr (\l, r => `(~l :: ~r)) `([])
235 |
236 | ||| Lifts the given foldable of elements to an expression of `Prelude.List`
237 | public export
238 | liftList' : Foldable f => f TTImp -> TTImp
239 | liftList' = foldr (\l, r => `(Prelude.(::) ~l ~r)) `(Prelude.Nil)
240 |
241 | -- Apply syntactically, optimise if LHS is `ILam`.
242 | -- This implementation does not take shadowing into account.
243 | -- Also, currently, the type of lambda argument is not used in the final expression, this can break typechecking in complex cases.
244 | public export
245 | applySyn : TTImp -> TTImp -> TTImp
246 | applySyn (ILam _ _ _ Nothing  _ lamExpr) _ = lamExpr
247 | applySyn (ILam _ _ _ (Just n) _ lamExpr) rhs = mapTTImp (\case orig@(IVar _ n') => if n == n' then rhs else orig; e => e) lamExpr
248 | applySyn lhs rhs = lhs `app` rhs
249 |
250 | --- `DPair` type parsing and rebuilding stuff ---
251 |
252 | public export
253 | unDPair : TTImp -> (List Arg, TTImp)
254 | unDPair (IApp _ (IApp _ (IVar _ `{Builtin.DPair.DPair}) typ) (ILam _ cnt piInfo mbname _ lamTy)) =
255 |     mapFst (MkArg cnt piInfo mbname typ ::) $ unDPair lamTy
256 | unDPair expr = ([], expr)
257 |
258 | public export
259 | unDPairUnAlt : TTImp -> Maybe (List Arg, TTImp)
260 | unDPairUnAlt (IAlternative _ _ alts) = case filter (not . null . Builtin.fst) $ unDPair <$> alts of
261 |   [x] => Just x
262 |   _   => Nothing
263 | unDPairUnAlt x = Just $ unDPair x
264 |
265 | public export
266 | buildDPair : (rhs : TTImp) -> List (Name, TTImp) -> TTImp
267 | buildDPair = foldr $ \(name, type), res =>
268 |   var `{Builtin.DPair.DPair} .$ type .$ lam (MkArg MW ExplicitArg (Just name) type) res
269 |
270 | -----------------------------------------------------
271 | --- Analysis of pieces inside `TTImp` expressions ---
272 | -----------------------------------------------------
273 |
274 | ||| Returns unnamespaced name and list of all namespaces stored in direct order
275 | |||
276 | ||| Say, for `Data.Vect.Vect` it would return (["Data", "Vect"], `{Vect}).
277 | export
278 | unNS : Name -> (List String, Name)
279 | unNS (NS (MkNS revNSs) nm) = mapFst (reverse revNSs ++) $ unNS nm
280 | unNS (DN _ nm)             = unNS nm
281 | unNS nm                    = ([], nm)
282 |
283 | ||| Returns all names that are suffixes of a given name (including the original name itself).
284 | |||
285 | ||| For example, for the name `Data.Vect.Vect` suffixes set would include
286 | ||| `Data.Vect.Vect`, `Vect.Vect` and `Vect`.
287 | export
288 | allNameSuffixes : Name -> List Name
289 | allNameSuffixes nm = do
290 |   let (nss, n) = unNS nm
291 |   tails nss <&> \case
292 |     [] => n
293 |     ns => NS (MkNS $ reverse ns) n
294 |
295 | export
296 | isNamespaced : Name -> Bool
297 | isNamespaced = not . null . fst . unNS
298 |
299 | public export
300 | isImplicit : PiInfo c -> Bool
301 | isImplicit ImplicitArg     = True
302 | isImplicit (DefImplicit x) = True
303 | isImplicit AutoImplicit    = True
304 | isImplicit ExplicitArg     = False
305 |
306 | -------------------------------------------------
307 | --- Syntactic analysis of `TTImp` expressions ---
308 | -------------------------------------------------
309 |
310 | public export
311 | isSameTypeAs : Name -> Name -> Elab Bool
312 | isSameTypeAs n m = let eq = (==) `on` fst in [| lookupName n `eq` lookupName m |]
313 |
314 | export
315 | nameConformsTo : (cand, origin : Name) -> Bool
316 | nameConformsTo cand origin = do
317 |   let (cns, cn) = simplify cand
318 |   let (ons, on) = simplify origin
319 |   cn == on && (cns `isPrefixOf` ons) -- notice that namespaces are stored in the reverse order
320 |   where
321 |     simplify : Name -> (List String, Name)
322 |     simplify (NS (MkNS ns) nm) = mapFst (++ ns) $ simplify nm
323 |     simplify (DN _ nm)         = simplify nm
324 |     simplify x                 = ([], x)
325 |
326 | 0 nct_corr_eq : nameConformsTo `{A.B.c} `{A.B.c} = True;  nct_corr_eq = Refl
327 | 0 nct_corr_le : nameConformsTo `{B.c}   `{A.B.c} = True;  nct_corr_le = Refl
328 | 0 nct_corr_ge : nameConformsTo `{A.B.c} `{B.c}   = False; nct_corr_ge = Refl
329 |
330 | -- simple syntactic search of a `IVar`, disregarding shadowing or whatever
331 | export
332 | allVarNames' : TTImp -> SortedSet Name
333 | allVarNames' = runConst . mapATTImp' f where
334 |   f : TTImp -> Const (SortedSet Name) TTImp -> Const (SortedSet Name) TTImp
335 |   f (IVar _ n) = const $ MkConst $ singleton n
336 |   f _          = id
337 |
338 | -- Same as `allVarNames'`, but returning `List`
339 | export
340 | allVarNames : TTImp -> List Name
341 | allVarNames = Prelude.toList . allVarNames'
342 |
343 | public export
344 | isVar : TTImp -> Bool
345 | isVar $ IVar {} = True
346 | isVar _         = False
347 |
348 | public export
349 | 0 ArgDeps : Nat -> Type
350 | ArgDeps n = DVect n $ FinSet . Fin.finToNat
351 |
352 | export
353 | argDeps : (args : List Arg) -> ArgDeps args.length
354 | argDeps args = do
355 |   let nameToIndices = SortedMap.fromList $ mapI args $ \i, arg => (argName' arg, Fin.Set.singleton i)
356 |   let args = Vect.fromList args <&> \arg => allVarNames arg.type <&> fromMaybe empty . lookup' nameToIndices
357 |   flip upmapI args $ \i, deps => flip concatMap deps $ \candidates =>
358 |     maybe empty singleton $ last' $ mapMaybe tryToFit $ Fin.Set.toList candidates
359 |
360 | export
361 | dependees : (args : List Arg) -> FinSet args.length
362 | dependees args = do
363 |   let nameToIndex = SortedMap.fromList $ mapI args $ \i, arg => (argName' arg, i)
364 |   let varsInTypes = concatMap (\arg => allVarNames' arg.type) args
365 |   fromList $ mapMaybe (lookup' nameToIndex) $ Prelude.toList varsInTypes
366 |
367 | namespace UpToRenaming
368 |
369 |   mutual
370 |
371 |     compWithSubst : (subst : List $ These Name Name) => (from, to : Maybe Name) -> TTImp -> TTImp -> Bool
372 |     compWithSubst (Just n) (Just n') e e' = n == n' && (e == e') @{UpToSubst} || (e == e') @{UpToSubst @{Both n n' :: subst}}
373 |     compWithSubst (Just n) Nothing   e e' = (e == e') @{UpToSubst @{This n  :: subst}}
374 |     compWithSubst Nothing  (Just n') e e' = (e == e') @{UpToSubst @{That n' :: subst}}
375 |     compWithSubst Nothing  Nothing   e e' = (e == e') @{UpToSubst}
376 |
377 |     [UpToSubst] (subst : List $ These Name Name) => Eq TTImp where
378 |       IVar _ v == IVar _ v' = maybe (v == v') (== Both v v') $ flip find subst $ \ior => fromThis ior == Just v || fromThat ior == Just v'
379 |       IPi _ c i n a r == IPi _ c' i' n' a' r' =
380 |         c == c' && (assert_total $ i == i') && a == a' && (assert_total $ compWithSubst n n' r r')
381 |       ILam _ c i n a r == ILam _ c' i' n' a' r' =
382 |         c == c' && (assert_total $ i == i') && a == a' && (assert_total $ compWithSubst n n' r r')
383 |       ILet _ _ c n ty val s == ILet _ _ c' n' ty' val' s' =
384 |         c == c' && ty == ty' && val == val' && (assert_total $ compWithSubst (Just n) (Just n') s s')
385 |
386 |       ICase _ os t ty cs == ICase _ os' t' ty' cs' =
387 |         t == t' && (assert_total $ os == os') && ty == ty' && (assert_total $ cs == cs')
388 |       ILocal _ ds e == ILocal _ ds' e' =
389 |         (assert_total $ ds == ds') && e == e'
390 |       IUpdate _ fs t == IUpdate _ fs' t' =
391 |         (assert_total $ fs == fs') && t == t'
392 |
393 |       IApp _ f x == IApp _ f' x' = f == f' && x == x'
394 |       INamedApp _ f n x == INamedApp _ f' n' x' =
395 |         f == f' && n == n' && x == x'
396 |       IAutoApp _ f x == IAutoApp _ f' x' = f == f' && x == x'
397 |       IWithApp _ f x == IWithApp _ f' x' = f == f' && x == x'
398 |
399 |       ISearch _ n == ISearch _ n' = n == n'
400 |       IAlternative _ t as == IAlternative _ t' as' =
401 |         (assert_total $ t == t') && (assert_total $ as == as')
402 |       IRewrite _ p q == IRewrite _ p' q' =
403 |         p == p' && q == q'
404 |
405 |       IBindHere _ m t == IBindHere _ m' t' =
406 |         m == m' && t == t'
407 |       IBindVar _ s == IBindVar _ s' = s == s'
408 |       IAs _ _ u n t == IAs _ _ u' n' t' =
409 |         u == u' && n == n' && t == t'
410 |       IMustUnify _ r t == IMustUnify _ r' t' =
411 |         r == r' && t == t'
412 |
413 |       IDelayed _ r t == IDelayed _ r' t' = r == r' && t == t'
414 |       IDelay _ t == IDelay _ t' = t == t'
415 |       IForce _ t == IForce _ t' = t == t'
416 |
417 |       IQuote _ tm == IQuote _ tm' = tm == tm'
418 |       IQuoteName _ n == IQuoteName _ n' = n == n'
419 |       IQuoteDecl _ ds == IQuoteDecl _ ds' = assert_total $ ds == ds'
420 |       IUnquote _ tm == IUnquote _ tm' = tm == tm'
421 |
422 |       IPrimVal _ c == IPrimVal _ c' = c == c'
423 |       IType _ == IType _ = True
424 |       IHole _ s == IHole _ s' = True -- Holes are anyway unique and does not matter what the names are.
425 |
426 |       Implicit _ b == Implicit _ b' = b == b'
427 |       IWithUnambigNames _ ns t == IWithUnambigNames _ ns' t' =
428 |         map snd ns == map snd ns' && t == t'
429 |
430 |       _ == _ = False
431 |
432 |   export
433 |   [UpToRenaming] Eq TTImp where
434 |     x == y = (x == y) @{UpToSubst @{empty}}
435 |