on bbb6583 help sign in
elk/src/Elm/Compiler/Module.hs
138 lines 2.8 kB history raw
1module Elm.Compiler.Module
2 ( Interface, Interfaces
3 , ModuleName.Raw
4 , nameToPath
5 , nameToString, nameFromString
6 , hyphenate, dehyphenate
7 , RawForJson(RawForJson), fromJson
8 , defaultImports
9 , interfaceAliasedTypes
10 , ModuleName.Canonical(..), qualifiedVar
11 )
12 where
14import qualified Data.Aeson as Json
15import qualified Data.Char as Char
16import qualified Data.List as List
17import qualified Data.Map as Map
18import qualified Data.Text as Text
19import System.FilePath ((</>))
21import qualified AST.Module as Module
22import qualified AST.Module.Name as ModuleName
23import qualified Elm.Compiler.Imports as Imports
24import qualified Elm.Compiler.Type as Type
25import qualified Elm.Compiler.Type.Extract as Extract
26import qualified Generate.JavaScript.Variable as Gen
30-- INTERFACES
33type Interface = Module.Interface
36type Interfaces = Module.Interfaces
39interfaceAliasedTypes :: Interface -> Map.Map String Type.Type
40interfaceAliasedTypes interface =
41 Map.map Extract.toAliasedType (Module.iTypes interface)
45-- NAMES
48newtype RawForJson = RawForJson ModuleName.Raw
51fromJson :: RawForJson -> ModuleName.Raw
52fromJson (RawForJson raw) =
53 raw
56qualifiedVar :: ModuleName.Canonical -> String -> String
57qualifiedVar =
58 Gen.qualified
61defaultImports :: [ModuleName.Raw]
62defaultImports =
63 map fst Imports.defaults
67-- STRING CONVERSIONS for RAW NAMES
70nameToPath :: ModuleName.Raw -> FilePath
71nameToPath names =
72 List.foldl1 (</>) names
75nameToString :: ModuleName.Raw -> String
76nameToString names =
77 List.intercalate "." names
80nameFromString :: String -> Maybe ModuleName.Raw
81nameFromString =
82 fromString '.'
85hyphenate :: ModuleName.Raw -> String
86hyphenate names =
87 List.intercalate "-" names
90dehyphenate :: String -> Maybe ModuleName.Raw
91dehyphenate =
92 fromString '-'
95fromString :: Char -> String -> Maybe ModuleName.Raw
96fromString sep raw =
97 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` "_'"
115-- JSON for NAME
118instance Json.ToJSON RawForJson where
119 toJSON (RawForJson name) =
120 Json.toJSON (nameToString name)
123instance Json.FromJSON RawForJson where
124 parseJSON (Json.String text) =
125 let
126 rawString =
127 Text.unpack text
128 in
129 case nameFromString rawString of
130 Nothing ->
131 fail (rawString ++ " is not a valid module name")
133 Just name ->
134 return (RawForJson name)
136 parseJSON _ =
137 fail "expecting the module name to be a string"