alanz / ghc-exactprint

GHC version of haskell-src-exts exactPrint
BSD 3-Clause "New" or "Revised" License
70 stars 32 forks source link

graftT #36

Closed xich closed 8 years ago

xich commented 8 years ago

I have found this function useful when copying an AST fragment from one module to another:

graftT :: (Data a,Typeable a) => Anns -> a -> Transform a
graftT origAnns = everywhereM (return `ext2M` replaceLocated)
  where
    replaceLocated :: forall loc a. (Typeable loc, Typeable a, Data a)
                    => GenLocated loc a -> Transform (GenLocated loc a)
    replaceLocated (L l t) = do
      case cast l :: Maybe SrcSpan of
        Just ss -> do
          newSpan <- uniqueSrcSpanT
          modifyAnnsT (\anns -> case M.lookup (mkAnnKey (L ss t)) origAnns of
                                  Nothing -> anns
                                  Just an -> M.insert (mkAnnKey (L newSpan t)) an anns)
          return $ fromJust $ cast $ L newSpan t
        Nothing -> return (L l t)

(it is a slightly more general form of cloneT)

Pasting here in case you want to include it with ghc-exactprint.

alanz commented 8 years ago

Thanks, will do. Starting to prepare the GHC-8.0.1 release

xich commented 8 years ago

Meant to say:

cloneT ast = do
  anns <- getAnnsT
  graftT anns ast

Don't remember why I stripped the Writer stuff out... probably just because I wasn't using it.