on bb35d68 help sign in
elk/src/Elm/Compiler/Module.hs
140 lines 2.9 kB history raw
1{-# OPTIONS_GHC -Wall #-}
2{-# LANGUAGE OverloadedStrings #-}
3module Elm.Compiler.Module
4 ( Interface, Interfaces
5 , ModuleName.Raw
6 , nameToPath
7 , nameToString, nameFromString
8 , hyphenate, dehyphenate
9 , RawForJson(RawForJson), fromJson
10 , interfaceAliasedTypes, programTypes
11 , ModuleName.Canonical(..), qualifiedVar
12 )
13 where
15import qualified Data.Aeson as Json
16import qualified Data.Char as Char
17import qualified Data.List as List
18import qualified Data.Map as Map
19import qualified Data.Text as Text
20import Data.Text (Text)
21import System.FilePath ((</>))
23import qualified AST.Module as Module
24import qualified AST.Module.Name as ModuleName
25import qualified Elm.Compiler.Type as PublicType
26import qualified Elm.Compiler.Type.Extract as Extract
27import qualified Generate.JavaScript.Variable as Gen
31-- INTERFACES
34type Interface = Module.Interface
37type Interfaces = Module.Interfaces
40interfaceAliasedTypes :: Interface -> Map.Map Text PublicType.Type
41interfaceAliasedTypes interface =
42 Map.map Extract.extract (Module.iTypes interface)
45programTypes :: Interfaces -> ModuleName.Canonical -> Maybe PublicType.Program
46programTypes =
47 Extract.extractProgram
51-- NAMES
54newtype RawForJson = RawForJson ModuleName.Raw
57fromJson :: RawForJson -> ModuleName.Raw
58fromJson (RawForJson raw) =
59 raw
62qualifiedVar :: ModuleName.Canonical -> Text -> Text
63qualifiedVar =
64 Gen.qualified
68-- STRING CONVERSIONS for RAW NAMES
71nameToPath :: ModuleName.Raw -> FilePath
72nameToPath name =
73 List.foldl1 (</>) (map Text.unpack (Text.splitOn "." name))
76nameToString :: ModuleName.Raw -> String
77nameToString name =
78 Text.unpack name
81nameFromString :: String -> Maybe ModuleName.Raw
82nameFromString =
83 fromString '.'
86hyphenate :: ModuleName.Raw -> String
87hyphenate names =
88 Text.unpack (Text.replace "." "-" names)
91dehyphenate :: String -> Maybe ModuleName.Raw
92dehyphenate =
93 fromString '-'
96fromString :: Char -> String -> Maybe ModuleName.Raw
97fromString sep raw =
98 do chunks <- mapM isLegit names
99 return (Text.pack (List.intercalate "." chunks))
100 where
101 names =
102 filter (/= [sep]) (List.groupBy (\a b -> a /= sep && b /= sep) raw)
104 isLegit name =
105 case name of
106 [] ->
107 Nothing
109 char:rest ->
110 if Char.isUpper char && all legitChar rest then Just name else Nothing
112 legitChar char =
113 Char.isAlphaNum char || char == '_'
117-- JSON for NAME
120instance Json.ToJSON RawForJson where
121 toJSON (RawForJson name) =
122 Json.toJSON (nameToString name)
125instance Json.FromJSON RawForJson where
126 parseJSON (Json.String text) =
127 let
128 rawString =
129 Text.unpack text
130 in
131 case nameFromString rawString of
132 Nothing ->
133 fail (rawString ++ " is not a valid module name")
135 Just name ->
136 return (RawForJson name)
138 parseJSON _ =
139 fail "expecting the module name to be a string"