{-# LANGUAGE DeriveGeneric #-}
module Language.PureScript.Environment where
import Prelude.Compat
import Protolude (ordNub)
import GHC.Generics (Generic)
import Control.DeepSeq (NFData)
import Data.Aeson ((.=), (.:))
import qualified Data.Aeson as A
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Maybe (fromMaybe, mapMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Tree (Tree, rootLabel)
import qualified Data.Graph as G
import Data.Foldable (toList, fold)
import qualified Data.List.NonEmpty as NEL
import Language.PureScript.AST.SourcePos
import Language.PureScript.Crash
import Language.PureScript.Kinds
import Language.PureScript.Names
import Language.PureScript.TypeClassDictionaries
import Language.PureScript.Types
import qualified Language.PureScript.Constants as C
data Environment = Environment
{ names :: M.Map (Qualified Ident) (SourceType, NameKind, NameVisibility)
, types :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
, dataConstructors :: M.Map (Qualified (ProperName 'ConstructorName)) (DataDeclType, ProperName 'TypeName, SourceType, [Ident])
, typeSynonyms :: M.Map (Qualified (ProperName 'TypeName)) ([(Text, Maybe SourceKind)], SourceType)
, typeClassDictionaries :: M.Map (Maybe ModuleName) (M.Map (Qualified (ProperName 'ClassName)) (M.Map (Qualified Ident) (NEL.NonEmpty NamedDict)))
, typeClasses :: M.Map (Qualified (ProperName 'ClassName)) TypeClassData
, kinds :: S.Set (Qualified (ProperName 'KindName))
} deriving (Show, Generic)
instance NFData Environment
data TypeClassData = TypeClassData
{ typeClassArguments :: [(Text, Maybe SourceKind)]
, typeClassMembers :: [(Ident, SourceType)]
, typeClassSuperclasses :: [SourceConstraint]
, typeClassDependencies :: [FunctionalDependency]
, typeClassDeterminedArguments :: S.Set Int
, typeClassCoveringSets :: S.Set (S.Set Int)
} deriving (Show, Generic)
instance NFData TypeClassData
data FunctionalDependency = FunctionalDependency
{ fdDeterminers :: [Int]
, fdDetermined :: [Int]
} deriving (Show, Generic)
instance NFData FunctionalDependency
instance A.FromJSON FunctionalDependency where
parseJSON = A.withObject "FunctionalDependency" $ \o ->
FunctionalDependency
<$> o .: "determiners"
<*> o .: "determined"
instance A.ToJSON FunctionalDependency where
toJSON FunctionalDependency{..} =
A.object [ "determiners" .= fdDeterminers
, "determined" .= fdDetermined
]
initEnvironment :: Environment
initEnvironment = Environment M.empty allPrimTypes M.empty M.empty M.empty allPrimClasses allPrimKinds
makeTypeClassData
:: [(Text, Maybe SourceKind)]
-> [(Ident, SourceType)]
-> [SourceConstraint]
-> [FunctionalDependency]
-> TypeClassData
makeTypeClassData args m s deps = TypeClassData args m s deps determinedArgs coveringSets
where
argumentIndicies = [0 .. length args - 1]
identities = (\i -> (i, [i])) <$> argumentIndicies
contributingDeps = M.fromListWith (++) $ identities ++ do
fd <- deps
src <- fdDeterminers fd
(src, fdDetermined fd) : map (, []) (fdDetermined fd)
(depGraph, fromVertex, fromKey) = G.graphFromEdges ((\(n, v) -> (n, n, ordNub v)) <$> M.toList contributingDeps)
isFunDepDetermined :: Int -> Bool
isFunDepDetermined arg = case fromKey arg of
Nothing -> internalError "Unknown argument index in makeTypeClassData"
Just v -> let contributesToVar = G.reachable (G.transposeG depGraph) v
varContributesTo = G.reachable depGraph v
in any (\r -> not (r `elem` varContributesTo)) contributesToVar
determinedArgs :: S.Set Int
determinedArgs = S.fromList $ filter isFunDepDetermined argumentIndicies
argFromVertex :: G.Vertex -> Int
argFromVertex index = let (_, arg, _) = fromVertex index in arg
isVertexDetermined :: G.Vertex -> Bool
isVertexDetermined = isFunDepDetermined . argFromVertex
sccNonDetermined :: Tree G.Vertex -> Maybe [Int]
sccNonDetermined tree
| isVertexDetermined (rootLabel tree) = Nothing
| otherwise = Just (argFromVertex <$> toList tree)
coveringSets :: S.Set (S.Set Int)
coveringSets = let funDepSets = sequence (mapMaybe sccNonDetermined (G.scc depGraph))
in S.fromList (S.fromList <$> funDepSets)
data NameVisibility
= Undefined
| Defined
deriving (Show, Eq, Generic)
instance NFData NameVisibility
data NameKind
= Private
| Public
| External
deriving (Show, Eq, Generic)
instance NFData NameKind
data TypeKind
= DataType [(Text, Maybe SourceKind)] [(ProperName 'ConstructorName, [SourceType])]
| TypeSynonym
| ExternData
| LocalTypeVariable
| ScopedTypeVar
deriving (Show, Eq, Generic)
instance NFData TypeKind
instance A.ToJSON TypeKind where
toJSON (DataType args ctors) =
A.object [ T.pack "DataType" .= A.object ["args" .= args, "ctors" .= ctors] ]
toJSON TypeSynonym = A.toJSON (T.pack "TypeSynonym")
toJSON ExternData = A.toJSON (T.pack "ExternData")
toJSON LocalTypeVariable = A.toJSON (T.pack "LocalTypeVariable")
toJSON ScopedTypeVar = A.toJSON (T.pack "ScopedTypeVar")
instance A.FromJSON TypeKind where
parseJSON (A.Object o) = do
args <- o .: "DataType"
A.withObject "args" (\o1 ->
DataType <$> o1 .: "args"
<*> o1 .: "ctors") args
parseJSON (A.String s) =
case s of
"TypeSynonym" -> pure TypeSynonym
"ExternData" -> pure ExternData
"LocalTypeVariable" -> pure LocalTypeVariable
"ScopedTypeVar" -> pure ScopedTypeVar
_ -> fail "Unknown TypeKind"
parseJSON _ = fail "Invalid TypeKind"
data DataDeclType
= Data
| Newtype
deriving (Show, Eq, Ord, Generic)
instance NFData DataDeclType
showDataDeclType :: DataDeclType -> Text
showDataDeclType Data = "data"
showDataDeclType Newtype = "newtype"
instance A.ToJSON DataDeclType where
toJSON = A.toJSON . showDataDeclType
instance A.FromJSON DataDeclType where
parseJSON = A.withText "DataDeclType" $ \str ->
case str of
"data" -> return Data
"newtype" -> return Newtype
other -> fail $ "invalid type: '" ++ T.unpack other ++ "'"
primName :: Text -> Qualified (ProperName a)
primName = Qualified (Just $ ModuleName [ProperName C.prim]) . ProperName
primSubName :: Text -> Text -> Qualified (ProperName a)
primSubName sub =
Qualified (Just $ ModuleName [ProperName C.prim, ProperName sub]) . ProperName
primKind :: Text -> SourceKind
primKind = NamedKind nullSourceAnn . primName
primSubKind :: Text -> Text -> SourceKind
primSubKind sub = NamedKind nullSourceAnn . primSubName sub
kindType :: SourceKind
kindType = primKind C.typ
kindConstraint :: SourceKind
kindConstraint = kindType
isKindType :: Kind a -> Bool
isKindType (NamedKind _ n) = n == primName C.typ
isKindType _ = False
(-:>) :: SourceKind -> SourceKind -> SourceKind
(-:>) = FunKind nullSourceAnn
infixr 4 -:>
kindSymbol :: SourceKind
kindSymbol = primKind C.symbol
kindDoc :: SourceKind
kindDoc = primSubKind C.typeError C.doc
kindBoolean :: SourceKind
kindBoolean = primSubKind C.moduleBoolean C.kindBoolean
kindOrdering :: SourceKind
kindOrdering = primSubKind C.moduleOrdering C.kindOrdering
kindRowList :: SourceKind
kindRowList = primSubKind C.moduleRowList C.kindRowList
kindRow :: SourceKind -> SourceKind
kindRow = Row nullSourceAnn
primTy :: Text -> SourceType
primTy = TypeConstructor nullSourceAnn . primName
tyFunction :: SourceType
tyFunction = primTy "Function"
tyString :: SourceType
tyString = primTy "String"
tyChar :: SourceType
tyChar = primTy "Char"
tyNumber :: SourceType
tyNumber = primTy "Number"
tyInt :: SourceType
tyInt = primTy "Int"
tyBoolean :: SourceType
tyBoolean = primTy "Boolean"
tyArray :: SourceType
tyArray = primTy "Array"
tyRecord :: SourceType
tyRecord = primTy "Record"
isObject :: Type a -> Bool
isObject = isTypeOrApplied tyRecord
isFunction :: Type a -> Bool
isFunction = isTypeOrApplied tyFunction
isTypeOrApplied :: Type a -> Type b -> Bool
isTypeOrApplied t1 (TypeApp _ t2 _) = eqType t1 t2
isTypeOrApplied t1 t2 = eqType t1 t2
function :: SourceType -> SourceType -> SourceType
function t1 t2 = TypeApp nullSourceAnn (TypeApp nullSourceAnn tyFunction t1) t2
primKinds :: S.Set (Qualified (ProperName 'KindName))
primKinds = S.fromList
[ primName C.typ
, primName C.symbol
]
primBooleanKinds :: S.Set (Qualified (ProperName 'KindName))
primBooleanKinds = S.fromList
[ primSubName C.moduleBoolean C.kindBoolean
]
primOrderingKinds :: S.Set (Qualified (ProperName 'KindName))
primOrderingKinds = S.fromList
[ primSubName C.moduleOrdering C.kindOrdering
]
primRowListKinds :: S.Set (Qualified (ProperName 'KindName))
primRowListKinds = S.fromList
[ primSubName C.moduleRowList C.kindRowList
]
primTypeErrorKinds :: S.Set (Qualified (ProperName 'KindName))
primTypeErrorKinds = S.fromList
[ primSubName C.typeError C.doc
]
allPrimKinds :: S.Set (Qualified (ProperName 'KindName))
allPrimKinds = fold
[ primKinds
, primBooleanKinds
, primOrderingKinds
, primRowListKinds
, primTypeErrorKinds
]
primTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
primTypes = M.fromList
[ (primName "Function", (kindType -:> kindType -:> kindType, ExternData))
, (primName "Array", (kindType -:> kindType, ExternData))
, (primName "Record", (kindRow kindType -:> kindType, ExternData))
, (primName "String", (kindType, ExternData))
, (primName "Char", (kindType, ExternData))
, (primName "Number", (kindType, ExternData))
, (primName "Int", (kindType, ExternData))
, (primName "Boolean", (kindType, ExternData))
, (primName "Partial", (kindConstraint, ExternData))
]
allPrimTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
allPrimTypes = M.unions
[ primTypes
, primBooleanTypes
, primOrderingTypes
, primRowTypes
, primRowListTypes
, primSymbolTypes
, primTypeErrorTypes
]
primBooleanTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
primBooleanTypes =
M.fromList
[ (primSubName C.moduleBoolean "True", (kindBoolean, ExternData))
, (primSubName C.moduleBoolean "False", (kindBoolean, ExternData))
]
primOrderingTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
primOrderingTypes =
M.fromList
[ (primSubName C.moduleOrdering "LT", (kindOrdering, ExternData))
, (primSubName C.moduleOrdering "EQ", (kindOrdering, ExternData))
, (primSubName C.moduleOrdering "GT", (kindOrdering, ExternData))
]
primRowTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
primRowTypes =
M.fromList
[ (primSubName C.moduleRow "Union", (kindRow kindType -:> kindRow kindType -:> kindRow kindType -:> kindConstraint, ExternData))
, (primSubName C.moduleRow "Nub", (kindRow kindType -:> kindRow kindType -:> kindConstraint, ExternData))
, (primSubName C.moduleRow "Lacks", (kindSymbol -:> kindRow kindType -:> kindConstraint, ExternData))
, (primSubName C.moduleRow "Cons", (kindSymbol -:> kindType -:> kindRow kindType -:> kindRow kindType -:> kindConstraint, ExternData))
]
primRowListTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
primRowListTypes =
M.fromList
[ (primSubName C.moduleRowList "Cons", (kindSymbol -:> kindType -:> kindRowList -:> kindRowList, ExternData))
, (primSubName C.moduleRowList "Nil", (kindRowList, ExternData))
, (primSubName C.moduleRowList "RowToList", (kindRow kindType -:> kindRowList -:> kindConstraint, ExternData))
]
primSymbolTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
primSymbolTypes =
M.fromList
[ (primSubName C.moduleSymbol "Append", (kindSymbol -:> kindSymbol -:> kindSymbol -:> kindConstraint, ExternData))
, (primSubName C.moduleSymbol "Compare", (kindSymbol -:> kindSymbol -:> kindOrdering -:> kindConstraint, ExternData))
, (primSubName C.moduleSymbol "Cons", (kindSymbol -:> kindSymbol -:> kindSymbol -:> kindConstraint, ExternData))
]
primTypeErrorTypes :: M.Map (Qualified (ProperName 'TypeName)) (SourceKind, TypeKind)
primTypeErrorTypes =
M.fromList
[ (primSubName C.typeError "Fail", (kindDoc -:> kindConstraint, ExternData))
, (primSubName C.typeError "Warn", (kindDoc -:> kindConstraint, ExternData))
, (primSubName C.typeError "Text", (kindSymbol -:> kindDoc, ExternData))
, (primSubName C.typeError "Quote", (kindType -:> kindDoc, ExternData))
, (primSubName C.typeError "QuoteLabel", (kindSymbol -:> kindDoc, ExternData))
, (primSubName C.typeError "Beside", (kindDoc -:> kindDoc -:> kindDoc, ExternData))
, (primSubName C.typeError "Above", (kindDoc -:> kindDoc -:> kindDoc, ExternData))
]
primClasses :: M.Map (Qualified (ProperName 'ClassName)) TypeClassData
primClasses =
M.fromList
[ (primName "Partial", (makeTypeClassData [] [] [] []))
]
allPrimClasses :: M.Map (Qualified (ProperName 'ClassName)) TypeClassData
allPrimClasses = M.unions
[ primClasses
, primRowClasses
, primRowListClasses
, primSymbolClasses
, primTypeErrorClasses
]
primRowClasses :: M.Map (Qualified (ProperName 'ClassName)) TypeClassData
primRowClasses =
M.fromList
[ (primSubName C.moduleRow "Union", makeTypeClassData
[ ("left", Just (kindRow kindType))
, ("right", Just (kindRow kindType))
, ("union", Just (kindRow kindType))
] [] []
[ FunctionalDependency [0, 1] [2]
, FunctionalDependency [1, 2] [0]
, FunctionalDependency [2, 0] [1]
])
, (primSubName C.moduleRow "Nub", makeTypeClassData
[ ("original", Just (kindRow kindType))
, ("nubbed", Just (kindRow kindType))
] [] []
[ FunctionalDependency [0] [1]
])
, (primSubName C.moduleRow "Lacks", makeTypeClassData
[ ("label", Just kindSymbol)
, ("row", Just (kindRow kindType))
] [] [] [])
, (primSubName C.moduleRow "Cons", makeTypeClassData
[ ("label", Just kindSymbol)
, ("a", Just kindType)
, ("tail", Just (kindRow kindType))
, ("row", Just (kindRow kindType))
] [] []
[ FunctionalDependency [0, 1, 2] [3]
, FunctionalDependency [0, 3] [1, 2]
])
]
primRowListClasses :: M.Map (Qualified (ProperName 'ClassName)) TypeClassData
primRowListClasses =
M.fromList
[ (primSubName C.moduleRowList "RowToList", makeTypeClassData
[ ("row", Just (kindRow kindType))
, ("list", Just kindRowList)
] [] []
[ FunctionalDependency [0] [1]
])
]
primSymbolClasses :: M.Map (Qualified (ProperName 'ClassName)) TypeClassData
primSymbolClasses =
M.fromList
[ (primSubName C.moduleSymbol "Append", makeTypeClassData
[ ("left", Just kindSymbol)
, ("right", Just kindSymbol)
, ("appended", Just kindSymbol)
] [] []
[ FunctionalDependency [0, 1] [2]
, FunctionalDependency [1, 2] [0]
, FunctionalDependency [2, 0] [1]
])
, (primSubName C.moduleSymbol "Compare", makeTypeClassData
[ ("left", Just kindSymbol)
, ("right", Just kindSymbol)
, ("ordering", Just kindOrdering)
] [] []
[ FunctionalDependency [0, 1] [2]
])
, (primSubName C.moduleSymbol "Cons", makeTypeClassData
[ ("head", Just kindSymbol)
, ("tail", Just kindSymbol)
, ("symbol", Just kindSymbol)
] [] []
[ FunctionalDependency [0, 1] [2]
, FunctionalDependency [2] [0, 1]
])
]
primTypeErrorClasses :: M.Map (Qualified (ProperName 'ClassName)) TypeClassData
primTypeErrorClasses =
M.fromList
[ (primSubName C.typeError "Fail", makeTypeClassData
[("message", Just kindDoc)] [] [] [])
, (primSubName C.typeError "Warn", makeTypeClassData
[("message", Just kindDoc)] [] [] [])
]
lookupConstructor :: Environment -> Qualified (ProperName 'ConstructorName) -> (DataDeclType, ProperName 'TypeName, SourceType, [Ident])
lookupConstructor env ctor =
fromMaybe (internalError "Data constructor not found") $ ctor `M.lookup` dataConstructors env
isNewtypeConstructor :: Environment -> Qualified (ProperName 'ConstructorName) -> Bool
isNewtypeConstructor e ctor = case lookupConstructor e ctor of
(Newtype, _, _, _) -> True
(Data, _, _, _) -> False
lookupValue :: Environment -> Qualified Ident -> Maybe (SourceType, NameKind, NameVisibility)
lookupValue env ident = ident `M.lookup` names env