on 0ebc19f help sign in
patch/src/Data/Patch/MapWithPatchingMove.hs
431 lines 18 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3{-# LANGUAGE FlexibleContexts #-}
4{-# LANGUAGE FlexibleInstances #-}
5{-# LANGUAGE LambdaCase #-}
6{-# LANGUAGE MultiParamTypeClasses #-}
7{-# LANGUAGE PatternGuards #-}
8{-# LANGUAGE ScopedTypeVariables #-}
9{-# LANGUAGE StandaloneDeriving #-}
10{-# LANGUAGE TemplateHaskell #-}
11{-# LANGUAGE TypeFamilies #-}
12{-# LANGUAGE UndecidableInstances #-}
14-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
15-- another
16module Data.Patch.MapWithPatchingMove
17 ( PatchMapWithPatchingMove (..)
18 , patchMapWithPatchingMove
19 , patchMapWithPatchingMoveInsertAll
20 , insertMapKey
21 , moveMapKey
22 , swapMapKey
23 , deleteMapKey
24 , unsafePatchMapWithPatchingMove
25 , patchMapWithPatchingMoveNewElements
26 , patchMapWithPatchingMoveNewElementsMap
27 , patchThatSortsMapWith
28 , patchThatChangesAndSortsMapWith
29 , patchThatChangesMap
31 -- * Node Info
32 , NodeInfo (..)
33 , bitraverseNodeInfo
34 , nodeInfoMapFrom
35 , nodeInfoMapMFrom
36 , nodeInfoSetTo
38 -- * From
39 , From(..)
40 , bitraverseFrom
42 -- * To
43 , To
45 -- TODO internals module
46 , Fixup (..)
47 ) where
49import Data.Patch.Class
51import Control.Arrow
52import Control.Lens.TH (makeWrapped)
53import Control.Monad.Trans.State
54import Data.Foldable
55import Data.Function
56import Data.List
57import Data.Map (Map)
58import qualified Data.Map as Map
59import Data.Maybe
60#if !MIN_VERSION_base(4,11,0)
61import Data.Semigroup (Semigroup (..))
62#endif
63import Data.Monoid.DecidablyEmpty
64import qualified Data.Set as Set
65import Data.These (These (..))
66import Data.Tuple
68-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
69-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
70-- and vice versa. There should never be any unpaired From/To keys.
71newtype PatchMapWithPatchingMove k p = PatchMapWithPatchingMove
72 { -- | Extract the internal representation of the 'PatchMapWithPatchingMove'
73 unPatchMapWithPatchingMove :: Map k (NodeInfo k p)
74 }
76deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithPatchingMove k p)
77deriving instance (Ord k, Read k, Read p, Read (PatchTarget p)) => Read (PatchMapWithPatchingMove k p)
78deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithPatchingMove k p)
79deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithPatchingMove k p)
81deriving instance ( Ord k
82#if !MIN_VERSION_base(4,11,0)
83 , Semigroup p
84#endif
85 , DecidablyEmpty p
86 , Patch p
87 ) => DecidablyEmpty (PatchMapWithPatchingMove k p)
89-- | Create a 'PatchMapWithPatchingMove', validating it
90patchMapWithPatchingMove
91 :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithPatchingMove k p)
92patchMapWithPatchingMove m = if valid then Just $ PatchMapWithPatchingMove m else Nothing
93 where valid = forwardLinks == backwardLinks
94 forwardLinks = Map.mapMaybe _nodeInfo_to m
95 backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
96 case _nodeInfo_from p of
97 From_Move from _ -> Just (from, to)
98 _ -> Nothing
100-- | Create a 'PatchMapWithPatchingMove' that inserts everything in the given 'Map'
101patchMapWithPatchingMoveInsertAll
102 :: Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
103patchMapWithPatchingMoveInsertAll m = PatchMapWithPatchingMove $ flip fmap m $ \v -> NodeInfo
104 { _nodeInfo_from = From_Insert v
105 , _nodeInfo_to = Nothing
106 }
108-- | Make a @'PatchMapWithPatchingMove' k p@ which has the effect of inserting or replacing a value @v@ at the given key @k@, like 'Map.insert'.
109insertMapKey
110 :: k -> PatchTarget p -> PatchMapWithPatchingMove k p
111insertMapKey k v = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
113-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of moving the value from the first key @k@ to the second key @k@, equivalent to:
114--
115-- @
116-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
117-- @
118moveMapKey
119 :: ( DecidablyEmpty p
120#if !MIN_VERSION_base(4,11,0)
121 , Semigroup p
122#endif
123 , Patch p
124 )
125 => Ord k => k -> k -> PatchMapWithPatchingMove k p
126moveMapKey src dst
127 | src == dst = mempty
128 | otherwise =
129 PatchMapWithPatchingMove $ Map.fromList
130 [ (dst, NodeInfo (From_Move src mempty) Nothing)
131 , (src, NodeInfo From_Delete (Just dst))
132 ]
134-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of swapping two keys in the mapping, equivalent to:
135--
136-- @
137-- let aMay = Map.lookup a map
138-- bMay = Map.lookup b map
139-- in maybe id (Map.insert a) (bMay <> aMay)
140-- . maybe id (Map.insert b) (aMay <> bMay)
141-- . Map.delete a . Map.delete b $ map
142-- @
143swapMapKey
144 :: ( DecidablyEmpty p
145#if !MIN_VERSION_base(4,11,0)
146 , Semigroup p
147#endif
148 , Patch p
149 )
150 => Ord k => k -> k -> PatchMapWithPatchingMove k p
151swapMapKey src dst
152 | src == dst = mempty
153 | otherwise =
154 PatchMapWithPatchingMove $ Map.fromList
155 [ (dst, NodeInfo (From_Move src mempty) (Just src))
156 , (src, NodeInfo (From_Move dst mempty) (Just dst))
157 ]
159-- | Make a @'PatchMapWithPatchingMove' k v@ which has the effect of deleting a key in
160-- the mapping, equivalent to 'Map.delete'.
161deleteMapKey
162 :: k -> PatchMapWithPatchingMove k v
163deleteMapKey k = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo From_Delete Nothing
165-- | Wrap a @'Map' k (NodeInfo k v)@ representing patch changes into a @'PatchMapWithPatchingMove' k v@, without checking any invariants.
166--
167-- __Warning:__ when using this function, you must ensure that the invariants of 'PatchMapWithPatchingMove' are preserved; they will not be checked.
168unsafePatchMapWithPatchingMove
169 :: Map k (NodeInfo k p) -> PatchMapWithPatchingMove k p
170unsafePatchMapWithPatchingMove = PatchMapWithPatchingMove
172-- | Apply the insertions, deletions, and moves to a given 'Map'
173instance (Ord k, Patch p) => Patch (PatchMapWithPatchingMove k p) where
174 type PatchTarget (PatchMapWithPatchingMove k p) = Map k (PatchTarget p)
175 -- TODO: return Nothing sometimes
176 -- Note: the strict application here is critical to ensuring that incremental
177 -- merges don't hold onto all their prerequisite events forever; can we make
178 -- this more robust?
179 apply (PatchMapWithPatchingMove m) old = Just $! insertions `Map.union` (old `Map.difference` deletions)
180 where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
181 From_Insert v -> Just v
182 From_Move k p -> applyAlways p <$> Map.lookup k old
183 From_Delete -> Nothing
184 deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
185 From_Delete -> Just ()
186 _ -> Nothing
188-- | Returns all the new elements that will be added to the 'Map'
189patchMapWithPatchingMoveNewElements
190 :: PatchMapWithPatchingMove k p -> [PatchTarget p]
191patchMapWithPatchingMoveNewElements = Map.elems . patchMapWithPatchingMoveNewElementsMap
193-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithPatchingMove' k v@.
194patchMapWithPatchingMoveNewElementsMap
195 :: PatchMapWithPatchingMove k p -> Map k (PatchTarget p)
196patchMapWithPatchingMoveNewElementsMap (PatchMapWithPatchingMove p) = Map.mapMaybe f p
197 where f ni = case _nodeInfo_from ni of
198 From_Insert v -> Just v
199 From_Move _ _ -> Nothing
200 From_Delete -> Nothing
202-- | Create a 'PatchMapWithPatchingMove' that, if applied to the given 'Map', will sort
203-- its values using the given ordering function. The set keys of the 'Map' is
204-- not changed.
205patchThatSortsMapWith
206 :: (Ord k, Monoid p)
207 => (PatchTarget p -> PatchTarget p -> Ordering)
208 -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
209patchThatSortsMapWith cmp m = PatchMapWithPatchingMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
210 where unsorted = Map.toList m
211 sorted = sortBy (cmp `on` snd) unsorted
212 f (to, _) (from, _) = if to == from then Nothing else
213 Just (from, to)
214 reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
215 g (to, _) (from, _) = if to == from then Nothing else
216 let Just movingTo = Map.lookup from reverseMapping
217 in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
219-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
220-- will produce a 'Map' with the same values as the second 'Map' but with the
221-- values sorted with the given ordering function.
222patchThatChangesAndSortsMapWith
223 :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p)
224 => (PatchTarget p -> PatchTarget p -> Ordering)
225 -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
226patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
227 where newList = Map.toList newByIndexUnsorted
228 newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
230-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
231-- will produce the second 'Map'.
232patchThatChangesMap
233 :: (Ord k, Ord (PatchTarget p), Monoid p)
234 => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
235patchThatChangesMap oldByIndex newByIndex = patch
236 where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
237 (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
238 let f k v = do
239 remainingValues <- get
240 let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
241 then Map.delete v remainingValues
242 else Map.insert v remainingKeys remainingValues
243 case Map.lookup v remainingValues of
244 Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
245 Just fromKs ->
246 if k `Set.member` fromKs
247 then do
248 putRemainingKeys $ Set.delete k fromKs
249 return $ NodeInfo (From_Move k mempty) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
250 else do
251 (fromK, remainingKeys) <- return $
252 fromMaybe (error "PatchMapWithPatchingMove.patchThatChangesMap: impossible: fromKs was empty") $
253 Set.minView fromKs -- There's an existing value, but it's not here; move it here
254 putRemainingKeys remainingKeys
255 return $ NodeInfo (From_Move fromK mempty) $ Just undefined
256 Map.traverseWithKey f newByIndex
257 unusedOldKeys = fold unusedValuesByValue
258 pointlessMove k = \case
259 From_Move k' _ | k == k' -> True
260 _ -> False
261 keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
262 then Just undefined
263 else Nothing
264 patch = unsafePatchMapWithPatchingMove $ Map.filterWithKey (\k -> not . pointlessMove k . _nodeInfo_from) $ Map.mergeWithKey (\k a _ -> Just $ nodeInfoSetTo (keyWasMoved k) a) (Map.mapWithKey $ \k -> nodeInfoSetTo $ keyWasMoved k) (Map.mapWithKey $ \k _ -> NodeInfo From_Delete $ keyWasMoved k) insertsAndMoves oldByIndex
266--
267-- NodeInfo
268--
270-- | Holds the information about each key: where its new value should come from,
271-- and where its old value should go to
272data NodeInfo k p = NodeInfo
273 { _nodeInfo_from :: !(From k p)
274 -- ^ Where do we get the new value for this key?
275 , _nodeInfo_to :: !(To k)
276 -- ^ If the old value is being kept (i.e. moved rather than deleted or
277 -- replaced), where is it going?
278 }
279deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
280deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
281deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
282deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
284-- | Traverse the 'NodeInfo' over the key, patch, and patch target. Because of
285-- the type families here, this doesn't it any bi- or tri-traversal class.
286bitraverseNodeInfo
287 :: Applicative f
288 => (k0 -> f k1)
289 -> (p0 -> f p1)
290 -> (PatchTarget p0 -> f (PatchTarget p1))
291 -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
292bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
293 <$> bitraverseFrom fk fp fpt from
294 <*> traverse fk to
296-- | Change the 'From' value of a 'NodeInfo'
297nodeInfoMapFrom
298 :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
299nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
301-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
302-- 'Applicative', 'Monad', etc.) action to get the new value
303nodeInfoMapMFrom
304 :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
305nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
307-- | Set the 'To' field of a 'NodeInfo'
308nodeInfoSetTo
309 :: To k -> NodeInfo k v -> NodeInfo k v
310nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
312--
313-- From
314--
316-- | Describe how a key's new value should be produced
317data From k p
318 = From_Insert (PatchTarget p) -- ^ Insert the given value here
319 | From_Delete -- ^ Delete the existing value, if any, from here
320 | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
322deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
323deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
324deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
325deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
327-- | Traverse the 'From' over the key, patch, and patch target. Because of
328-- the type families here, this doesn't it any bi- or tri-traversal class.
329bitraverseFrom
330 :: Applicative f
331 => (k0 -> f k1)
332 -> (p0 -> f p1)
333 -> (PatchTarget p0 -> f (PatchTarget p1))
334 -> From k0 p0 -> f (From k1 p1)
335bitraverseFrom fk fp fpt = \case
336 From_Insert pt -> From_Insert <$> fpt pt
337 From_Delete -> pure From_Delete
338 From_Move k p -> From_Move <$> fk k <*> fp p
340--
341-- To
342--
344-- | Describe where a key's old value will go. If this is 'Just', that means
345-- the key's old value will be moved to the given other key; if it is 'Nothing',
346-- that means it will be deleted.
347type To = Maybe
349--
350-- Fixup
351--
353-- | Helper data structure used for composing patches using the monoid instance.
354data Fixup k v
355 = Fixup_Delete
356 | Fixup_Update (These (From k v) (To k))
358-- | Compose patches having the same effect as applying the patches in turn:
359-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
360instance ( Ord k
361#if !MIN_VERSION_base(4,11,0)
362 , Semigroup p
363#endif
364 , DecidablyEmpty p
365 , Patch p
366 ) => Semigroup (PatchMapWithPatchingMove k p) where
367 PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
368 where
369 connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
370 h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
371 h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
372 (Just toAfter, From_Move fromBefore p)
373 | fromBefore == toAfter && isEmpty p
374 -> [(toAfter, Fixup_Delete)]
375 | otherwise
376 -> [ (toAfter, Fixup_Update (This editBefore))
377 , (fromBefore, Fixup_Update (That mToAfter))
378 ]
379 (Nothing, From_Move fromBefore _) -> [(fromBefore, Fixup_Update (That mToAfter))] -- The item is destroyed in the second patch, so indicate that it is destroyed in the source map
380 (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
381 (Nothing, _) -> []
382 mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
383 mergeFixups _ (Fixup_Update a) (Fixup_Update b)
384 | This x <- a, That y <- b
385 = Fixup_Update $ These x y
386 | That y <- a, This x <- b
387 = Fixup_Update $ These x y
388 mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
389 fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
390 combineNodeInfos _ nia nib = NodeInfo
391 { _nodeInfo_from = _nodeInfo_from nia
392 , _nodeInfo_to = _nodeInfo_to nib
393 }
394 applyFixup _ ni = \case
395 Fixup_Delete -> Nothing
396 Fixup_Update u -> Just $ NodeInfo
397 { _nodeInfo_from = case _nodeInfo_from ni of
398 f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
399 Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
400 Just (From_Insert v) -> From_Insert $ applyAlways p' v
401 Just From_Delete -> From_Delete
402 Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
403 _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
404 , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
405 }
406 m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
407 getHere :: These a b -> Maybe a
408 getHere = \case
409 This a -> Just a
410 These a _ -> Just a
411 That _ -> Nothing
412 getThere :: These a b -> Maybe b
413 getThere = \case
414 This _ -> Nothing
415 These _ b -> Just b
416 That b -> Just b
418--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
419-- | Compose patches having the same effect as applying the patches in turn:
420-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
421instance ( Ord k
422#if !MIN_VERSION_base(4,11,0)
423 , Semigroup p
424#endif
425 , DecidablyEmpty p
426 , Patch p
427 ) => Monoid (PatchMapWithPatchingMove k p) where
428 mempty = PatchMapWithPatchingMove mempty
429 mappend = (<>)
431makeWrapped ''PatchMapWithPatchingMove