module Language.PureScript.Names where
import Control.Monad (liftM)
import Control.Monad.Supply.Class
import Data.List
import Data.Aeson
import Data.Aeson.TH
data Ident
= Ident String
| Op String
| GenIdent (Maybe String) Integer
deriving (Show, Read, Eq, Ord)
runIdent :: Ident -> String
runIdent (Ident i) = i
runIdent (Op op) = op
runIdent (GenIdent Nothing n) = "$" ++ show n
runIdent (GenIdent (Just name) n) = "$" ++ name ++ show n
showIdent :: Ident -> String
showIdent (Op op) = '(' : op ++ ")"
showIdent i = runIdent i
freshIdent :: (MonadSupply m) => String -> m Ident
freshIdent name = liftM (GenIdent (Just name)) fresh
freshIdent' :: (MonadSupply m) => m Ident
freshIdent' = liftM (GenIdent Nothing) fresh
newtype ProperName (a :: ProperNameType) = ProperName { runProperName :: String }
deriving (Show, Read, Eq, Ord)
instance ToJSON (ProperName a) where
toJSON = toJSON . runProperName
instance FromJSON (ProperName a) where
parseJSON = fmap ProperName . parseJSON
data ProperNameType = TypeName | ConstructorName | ClassName | Namespace
coerceProperName :: ProperName a -> ProperName b
coerceProperName = ProperName . runProperName
newtype ModuleName = ModuleName [ProperName 'Namespace]
deriving (Show, Read, Eq, Ord)
runModuleName :: ModuleName -> String
runModuleName (ModuleName pns) = intercalate "." (runProperName `map` pns)
moduleNameFromString :: String -> ModuleName
moduleNameFromString = ModuleName . splitProperNames
where
splitProperNames s = case dropWhile (== '.') s of
"" -> []
s' -> ProperName w : splitProperNames s''
where (w, s'') = break (== '.') s'
data Qualified a = Qualified (Maybe ModuleName) a
deriving (Show, Read, Eq, Ord, Functor)
showQualified :: (a -> String) -> Qualified a -> String
showQualified f (Qualified Nothing a) = f a
showQualified f (Qualified (Just name) a) = runModuleName name ++ "." ++ f a
qualify :: ModuleName -> Qualified a -> (ModuleName, a)
qualify m (Qualified Nothing a) = (m, a)
qualify _ (Qualified (Just m) a) = (m, a)
mkQualified :: a -> ModuleName -> Qualified a
mkQualified name mn = Qualified (Just mn) name
disqualify :: Qualified a -> a
disqualify (Qualified _ a) = a
isQualified :: Qualified a -> Bool
isQualified (Qualified Nothing _) = False
isQualified _ = True
isUnqualified :: Qualified a -> Bool
isUnqualified = not . isQualified
isQualifiedWith :: ModuleName -> Qualified a -> Bool
isQualifiedWith mn (Qualified (Just mn') _) = mn == mn'
isQualifiedWith _ _ = False
$(deriveJSON (defaultOptions { sumEncoding = ObjectWithSingleField }) ''Qualified)
$(deriveJSON (defaultOptions { sumEncoding = ObjectWithSingleField }) ''Ident)
$(deriveJSON (defaultOptions { sumEncoding = ObjectWithSingleField }) ''ModuleName)