on db31fe2 help sign in
elk/src/Elm/Compiler/Module.hs
89 lines 2.0 kB history raw
1module Elm.Compiler.Module
2 ( Interface, Name(Name)
3 , nameToPath
4 , nameToString, nameFromString
5 , hyphenate, dehyphenate
6 , defaultImports
7 )
8 where
10import Control.Monad (mzero)
11import qualified Data.Aeson as Json
12import qualified Data.Char as Char
13import qualified Data.List as List
14import qualified Data.Map as Map
15import qualified Data.Text as Text
16import System.FilePath ((</>))
18import qualified AST.Module as Module
19import qualified Transform.AddDefaultImports as Defaults
22type Interface = Module.Interface
24newtype Name = Name [String]
25 deriving (Eq, Ord)
28defaultImports :: [Name]
29defaultImports =
30 map Name (Map.keys Defaults.defaultImports)
33nameToPath :: Name -> FilePath
34nameToPath (Name names) =
35 List.foldl1 (</>) names
38nameToString :: Name -> String
39nameToString (Name names) =
40 List.intercalate "." names
43nameFromString :: String -> Maybe Name
44nameFromString =
45 fromString '.'
48hyphenate :: Name -> String
49hyphenate (Name names) =
50 List.intercalate "-" names
53dehyphenate :: String -> Maybe Name
54dehyphenate =
55 fromString '-'
58fromString :: Char -> String -> Maybe Name
59fromString sep raw =
60 Name `fmap` mapM isLegit names
61 where
62 names =
63 filter (/= [sep]) (List.groupBy (\a b -> a /= sep && b /= sep) raw)
65 isLegit name =
66 case name of
67 [] -> Nothing
68 char:rest ->
69 if Char.isUpper char && all legitChar rest
70 then Just name
71 else Nothing
73 legitChar char =
74 Char.isAlphaNum char || char `elem` "_'"
77instance Json.ToJSON Name where
78 toJSON name =
79 Json.toJSON (nameToString name)
82instance Json.FromJSON Name where
83 parseJSON (Json.String text) =
84 let rawName = Text.unpack text in
85 case nameFromString rawName of
86 Nothing -> fail (rawName ++ " is not a valid module name")
87 Just name -> return name
89 parseJSON _ = mzero