2{-# LANGUAGE FlexibleContexts #-}
3{-# LANGUAGE FlexibleInstances #-}
4{-# LANGUAGE LambdaCase #-}
5{-# LANGUAGE MultiParamTypeClasses #-}
6{-# LANGUAGE PatternGuards #-}
7{-# LANGUAGE ScopedTypeVariables #-}
8{-# LANGUAGE StandaloneDeriving #-}
9{-# LANGUAGE TemplateHaskell #-}
10{-# LANGUAGE TypeFamilies #-}
11{-# LANGUAGE UndecidableInstances #-}
13-- | 'Patch'es on 'Map' that can insert, delete, and move values from one key to
15module Data.Patch.MapWithPatchingMove where
17import Data.Patch.Class
20import Control.Lens.TH (makeWrapped)
21import Control.Monad.Trans.State
26import qualified Data.Map as Map
28#if !MIN_VERSION_base(4,10,0)
29import Data.Semigroup (Semigroup (..))
31import Data.Monoid.DecidablyEmpty
32import qualified Data.Set as Set
33import Data.These (These (..))
36-- | Patch a Map with additions, deletions, and moves. Invariant: If key @k1@
37-- is coming from @From_Move k2@, then key @k2@ should be going to @Just k1@,
38-- and vice versa. There should never be any unpaired From/To keys.
39newtype PatchMapWithPatchingMove k p = PatchMapWithPatchingMove
40 { -- | Extract the internal representation of the 'PatchMapWithPatchingMove'
41 unPatchMapWithPatchingMove :: Map k (NodeInfo k p)
44deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (PatchMapWithPatchingMove k p)
45deriving instance (Ord k, Read k, Read p, Read (PatchTarget p)) => Read (PatchMapWithPatchingMove k p)
46deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (PatchMapWithPatchingMove k p)
47deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (PatchMapWithPatchingMove k p)
49-- | Holds the information about each key: where its new value should come from,
50-- and where its old value should go to
51data NodeInfo k p = NodeInfo
52 { _nodeInfo_from :: !(From k p)
53 -- ^ Where do we get the new value for this key?
54 , _nodeInfo_to :: !(To k)
55 -- ^ If the old value is being kept (i.e. moved rather than deleted or
56 -- replaced), where is it going?
58deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (NodeInfo k p)
59deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (NodeInfo k p)
60deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (NodeInfo k p)
61deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (NodeInfo k p)
67 -> (PatchTarget p0 -> f (PatchTarget p1))
68 -> NodeInfo k0 p0 -> f (NodeInfo k1 p1)
69bitraverseNodeInfo fk fp fpt (NodeInfo from to) = NodeInfo
70 <$> bitraverseFrom fk fp fpt from
73-- | Describe how a key's new value should be produced
75 = From_Insert (PatchTarget p) -- ^ Insert the given value here
76 | From_Delete -- ^ Delete the existing value, if any, from here
77 | From_Move !k !p -- ^ Move the value here from the given key, and apply the given patch
83 -> (PatchTarget p0 -> f (PatchTarget p1))
84 -> From k0 p0 -> f (From k1 p1)
85bitraverseFrom fk fp fpt = \case
86 From_Insert pt -> From_Insert <$> fpt pt
87 From_Delete -> pure From_Delete
88 From_Move k p -> From_Move <$> fk k <*> fp p
90deriving instance (Show k, Show p, Show (PatchTarget p)) => Show (From k p)
91deriving instance (Read k, Read p, Read (PatchTarget p)) => Read (From k p)
92deriving instance (Eq k, Eq p, Eq (PatchTarget p)) => Eq (From k p)
93deriving instance (Ord k, Ord p, Ord (PatchTarget p)) => Ord (From k p)
95-- | Describe where a key's old value will go. If this is 'Just', that means
96-- the key's old value will be moved to the given other key; if it is 'Nothing',
97-- that means it will be deleted.
100-- | Create a 'PatchMapWithPatchingMove', validating it
101patchMapWithPatchingMove
102 :: Ord k => Map k (NodeInfo k p) -> Maybe (PatchMapWithPatchingMove k p)
103patchMapWithPatchingMove m = if valid then Just $ PatchMapWithPatchingMove m else Nothing
104 where valid = forwardLinks == backwardLinks
105 forwardLinks = Map.mapMaybe _nodeInfo_to m
106 backwardLinks = Map.fromList $ catMaybes $ flip fmap (Map.toList m) $ \(to, p) ->
107 case _nodeInfo_from p of
108 From_Move from _ -> Just (from, to)
111-- | Create a 'PatchMapWithPatchingMove' that inserts everything in the given 'Map'
112patchMapWithPatchingMoveInsertAll
113 :: Map k (PatchTarget p) -> PatchMapWithPatchingMove k p
114patchMapWithPatchingMoveInsertAll m = PatchMapWithPatchingMove $ flip fmap m $ \v -> NodeInfo
115 { _nodeInfo_from = From_Insert v
116 , _nodeInfo_to = Nothing
119-- | Make a @'PatchMapWithPatchingMove' k p@ which has the effect of inserting or replacing a value @v@ at the given key @k@, like 'Map.insert'.
121 :: k -> PatchTarget p -> PatchMapWithPatchingMove k p
122insertMapKey k v = PatchMapWithPatchingMove . Map.singleton k $ NodeInfo (From_Insert v) Nothing
124-- |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:
127-- 'Map.delete' src (maybe map ('Map.insert' dst) (Map.lookup src map))
130 :: (DecidablyEmpty p, Patch p) => Ord k => k -> k -> PatchMapWithPatchingMove k p
132 | src == dst = mempty
134 PatchMapWithPatchingMove $ Map.fromList
135 [ (dst, NodeInfo (From_Move src mempty) Nothing)
136 , (src, NodeInfo From_Delete (Just dst))
139-- |Make a @'PatchMapWithPatchingMove' k p@ which has the effect of swapping two keys in the mapping, equivalent to:
142-- let aMay = Map.lookup a map
143-- bMay = Map.lookup b map
144-- in maybe id (Map.insert a) (bMay `mplus` aMay)
145-- . maybe id (Map.insert b) (aMay `mplus` bMay)
146-- . Map.delete a . Map.delete b $ map
149 :: (DecidablyEmpty p, Patch p)
150 => Ord k => k -> k -> PatchMapWithPatchingMove k p
152 | src == dst = mempty
154 PatchMapWithPatchingMove $ Map.fromList
155 [ (dst, NodeInfo (From_Move src mempty) (Just src))
156 , (src, NodeInfo (From_Move dst mempty) (Just dst))
159-- | Make a @'PatchMapWithPatchingMove' k v@ which has the effect of deleting a key in
160-- the mapping, equivalent to 'Map.delete'.
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.
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
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 ()
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
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
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'.
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
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
246 if k `Set.member` fromKs
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
251 (fromK, remainingKeys) <- return . fromJust $ Set.minView fromKs -- There's an existing value, but it's not here; move it here
252 putRemainingKeys remainingKeys
253 return $ NodeInfo (From_Move fromK mempty) $ Just undefined
254 Map.traverseWithKey f newByIndex
255 unusedOldKeys = fold unusedValuesByValue
256 pointlessMove k = \case
257 From_Move k' _ | k == k' -> True
259 keyWasMoved k = if k `Map.member` oldByIndex && not (k `Set.member` unusedOldKeys)
262 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
264-- | Change the 'From' value of a 'NodeInfo'
266 :: (From k v -> From k v) -> NodeInfo k v -> NodeInfo k v
267nodeInfoMapFrom f ni = ni { _nodeInfo_from = f $ _nodeInfo_from ni }
269-- | Change the 'From' value of a 'NodeInfo', using a 'Functor' (or
270-- 'Applicative', 'Monad', etc.) action to get the new value
272 :: Functor f => (From k v -> f (From k v)) -> NodeInfo k v -> f (NodeInfo k v)
273nodeInfoMapMFrom f ni = fmap (\result -> ni { _nodeInfo_from = result }) $ f $ _nodeInfo_from ni
275-- | Set the 'To' field of a 'NodeInfo'
277 :: To k -> NodeInfo k v -> NodeInfo k v
278nodeInfoSetTo to ni = ni { _nodeInfo_to = to }
280-- |Helper data structure used for composing patches using the monoid instance.
283 | Fixup_Update (These (From k v) (To k))
285-- |Compose patches having the same effect as applying the patches in turn: @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
290 ) => Semigroup (PatchMapWithPatchingMove k p) where
291 PatchMapWithPatchingMove ma <> PatchMapWithPatchingMove mb = PatchMapWithPatchingMove m
293 connections = Map.toList $ Map.intersectionWithKey (\_ a b -> (_nodeInfo_to a, _nodeInfo_from b)) ma mb
294 h :: (k, (Maybe k, From k p)) -> [(k, Fixup k p)]
295 h (_, (mToAfter, editBefore)) = case (mToAfter, editBefore) of
296 (Just toAfter, From_Move fromBefore p)
297 | fromBefore == toAfter && isEmpty p
298 -> [(toAfter, Fixup_Delete)]
300 -> [ (toAfter, Fixup_Update (This editBefore))
301 , (fromBefore, Fixup_Update (That mToAfter))
303 (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
304 (Just toAfter, _) -> [(toAfter, Fixup_Update (This editBefore))]
306 mergeFixups _ Fixup_Delete Fixup_Delete = Fixup_Delete
307 mergeFixups _ (Fixup_Update a) (Fixup_Update b)
308 | This x <- a, That y <- b
309 = Fixup_Update $ These x y
310 | That y <- a, This x <- b
311 = Fixup_Update $ These x y
312 mergeFixups _ _ _ = error "PatchMapWithPatchingMove: incompatible fixups"
313 fixups = Map.fromListWithKey mergeFixups $ concatMap h connections
314 combineNodeInfos _ nia nib = NodeInfo
315 { _nodeInfo_from = _nodeInfo_from nia
316 , _nodeInfo_to = _nodeInfo_to nib
318 applyFixup _ ni = \case
319 Fixup_Delete -> Nothing
320 Fixup_Update u -> Just $ NodeInfo
321 { _nodeInfo_from = case _nodeInfo_from ni of
322 f@(From_Move _ p') -> case getHere u of -- The `from` fixup comes from the "old" patch
323 Nothing -> f -- If there's no `from` fixup, just use the "new" `from`
324 Just (From_Insert v) -> From_Insert $ applyAlways p' v
325 Just From_Delete -> From_Delete
326 Just (From_Move oldKey p) -> From_Move oldKey $ p' <> p
327 _ -> error "PatchMapWithPatchingMove: fixup for non-move From"
328 , _nodeInfo_to = fromMaybe (_nodeInfo_to ni) $ getThere u
330 m = Map.differenceWithKey applyFixup (Map.unionWithKey combineNodeInfos ma mb) fixups
331 getHere :: These a b -> Maybe a
336 getThere :: These a b -> Maybe b
342--TODO: Figure out how to implement this in terms of PatchDMapWithPatchingMove rather than duplicating it here
343-- | Compose patches having the same effect as applying the patches in turn:
344-- @'applyAlways' (p <> q) == 'applyAlways' p . 'applyAlways' q@
349 ) => Monoid (PatchMapWithPatchingMove k p) where
350 mempty = PatchMapWithPatchingMove mempty
353makeWrapped ''PatchMapWithPatchingMove
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list