on 92be75c help sign in
elk/src/Elm/Compiler/Module.hs
80 lines 1.8 kB history raw
1module Elm.Compiler.Module
2 ( Interface, Name(Name)
3 , nameToPath
4 , nameToString, nameFromString
5 , hyphenate, dehyphenate
6 )
7 where
9import Control.Monad (mzero)
10import qualified Data.Aeson as Json
11import qualified Data.Char as Char
12import qualified Data.List as List
13import qualified Data.Text as Text
14import System.FilePath ((</>))
15import qualified AST.Module as Module
18type Interface = Module.Interface
20newtype Name = Name [String]
21 deriving (Eq, Ord)
24nameToPath :: Name -> FilePath
25nameToPath (Name names) =
26 List.foldl1 (</>) names
29nameToString :: Name -> String
30nameToString (Name names) =
31 List.intercalate "." names
34nameFromString :: String -> Maybe Name
35nameFromString =
36 fromString '.'
39hyphenate :: Name -> String
40hyphenate (Name names) =
41 List.intercalate "-" names
44dehyphenate :: String -> Maybe Name
45dehyphenate =
46 fromString '-'
49fromString :: Char -> String -> Maybe Name
50fromString sep raw =
51 Name `fmap` mapM isLegit names
52 where
53 names =
54 filter (/= [sep]) (List.groupBy (\a b -> a /= sep && b /= sep) raw)
56 isLegit name =
57 case name of
58 [] -> Nothing
59 char:rest ->
60 if Char.isUpper char && all legitChar rest
61 then Just name
62 else Nothing
64 legitChar char =
65 Char.isAlphaNum char || char `elem` "_'"
68instance Json.ToJSON Name where
69 toJSON name =
70 Json.toJSON (nameToString name)
73instance Json.FromJSON Name where
74 parseJSON (Json.String text) =
75 let rawName = Text.unpack text in
76 case nameFromString rawName of
77 Nothing -> fail (rawName ++ " is not a valid module name")
78 Just name -> return name
80 parseJSON _ = mzero