on ac8f411 help sign in
patch/src/Data/Patch/MapWithPatchingMove.hs
434 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) => PatchHet (PatchMapWithPatchingMove k p) where
174 type PatchSource (PatchMapWithPatchingMove k p) = Map k (PatchSource p)
175 type PatchTarget (PatchMapWithPatchingMove k p) = Map k (PatchTarget p)
177instance (Ord k, Patch p) => Patch (PatchMapWithPatchingMove k p) where
178 -- TODO: return Nothing sometimes
179 -- Note: the strict application here is critical to ensuring that incremental
180 -- merges don't hold onto all their prerequisite events forever; can we make
181 -- this more robust?
182 apply (PatchMapWithPatchingMove m) old = Just $! insertions `Map.union` (old `Map.difference` deletions)
183 where insertions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
184 From_Insert v -> Just v
185 From_Move k p -> applyAlways p <$> Map.lookup k old
186 From_Delete -> Nothing
187 deletions = flip Map.mapMaybeWithKey m $ \_ ni -> case _nodeInfo_from ni of
188 From_Delete -> Just ()
189 _ -> Nothing
191-- | Returns all the new elements that will be added to the 'Map'
192patchMapWithPatchingMoveNewElements
193 :: PatchMapWithPatchingMove k p -> [PatchTarget p]
194patchMapWithPatchingMoveNewElements = Map.elems . patchMapWithPatchingMoveNewElementsMap
196-- | Return a @'Map' k v@ with all the inserts/updates from the given @'PatchMapWithPatchingMove' k v@.
197patchMapWithPatchingMoveNewElementsMap
198 :: PatchMapWithPatchingMove k p -> Map k (PatchTarget p)
199patchMapWithPatchingMoveNewElementsMap (PatchMapWithPatchingMove p) = Map.mapMaybe f p
200 where f ni = case _nodeInfo_from ni of
201 From_Insert v -> Just v
202 From_Move _ _ -> Nothing
203 From_Delete -> Nothing
205-- | Create a 'PatchMapWithPatchingMove' that, if applied to the given 'Map', will sort
206-- its values using the given ordering function. The set keys of the 'Map' is
207-- not changed.
208patchThatSortsMapWith
209 :: (Ord k, Monoid p)
210 => (PatchTarget p -> PatchTarget p -> Ordering)
211 -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
212patchThatSortsMapWith cmp m = PatchMapWithPatchingMove $ Map.fromList $ catMaybes $ zipWith g unsorted sorted
213 where unsorted = Map.toList m
214 sorted = sortBy (cmp `on` snd) unsorted
215 f (to, _) (from, _) = if to == from then Nothing else
216 Just (from, to)
217 reverseMapping = Map.fromList $ catMaybes $ zipWith f unsorted sorted
218 g (to, _) (from, _) = if to == from then Nothing else
219 let Just movingTo = Map.lookup from reverseMapping
220 in Just (to, NodeInfo (From_Move from mempty) $ Just movingTo)
222-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
223-- will produce a 'Map' with the same values as the second 'Map' but with the
224-- values sorted with the given ordering function.
225patchThatChangesAndSortsMapWith
226 :: forall k p. (Ord k, Ord (PatchTarget p), Monoid p)
227 => (PatchTarget p -> PatchTarget p -> Ordering)
228 -> Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
229patchThatChangesAndSortsMapWith cmp oldByIndex newByIndexUnsorted = patchThatChangesMap oldByIndex newByIndex
230 where newList = Map.toList newByIndexUnsorted
231 newByIndex = Map.fromList $ zip (fst <$> newList) $ sortBy cmp $ snd <$> newList
233-- | Create a 'PatchMapWithPatchingMove' that, if applied to the first 'Map' provided,
234-- will produce the second 'Map'.
235patchThatChangesMap
236 :: (Ord k, Ord (PatchTarget p), Monoid p)
237 => Map k (PatchTarget p) -> Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
238patchThatChangesMap oldByIndex newByIndex = patch
239 where oldByValue = Map.fromListWith Set.union $ swap . first Set.singleton <$> Map.toList oldByIndex
240 (insertsAndMoves, unusedValuesByValue) = flip runState oldByValue $ do
241 let f k v = do
242 remainingValues <- get
243 let putRemainingKeys remainingKeys = put $ if Set.null remainingKeys
244 then Map.delete v remainingValues
245 else Map.insert v remainingKeys remainingValues
246 case Map.lookup v remainingValues of
247 Nothing -> return $ NodeInfo (From_Insert v) $ Just undefined -- There's no existing value we can take
248 Just fromKs ->
249 if k `Set.member` fromKs
250 then do
251 putRemainingKeys $ Set.delete k fromKs
252 return $ NodeInfo (From_Move k mempty) $ Just undefined -- There's an existing value, and it's here, so no patch necessary
253 else do
254 (fromK, remainingKeys) <- return $
255 fromMaybe (error "PatchMapWithPatchingMove.patchThatChangesMap: impossible: fromKs was empty") $
256 Set.minView fromKs -- There's an existing value, but it's not here; move it here
257 putRemainingKeys remainingKeys
258 return $ NodeInfo (From_Move fromK mempty) $ Just undefined
259 Map.traverseWithKey f newByIndex
260 unusedOldKeys = fold unusedValuesByValue
261 pointlessMove k = \case
262 From_Move k' _ | k == k' -> True
263 _ -> False
264 keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
265 then Just undefined
266 else Nothing
267 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
269--
270-- NodeInfo
271--
273-- | Holds the information about each key: where its new value should come from,
274-- and where its old value should go to
275data NodeInfo k p = NodeInfo
276 { _nodeInfo_from :: !(From k p)
277 -- ^ Where do we get the new value for this key?
278 , _nodeInfo_to :: !(To k)
279 -- ^ If the old value is being kept (i.e. moved rather than deleted or
280 -- replaced), where is it going?
281 }
282deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
283deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
284deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
285deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
287-- | Traverse the 'NodeInfo' over the key, patch, and patch target. Because of
288-- the type families here, this doesn't it any bi- or tri-traversal class.
289bitraverseNodeInfo
290 :: Applicative f
291 => (k0 -> f k1)
292 -> (p0 -> f p1)
293 -> (PatchTarget p0 -> f (PatchTarget p1))
294 -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
295bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
296 <$> bitraverseFrom fk fp fpt from
297 <*> traverse fk to
299-- | Change the 'From' value of a 'NodeInfo'
300nodeInfoMapFrom
301 :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
302nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
304-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
305-- 'Applicative', 'Monad', etc.) action to get the new value
306nodeInfoMapMFrom
307 :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
308nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
310-- | Set the 'To' field of a 'NodeInfo'
311nodeInfoSetTo
312 :: To k -> NodeInfo k v -> NodeInfo k v
313nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
315--
316-- From
317--
319-- | Describe how a key's new value should be produced
320data From k p
321 = From_Insert (PatchTarget p) -- ^ Insert the given value here
322 | From_Delete -- ^ Delete the existing value, if any, from here
323 | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
325deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
326deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
327deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
328deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
330-- | Traverse the 'From' over the key, patch, and patch target. Because of
331-- the type families here, this doesn't it any bi- or tri-traversal class.
332bitraverseFrom
333 :: Applicative f
334 => (k0 -> f k1)
335 -> (p0 -> f p1)
336 -> (PatchTarget p0 -> f (PatchTarget p1))
337 -> From k0 p0 -> f (From k1 p1)
338bitraverseFrom fk fp fpt = \case
339 From_Insert pt -> From_Insert <$> fpt pt
340 From_Delete -> pure From_Delete
341 From_Move k p -> From_Move <$> fk k <*> fp p
343--
344-- To
345--
347-- | Describe where a key's old value will go. If this is 'Just', that means
348-- the key's old value will be moved to the given other key; if it is 'Nothing',
349-- that means it will be deleted.
350type To = Maybe
352--
353-- Fixup
354--
356-- | Helper data structure used for composing patches using the monoid instance.
357data Fixup k v
358 = Fixup_Delete
359 | Fixup_Update (These (From k v) (To k))
361-- | Compose patches having the same effect as applying the patches in turn:
362-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
363instance ( Ord k
364#if !MIN_VERSION_base(4,11,0)
365 , Semigroup p
366#endif
367 , DecidablyEmpty p
368 , Patch p
369 ) => Semigroup (PatchMapWithPatchingMove k p) where
370 PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
371 where
372 connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
373 h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
374 h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
375 (Just toAfter, From_Move fromBefore p)
376 | fromBefore == toAfter && isEmpty p
377 -> [(toAfter, Fixup_Delete)]
378 | otherwise
379 -> [ (toAfter, Fixup_Update (This editBefore))
380 , (fromBefore, Fixup_Update (That mToAfter))
381 ]
382 (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
383 (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
384 (Nothing, _) -> []
385 mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
386 mergeFixups _ (Fixup_Update a) (Fixup_Update b)
387 | This x <- a, That y <- b
388 = Fixup_Update $ These x y
389 | That y <- a, This x <- b
390 = Fixup_Update $ These x y
391 mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
392 fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
393 combineNodeInfos _ nia nib = NodeInfo
394 { _nodeInfo_from = _nodeInfo_from nia
395 , _nodeInfo_to = _nodeInfo_to nib
396 }
397 applyFixup _ ni = \case
398 Fixup_Delete -> Nothing
399 Fixup_Update u -> Just $ NodeInfo
400 { _nodeInfo_from = case _nodeInfo_from ni of
401 f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
402 Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
403 Just (From_Insert v) -> From_Insert $ applyAlways p' v
404 Just From_Delete -> From_Delete
405 Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
406 _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
407 , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
408 }
409 m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
410 getHere :: These a b -> Maybe a
411 getHere = \case
412 This a -> Just a
413 These a _ -> Just a
414 That _ -> Nothing
415 getThere :: These a b -> Maybe b
416 getThere = \case
417 This _ -> Nothing
418 These _ b -> Just b
419 That b -> Just b
421--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
422-- | Compose patches having the same effect as applying the patches in turn:
423-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
424instance ( Ord k
425#if !MIN_VERSION_base(4,11,0)
426 , Semigroup p
427#endif
428 , DecidablyEmpty p
429 , Patch p
430 ) => Monoid (PatchMapWithPatchingMove k p) where
431 mempty = PatchMapWithPatchingMove mempty
432 mappend = (<>)
434makeWrapped ''PatchMapWithPatchingMove