0 | module Syntax.StringDiagram.Arrow
  1 |
  2 | import public Control.Monad.State
  3 | import public Control.Applicative.Const
  4 | import public Control.Arrow
  5 | import public Control.Category.Core
  6 | import public Language.Reflection
  7 | import public Data.Wrap0
  8 |
  9 | %default total
 10 | %language ElabReflection
 11 |
 12 | export infix 0 -<
 13 | export prefix 0 =<
 14 |
 15 |
 16 | record ArrowVar where
 17 |   constructor MkAVar
 18 |   name : String
 19 |   type : TTImp
 20 |
 21 |
 22 | zipFilter : List a -> List Bool -> List a
 23 | zipFilter = catMaybes .: zipWith (\x,b => guard b $> x)
 24 |
 25 |
 26 | bindVars : TTImp -> List String
 27 | bindVars = (nub . runConst .) $ mapATTImp' $ \case
 28 |   IBindVar _ (UN $ Basic var) => const $ MkConst [var]
 29 |   IAs _ _ _ (UN $ Basic var) _ => \(MkConst vs) => MkConst (var :: vs)
 30 |   _ => id
 31 |
 32 | isBoundVar : TTImp -> String -> Bool
 33 | isBoundVar t var =
 34 |   let _ = Lazy.Monoid.Any
 35 |   in runConst {a=Lazy Bool} $ flip mapATTImp' t $ \case
 36 |     IBindVar _ (UN $ Basic var') => const $ MkConst $ delay (var == var')
 37 |     IAs _ _ _ (UN $ Basic var') _ => \(MkConst b) => MkConst (var == var' || b)
 38 |     _ => id
 39 |
 40 | usedInExpr : TTImp -> String -> Bool
 41 | usedInExpr t var =
 42 |   let _ = Lazy.Monoid.Any
 43 |   in runConst {a=Lazy Bool} $ flip mapATTImp' t $ \case
 44 |     -- If a hole is found, always include every possible variable
 45 |     IHole _ _ => const $ MkConst $ delay True
 46 |     IVar _ (UN $ Basic var') => const $ MkConst $ delay (var == var')
 47 |     _ => id
 48 |
 49 | usedInDiagram : TTImp -> String -> Bool
 50 | usedInDiagram (ILam _ _ _ (Just $ UN $ Basic v) _ rest) var =
 51 |   v /= var && usedInDiagram rest var
 52 | usedInDiagram (ILam _ _ _ _ _ rest) var = usedInDiagram rest var
 53 | usedInDiagram (ILet _ _ _ (UN $ Basic v) _ exp rest) var =
 54 |   usedInExpr exp var || (v /= var && usedInDiagram rest var)
 55 | usedInDiagram (ILet _ _ _ _ _ exp rest) var =
 56 |   usedInExpr exp var || usedInDiagram rest var
 57 | usedInDiagram (ICase _ _ exp _ clauses) var =
 58 |   usedInExpr exp var || any (\case
 59 |     PatClause _ lhs rhs =>
 60 |       not (isBoundVar lhs var) &&
 61 |         usedInDiagram (assert_smaller clauses rhs) var
 62 |     _ => False
 63 |     ) clauses
 64 | usedInDiagram `((~(mor) -< ~(inp)) >>= ~(rest)) var =
 65 |   usedInExpr inp var || usedInDiagram rest var
 66 | usedInDiagram `((~(mor) -< ~(inp)) >> ~(rest)) var =
 67 |   usedInExpr inp var || usedInDiagram rest var
 68 | usedInDiagram `(=< ~(out)) var = usedInExpr out var
 69 | usedInDiagram _ _ = False
 70 |
 71 |
 72 | export
 73 | arrowImpl : (impl : Maybe (TTImp, Bool)) -> TTImp -> Elab TTImp
 74 | arrowImpl impl t = do
 75 |   cat <- genSym "cat"
 76 |   arr <- genSym "arr"
 77 |   choice <- genSym "choice"
 78 |   let catImpl : TTImp =
 79 |       case impl of
 80 |         Nothing => `(%search)
 81 |         Just _ => IVar EmptyFC cat
 82 |   let arrImpl : TTImp =
 83 |       case impl of
 84 |         Nothing => `(%search)
 85 |         Just _ => IVar EmptyFC arr
 86 |   let choiceImpl : TTImp =
 87 |       case impl of
 88 |         Just (_, True) => IVar EmptyFC choice
 89 |         _ => `(%search)
 90 |   ts <- arrowImplLam catImpl arrImpl choiceImpl [<] [] t
 91 |   let out = composeImp catImpl $ optimize ts
 92 |   pure $ case impl of
 93 |     Nothing => out
 94 |     Just (im, False) => ILet EmptyFC EmptyFC MW arr (Implicit EmptyFC True) im
 95 |       `(let (Builtin.MkPair (Control.Category.Promonad.MkPromonad0 @{~(IBindVar EmptyFC cat)} {}) _) = ~(IVar EmptyFC arr)
 96 |         in ~out)
 97 |     Just (im, True) => ILet EmptyFC EmptyFC MW choice (Implicit EmptyFC True) im
 98 |       `(let (Builtin.MkPair ~(IBindVar EmptyFC arr) _) = ~(IVar EmptyFC choice)
 99 |             (Builtin.MkPair (Control.Category.Promonad.MkPromonad0 @{~(IBindVar EmptyFC cat)} {}) _) = ~(IVar EmptyFC arr)
100 |         in ~out)
101 |   where
102 |     optimize : SnocList TTImp -> SnocList TTImp
103 |     optimize [<] = [<]
104 |     optimize [<t] = [<t]
105 |     optimize (ts :< `(Control.Arrow.arrow @{~ar} {a = ~a, b = ~_} ~f) :< `(Control.Arrow.arrow @{~_} {a = ~b, b = ~c} ~g)) =
106 |       assert_total $ optimize (ts :< `(Control.Arrow.arrow @{~ar} {a = ~a, b = ~c} (Prelude.(.) {a = ~a, b = ~b, c = ~c} ~g ~f)))
107 |     optimize (ts :< t :< t') = optimize (ts :< t) :< t'
108 |
109 |     composeImp : (cat : TTImp) -> SnocList TTImp -> TTImp
110 |     composeImp cat [<] = `(Control.Category.Core.id @{~cat})
111 |     composeImp _ [<t] = t
112 |     composeImp cat (ts :< t) =
113 |       `(Control.Category.Core.(.) @{~cat} {a = _, b = _}
114 |         ~t ~(composeImp cat ts))
115 |
116 |     pairTy : List ArrowVar -> TTImp
117 |     pairTy [] = `(Builtin.Unit)
118 |     pairTy [MkAVar _ ty] = ty
119 |     pairTy (MkAVar _ ty :: vars) = `(Builtin.Pair ~ty ~(pairTy vars))
120 |
121 |     pair : List String -> TTImp
122 |     pair [] = `(Builtin.MkUnit)
123 |     pair [n] = IVar EmptyFC $ UN $ Basic n
124 |     pair (n :: ns) = `(Builtin.MkPair ~(IVar EmptyFC $ UN $ Basic n) ~(pair ns))
125 |
126 |     stringBind : List (ArrowVar, Bool) -> TTImp
127 |     stringBind [] = `(Builtin.MkUnit)
128 |     stringBind [(v,b)] = if b then IBindVar EmptyFC (UN $ Basic v.name) else Implicit EmptyFC True
129 |     stringBind ((v,b) :: strings) = `(Builtin.MkPair ~(if b then IBindVar EmptyFC (UN $ Basic v.name) else Implicit EmptyFC True) ~(stringBind strings))
130 |
131 |     stringLam : List (ArrowVar, Bool) -> TTImp -> TTImp
132 |     stringLam [] t = `(\_ => ~t)
133 |     stringLam [(_,False)] t = `(\_ => ~t)
134 |     stringLam [(v,True)] t = ILam EmptyFC MW ExplicitArg (Just $ UN $ Basic v.name) (Implicit EmptyFC False) t
135 |     stringLam ns t = `(\ ~(stringBind ns) => ~t)
136 |
137 |     stringLamMN : Name -> List (ArrowVar, Bool) -> TTImp -> TTImp
138 |     stringLamMN mn [] t = ILam EmptyFC MW ExplicitArg (Just mn) (Implicit EmptyFC False) t
139 |     stringLamMN mn ns t = `(\ (Builtins.MkPair ~(IBindVar EmptyFC mn) ~(stringBind ns)) => ~t)
140 |
141 |     mkEither : (i,n : Nat) -> TTImp -> TTImp
142 |     mkEither Z (S (S _)) t = `(Prelude.Left ~t)
143 |     mkEither (S n) (S n') t = `(Prelude.Right ~(mkEither n n' t))
144 |     mkEither _ _ t = t
145 |
146 |     arrowImplLam : (ct,ar,ch : TTImp) -> SnocList TTImp -> List ArrowVar -> TTImp -> Elab (SnocList TTImp)
147 |     arrowImpl' : (ct,ar,ch : TTImp) -> SnocList TTImp -> List ArrowVar -> TTImp -> Elab (SnocList TTImp)
148 |
149 |     arrowImplLam ct ar ch ts [] (ILam _ MW ExplicitArg Nothing _ rest) =
150 |       arrowImpl' ct ar ch (ts :< `(Control.Arrow.arrow @{~ar} {a=_,b=_} (\_ => Builtin.MkUnit))) [] rest
151 |     arrowImplLam ct ar ch ts [] (ILam _ MW ExplicitArg (Just $ UN $ Basic var) ty rest) =
152 |       arrowImpl' ct ar ch ts [MkAVar var ty] rest
153 |     arrowImplLam ct ar ch ts strings (ILam _ MW ExplicitArg Nothing _ rest) =
154 |       arrowImpl' ct ar ch (ts :< `(Control.Arrow.arrow @{~ar} {a=_,b=_} Builtin.snd)) strings rest
155 |     arrowImplLam ct ar ch ts strings (ILam _ MW ExplicitArg (Just $ UN $ Basic var) ty rest) =
156 |       if any (\v => v.name == var) strings
157 |       then do
158 |         let used = map (\v => v.name /= var) strings
159 |         let strings' = MkAVar var ty :: zipFilter strings used
160 |         arrowImpl' ct ar ch
161 |           (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy $ MkAVar var ty :: strings), b = ~(pairTy strings')}
162 |                     (\(Builtin.MkPair ~(IBindVar EmptyFC $ UN $ Basic var) ~(stringBind $ zip strings used)) =>
163 |                       ~(pair $ map name strings'))))
164 |           strings' rest
165 |       else arrowImpl' ct ar ch ts (MkAVar var ty :: strings) rest
166 |     arrowImplLam ct ar ch ts strings (ILam _ MW ExplicitArg (Just $ MN var _) ty rest) = do
167 |       arrowImpl' ct ar ch ts (MkAVar var ty :: strings) rest
168 |     arrowImplLam _ _ _ _ _ (ILam fc {}) = failAt fc "Invalid lambda"
169 |     arrowImplLam _ _ _ _ _ t = failAt (getFC t) "Expected lambda expression or binding pattern"
170 |
171 |     arrowImpl' ct ar ch ts (MkAVar v ty :: strings) (ICase fc _ (IVar _ var@(MN {})) _ clauses) = do
172 |       let tot = length clauses
173 |       (clauses', conts) <- map unzip $ evalStateT Z $ for clauses $ \case
174 |         PatClause fc' lhs rhs => do
175 |           let names = bindVars lhs
176 |           let vars = map (`MkAVar` `(_)) names
177 |           let usedLater = map (\v => not (elem v.name names) && usedInDiagram rhs v.name) strings
178 |           let strings' = vars ++ zipFilter strings usedLater
179 |           t <- lift $ assert_total $ arrowImpl' ct ar ch [<] strings' rhs
180 |           i <- get
181 |           modify S
182 |           pure (PatClause fc' lhs $ mkEither i tot $ pair $ map name strings', Just $ composeImp ct $ optimize t)
183 |         ImpossibleClause fc' lhs => pure (ImpossibleClause fc' lhs, Nothing)
184 |         WithClause fc' {} => failAt fc' "Unrecognized case pattern"
185 |       let conts' = catMaybes conts
186 |       case conts' of
187 |         [] =>
188 |           pure (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy $ MkAVar v ty :: strings), b = _}
189 |                       ~(stringLamMN var (map (,False) strings)
190 |                         (ICase fc [] (IVar EmptyFC var) ty clauses'))))
191 |         _ :: _ =>
192 |           pure (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy $ MkAVar v ty :: strings), b = _}
193 |                       ~(stringLamMN var (map (,False) strings)
194 |                         (ICase fc [] (IVar EmptyFC var) ty clauses')))
195 |                     :< foldr1 (\t,t' => `(Control.Arrow.(\|/) @{~ch} ~t ~t')) conts')
196 |     arrowImpl' ct ar ch ts strings (ICase fc _ exp ty clauses) = do
197 |       let tot = length clauses
198 |       (clauses', conts) <- map unzip $ evalStateT Z $ for clauses $ \case
199 |         PatClause fc' lhs rhs => do
200 |           let names = bindVars lhs
201 |           let vars = map (`MkAVar` `(_)) names
202 |           let usedLater = map (\v => not (elem v.name names) && usedInDiagram rhs v.name) strings
203 |           let strings' = vars ++ zipFilter strings usedLater
204 |           t <- lift $ assert_total $ arrowImpl' ct ar ch [<] strings' rhs
205 |           i <- get
206 |           modify S
207 |           pure (PatClause fc' lhs $ mkEither i tot $ pair $ map name strings', Just $ composeImp ct $ optimize t)
208 |         ImpossibleClause fc' lhs => pure (ImpossibleClause fc' lhs, Nothing)
209 |         WithClause fc' {} => failAt fc' "Unrecognized case pattern"
210 |       let conts' = catMaybes conts
211 |       case conts' of
212 |         [] =>
213 |           pure (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
214 |                       ~(stringLam (map (,True) strings) (ICase fc [] exp ty clauses'))))
215 |         _ :: _ =>
216 |           pure (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
217 |                       ~(stringLam (map (,True) strings) (ICase fc [] exp ty clauses')))
218 |                     :< foldr1 (\t,t' => `(Control.Arrow.(\|/) @{~ch} ~t ~t')) conts')
219 |     arrowImpl' ct ar ch ts strings `(~(ICase fc _ exp ty clauses) >> ~(rest)) = do
220 |       let tot = length clauses
221 |       (clauses', conts) <- map unzip $ evalStateT Z $ for clauses $ \case
222 |         PatClause fc' lhs rhs => do
223 |           let names = bindVars lhs
224 |           let vars = map (`MkAVar` `(_)) names
225 |           let usedLater = map (\v => not (elem v.name names) && usedInDiagram rhs v.name) strings
226 |           let strings' = vars ++ zipFilter strings usedLater
227 |           t <- lift $ assert_total $ arrowImpl' ct ar ch [<] strings' rhs
228 |           i <- get
229 |           modify S
230 |           pure (PatClause fc' lhs $ mkEither i tot $ pair $ map name strings', Just $ composeImp ct $ optimize t)
231 |         ImpossibleClause fc' lhs => pure (ImpossibleClause fc' lhs, Nothing)
232 |         WithClause fc' {} => failAt fc' "Unrecognized case pattern"
233 |       let conts' = catMaybes conts
234 |       case conts' of
235 |         [] =>
236 |           arrowImpl' ct ar ch (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
237 |                       ~(stringLam (map (,True) strings) (ICase fc [] exp ty clauses'))))
238 |             strings rest
239 |         _ :: _ =>
240 |           arrowImpl' ct ar ch (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
241 |                         ~(stringLam (map (,True) strings)
242 |                         `(Builtin.MkPair ~(ICase fc [] exp ty clauses') ~(pair $ map name strings))))
243 |                       :< `(Control.Arrow.first @{~ar} ~(foldr1 (\t,t' => `(Control.Arrow.(\|/) @{~ch} ~t ~t')) conts'))
244 |                       :< `(Control.Arrow.arrow @{~ar} {a=_,b=_} Builtin.snd))
245 |             strings rest
246 |     arrowImpl' ct ar ch ts strings `(~(ICase fc _ exp ty clauses) >>= ~(rest)) = do
247 |       let tot = length clauses
248 |       (clauses', conts) <- map unzip $ evalStateT Z $ for clauses $ \case
249 |         PatClause fc' lhs rhs => do
250 |           let names = bindVars lhs
251 |           let vars = map (`MkAVar` `(_)) names
252 |           let usedLater = map (\v => not (elem v.name names) && usedInDiagram rhs v.name) strings
253 |           let strings' = vars ++ zipFilter strings usedLater
254 |           t <- lift $ assert_total $ arrowImpl' ct ar ch [<] strings' rhs
255 |           i <- get
256 |           modify S
257 |           pure (PatClause fc' lhs $ mkEither i tot $ pair $ map name strings', Just $ composeImp ct $ optimize t)
258 |         ImpossibleClause fc' lhs => pure (ImpossibleClause fc' lhs, Nothing)
259 |         WithClause fc' {} => failAt fc' "Unrecognized case pattern"
260 |       let conts' = catMaybes conts
261 |       case conts' of
262 |         [] =>
263 |           arrowImplLam ct ar ch (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
264 |                       ~(stringLam (map (,True) strings) (ICase fc [] exp ty clauses'))))
265 |             strings rest
266 |         _ :: _ =>
267 |           arrowImplLam ct ar ch (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
268 |                         ~(stringLam (map (,True) strings)
269 |                         `(Builtin.MkPair ~(ICase fc [] exp ty clauses') ~(pair $ map name strings))))
270 |                       :< `(Control.Arrow.first @{~ar} ~(foldr1 (\t,t' => `(Control.Arrow.(\|/) @{~ch} ~t ~t')) conts')))
271 |             strings rest
272 |     arrowImpl' ct ar ch ts strings (ILet fc fc' MW (UN $ Basic var) ty exp rest) = do
273 |       (usedExp,usedLater,strings') <- do
274 |         let usedExp = map (usedInExpr exp . name) strings
275 |         let usedLater = map (\v => v.name /= var && usedInDiagram rest v.name) strings
276 |         let strings' = MkAVar var ty :: zipFilter strings usedLater
277 |         pure (usedExp,usedLater,strings')
278 |       arrowImpl' ct ar ch
279 |         (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = ~(pairTy strings')}
280 |           ~(stringLam (zip strings $ zipWith (\x,y => x || y) usedExp usedLater)
281 |             (ILet fc fc' MW (UN $ Basic var) ty exp (pair $ map name strings')))))
282 |         strings' rest
283 |     arrowImpl' ct ar ch ts strings (ILet fc {}) = failAt fc "Let binding must be unrestricted"
284 |     arrowImpl' ct ar ch ts strings `((~(mor) -< ~(inp)) >>= ~(rest)) =
285 |       case strings of
286 |         [] => arrowImplLam ct ar ch (ts :< `(Control.Arrow.arrow @{~ar} {a=_,b=_} (\_ => ~inp)) :< mor) [] rest
287 |         _ :: _ => do
288 |           (usedInp,usedLater,strings') <- do
289 |             let usedInp = map (usedInExpr inp . name) strings
290 |             let usedLater = map (usedInDiagram rest . name) strings
291 |             let strings' = zipFilter strings usedLater
292 |             pure (usedInp,usedLater,strings')
293 |           case strings' of
294 |             [] =>
295 |               arrowImplLam ct ar ch
296 |                 (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings),b=_}
297 |                           ~(stringLam (zip strings usedInp) inp))
298 |                     :< mor)
299 |                 strings' rest
300 |             _ :: _ =>
301 |               arrowImplLam ct ar ch
302 |                 (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = Builtin.Pair _ ~(pairTy strings')}
303 |                   ~(stringLam (zip strings $ zipWith (\x,y => x || y) usedInp usedLater)
304 |                     `(Builtin.MkPair ~inp ~(pair $ map name strings'))))
305 |                     :< `(Control.Arrow.first @{~ar} ~mor))
306 |                 strings' rest
307 |     arrowImpl' ct ar ch ts strings `((~(mor) -< ~(inp)) >> ~(rest)) =
308 |       case strings of
309 |         [] => arrowImpl' ct ar ch (ts
310 |           :< `(Control.Arrow.arrow @{~ar} {a=Builtin.Unit,b=_} (\_ => ~inp))
311 |           :< mor
312 |           :< `(Control.Arrow.arrow @{~ar} {a=_,b=Builtin.Unit} (\_ => Builtin.MkUnit))) [] rest
313 |         _ :: _ => do
314 |           (usedInp,usedLater,strings') <- do
315 |             let usedInp = map (usedInExpr inp . name) strings
316 |             let usedLater = map (usedInDiagram rest . name) strings
317 |             let strings' = zipFilter strings usedLater
318 |             pure (usedInp,usedLater,strings')
319 |           case strings' of
320 |             [] =>
321 |               arrowImpl' ct ar ch
322 |                 (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
323 |                           ~(stringLam (zip strings usedInp) inp))
324 |                     :< mor :< `(Control.Arrow.arrow @{~ar} {a=_,b=_} (\_ => ())))
325 |                 strings' rest
326 |             _ :: _ =>
327 |               arrowImpl' ct ar ch
328 |                 (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = Builtin.Pair _ ~(pairTy strings')}
329 |                         ~(stringLam (zip strings $ zipWith (\x,y => x || y) usedInp usedLater)
330 |                           `(Builtin.MkPair ~inp ~(pair $ map name strings'))))
331 |                     :< `(Control.Arrow.first @{~ar} ~mor) :< `(Control.Arrow.arrow @{~ar} {a=_,b=_} Builtin.snd))
332 |                 strings' rest
333 |     arrowImpl' ct ar ch ts strings `(~(mor) -< ~(inp)) =
334 |       pure (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings), b = _}
335 |                     ~(stringLam (map (,True) strings) inp))
336 |                 :< mor)
337 |     arrowImpl' ct ar ch ts strings `(=< ~(out)) =
338 |       pure (ts :< `(Control.Arrow.arrow @{~ar} {a = ~(pairTy strings),b=_}
339 |         ~(stringLam (map (,True) strings) out)))
340 |
341 |     arrowImpl' _ _ _ _ _ (IHole fc _) = failAt fc "Holes are not allowed as top-level commands"
342 |     arrowImpl' _ _ _ _ _ (ILam fc {}) = failAt (getFC t) "Lambda not allowed here"
343 |     arrowImpl' _ _ _ _ _ t = failAt (getFC t) "Could not parse expression"
344 |
345 | ||| Enter arrow notation.
346 | |||
347 | ||| This elaboration script must be specifically invoked with
348 | ||| `%runElab`. The category is inferred from the return type.
349 | export
350 | arrowDo : {0 arr : Hom Type0} -> (0 _ : Arrow arr) => TTImp -> Elab (arr (W0 a) (W0 b))
351 | arrowDo @{impl} t = check !(arrowImpl (Just (!(quote impl), False)) t)
352 |
353 | ||| Enter arrow notation. Unlike `arrowDo`, this script allows you to
354 | ||| explicitly provide an `ArrowChoice` implementation instead of
355 | ||| searching for one.
356 | |||
357 | ||| This elaboration script must be specifically invoked with
358 | ||| `%runElab`. The category is inferred from the return type.
359 | export
360 | arrowChoiceDo : {0 arr : Hom Type0} -> (0 _ : ArrowChoice arr) => TTImp -> Elab (arr (W0 a) (W0 b))
361 | arrowChoiceDo @{impl} t = check !(arrowImpl (Just (!(quote impl), True)) t)
362 |