on 4e73834 help sign in
elk/src/Elm/Compiler/Module.hs
148 lines 2.9 kB history raw
1module Elm.Compiler.Module
2 ( Interface, Interfaces
3 , Name(Name)
4 , nameToPath
5 , nameToString, nameFromString
6 , hyphenate, dehyphenate
7 , defaultImports
8 , interfacePorts
9 , interfaceAliasedTypes
10 , CanonicalName, canonicalName
11 )
12 where
14import Control.Monad (mzero)
15import qualified Data.Aeson as Json
16import Data.Binary
17import qualified Data.Char as Char
18import qualified Data.List as List
19import qualified Data.Map as Map
20import qualified Data.Text as Text
21import System.FilePath ((</>))
23import qualified AST.Module as Module
24import qualified AST.Module.Name as ModuleName
25import qualified Elm.Compiler.Imports as Imports
26import qualified Elm.Compiler.Type as Type
27import qualified Elm.Compiler.Type.Extract as Extract
28import qualified Elm.Package as Package
32-- INTERFACES
35type Interface = Module.Interface
38type Interfaces = Module.Interfaces
41interfacePorts :: Interface -> [String]
42interfacePorts interface =
43 Module.iPorts interface
46interfaceAliasedTypes :: Interface -> Map.Map String Type.Type
47interfaceAliasedTypes interface =
48 Map.map Extract.toAliasedType (Module.iTypes interface)
52-- NAMES
55newtype Name = Name ModuleName.Raw
56 deriving (Eq, Ord)
59type CanonicalName = ModuleName.Canonical
62canonicalName :: Package.Name -> Name -> CanonicalName
63canonicalName pkgName (Name name) =
64 ModuleName.Canonical pkgName name
67defaultImports :: [Name]
68defaultImports =
69 map (Name . fst) Imports.defaults
73-- STRING CONVERSIONS for NAMES
76nameToPath :: Name -> FilePath
77nameToPath (Name names) =
78 List.foldl1 (</>) names
81nameToString :: Name -> String
82nameToString (Name names) =
83 List.intercalate "." names
86nameFromString :: String -> Maybe Name
87nameFromString =
88 fromString '.'
91hyphenate :: Name -> String
92hyphenate (Name names) =
93 List.intercalate "-" names
96dehyphenate :: String -> Maybe Name
97dehyphenate =
98 fromString '-'
101fromString :: Char -> String -> Maybe Name
102fromString sep raw =
103 Name `fmap` mapM isLegit names
104 where
105 names =
106 filter (/= [sep]) (List.groupBy (\a b -> a /= sep && b /= sep) raw)
108 isLegit name =
109 case name of
110 [] -> Nothing
111 char:rest ->
112 if Char.isUpper char && all legitChar rest
113 then Just name
114 else Nothing
116 legitChar char =
117 Char.isAlphaNum char || char `elem` "_'"
121-- JSON for NAME
124instance Json.ToJSON Name where
125 toJSON name =
126 Json.toJSON (nameToString name)
129instance Json.FromJSON Name where
130 parseJSON (Json.String text) =
131 let rawName = Text.unpack text in
132 case nameFromString rawName of
133 Nothing -> fail (rawName ++ " is not a valid module name")
134 Just name -> return name
136 parseJSON _ = mzero
140-- BINARY for NAME
143instance Binary Name where
144 get =
145 fmap Name get
147 put (Name names) =
148 put names