git.iko.soy/rowtype-yoga/purescript-native
on 532e62d help sign in
102 lines 2.9 kB history raw
1-----------------------------------------------------------------------------
2--
3-- Module : Language.PureScript.Names
4-- Copyright : (c) Phil Freeman 2013
5-- License : MIT
6--
7-- Maintainer : Phil Freeman <paf31@cantab.net>
8-- Stability : experimental
9-- Portability :
10--
11-- |
12-- Data types for names
13--
14-----------------------------------------------------------------------------
16{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, GADTs #-}
18module Language.PureScript.Names where
20import Data.List
21import Data.Data
22import Data.List.Split (splitOn)
23import qualified Data.Aeson as A
24import qualified Data.Text as T
26-- |
27-- Names for value identifiers
28--
29data Ident
30 -- |
31 -- An alphanumeric identifier
32 --
33 = Ident String
34 -- |
35 -- A symbolic name for an infix operator
36 --
37 | Op String deriving (Eq, Ord, Data, Typeable)
39runIdent :: Ident -> String
40runIdent (Ident i) = i
41runIdent (Op op) = op
43instance Show Ident where
44 show (Ident s) = s
45 show (Op op) = '(':op ++ ")"
47-- |
48-- Proper names, i.e. capitalized names for e.g. module names, type//data constructors.
49--
50newtype ProperName = ProperName { runProperName :: String } deriving (Eq, Ord, Data, Typeable)
52instance Show ProperName where
53 show = runProperName
55-- |
56-- Module names
57--
58data ModuleName = ModuleName [ProperName] deriving (Eq, Ord, Data, Typeable)
60runModuleName :: ModuleName -> String
61runModuleName (ModuleName pns) = intercalate "." (runProperName `map` pns)
63moduleNameFromString :: String -> ModuleName
64moduleNameFromString = ModuleName . splitProperNames
65 where
66 splitProperNames s = case dropWhile (== '.') s of
67 "" -> []
68 s' -> ProperName w : splitProperNames s''
69 where (w, s'') = break (== '.') s'
71instance Show ModuleName where
72 show = runModuleName
74-- |
75-- A qualified name, i.e. a name with an optional module name
76--
77data Qualified a = Qualified (Maybe ModuleName) a deriving (Eq, Ord, Data, Typeable, Functor)
79instance (Show a) => Show (Qualified a) where
80 show (Qualified Nothing a) = show a
81 show (Qualified (Just name) a) = show name ++ "." ++ show a
83instance (a ~ ProperName) => A.ToJSON (Qualified a) where
84 toJSON = A.toJSON . show
86instance (a ~ ProperName) => A.FromJSON (Qualified a) where
87 parseJSON =
88 A.withText "Qualified ProperName" $ \str ->
89 return $ case reverse (splitOn "." (T.unpack str)) of
90 [name] -> Qualified Nothing (ProperName name)
91 (name:rest) -> Qualified (Just (reconstructModuleName rest)) (ProperName name)
92 _ -> Qualified Nothing (ProperName "")
93 where
94 reconstructModuleName = moduleNameFromString . intercalate "." . reverse
97-- |
98-- Provide a default module name, if a name is unqualified
99--
100qualify :: ModuleName -> Qualified a -> (ModuleName, a)
101qualify m (Qualified Nothing a) = (m, a)
102qualify _ (Qualified (Just m) a) = (m, a)