on 2d29699 help sign in
elk/src/Elm/Compiler/Module.hs
138 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
31-- INTERFACES
33type Interface = Module.Interface
36type Interfaces = Module.Interfaces
39interfacePorts :: Interface -> [String]
40interfacePorts interface =
41 Module.iPorts interface
44interfaceAliasedTypes :: Interface -> Map.Map String Type.Type
45interfaceAliasedTypes interface =
46 Map.map Extract.toAliasedType (Module.iTypes interface)
49-- NAMES
51newtype Name = Name ModuleName.Raw
52 deriving (Eq, Ord)
55type CanonicalName = ModuleName.Canonical
58canonicalName :: Package.Name -> Name -> CanonicalName
59canonicalName pkgName (Name name) =
60 ModuleName.Canonical pkgName name
63defaultImports :: [Name]
64defaultImports =
65 map (Name . fst) Imports.defaults
68-- STRING CONVERSIONS for NAMES
70nameToPath :: Name -> FilePath
71nameToPath (Name names) =
72 List.foldl1 (</>) names
75nameToString :: Name -> String
76nameToString (Name names) =
77 List.intercalate "." names
80nameFromString :: String -> Maybe Name
81nameFromString =
82 fromString '.'
85hyphenate :: Name -> String
86hyphenate (Name names) =
87 List.intercalate "-" names
90dehyphenate :: String -> Maybe Name
91dehyphenate =
92 fromString '-'
95fromString :: Char -> String -> Maybe Name
96fromString sep raw =
97 Name `fmap` mapM isLegit names
98 where
99 names =
100 filter (/= [sep]) (List.groupBy (\a b -> a /= sep && b /= sep) raw)
102 isLegit name =
103 case name of
104 [] -> Nothing
105 char:rest ->
106 if Char.isUpper char && all legitChar rest
107 then Just name
108 else Nothing
110 legitChar char =
111 Char.isAlphaNum char || char `elem` "_'"
114-- JSON for NAME
116instance Json.ToJSON Name where
117 toJSON name =
118 Json.toJSON (nameToString name)
121instance Json.FromJSON Name where
122 parseJSON (Json.String text) =
123 let rawName = Text.unpack text in
124 case nameFromString rawName of
125 Nothing -> fail (rawName ++ " is not a valid module name")
126 Just name -> return name
128 parseJSON _ = mzero
131-- BINARY for NAME
133instance Binary Name where
134 get =
135 fmap Name get
137 put (Name names) =
138 put names