@@ -12,6 +12,7 @@ module Language.PureScript.PSString
13import Prelude.Compat
13import Prelude.Compat
14import Control.Exception (try, evaluate)
14import Control.Exception (try, evaluate)
15+import Control.Applicative ((<|>))
15import Data.Char (chr)
16import Data.Char (chr)
16import Data.Bits (shiftR)
17import Data.Bits (shiftR)
17import Data.List (unfoldr)
18import Data.List (unfoldr)
@@ -40,6 +41,11 @@ import qualified Data.Aeson.Types as A
40-- The Show instance for PSString produces a string literal which would
41-- The Show instance for PSString produces a string literal which would
41-- represent the same data were it inserted into a PureScript source file.
42-- represent the same data were it inserted into a PureScript source file.
44+-- Because JSON parsers vary wildly in terms of how they deal with lone
45+-- surrogates in JSON strings, the ToJSON instance for PSString produces JSON
46+-- strings where that would be safe (i.e. when there are no lone surrogates),
47+-- and arrays of UTF-16 code units (integers) otherwise.
43newtype PSString = PSString { toUTF16CodeUnits :: [Word16] }
49newtype PSString = PSString { toUTF16CodeUnits :: [Word16] }
44 deriving (Eq, Ord, Monoid)
50 deriving (Eq, Ord, Monoid)
@@ -116,13 +122,21 @@ instance IsString PSString where
116 encodeUTF16 c = [toWord $ fromEnum c]
122 encodeUTF16 c = [toWord $ fromEnum c]
118instance A.ToJSON PSString where
124instance A.ToJSON PSString where
126+ case decodeString str of
127+ Just t -> A.toJSON t
119− toJSON = A.toJSON . toUTF16CodeUnits
128+ Nothing -> A.toJSON (toUTF16CodeUnits str)
121instance A.FromJSON PSString where
130instance A.FromJSON PSString where
122− parseJSON a = PSString <$> parseArrayOfCodeUnits a
131+ parseJSON a = jsonString <|> arrayOfCodeUnits
133+ jsonString = fromString <$> A.parseJSON a
135+ arrayOfCodeUnits = PSString <$> parseArrayOfCodeUnits a
124 parseArrayOfCodeUnits :: A.Value -> A.Parser [Word16]
137 parseArrayOfCodeUnits :: A.Value -> A.Parser [Word16]
125 parseArrayOfCodeUnits = A.withArray "array of UTF-16 code units" (traverse parseCodeUnit . V.toList)
138 parseArrayOfCodeUnits = A.withArray "array of UTF-16 code units" (traverse parseCodeUnit . V.toList)
126 parseCodeUnit :: A.Value -> A.Parser Word16
140 parseCodeUnit :: A.Value -> A.Parser Word16
127 parseCodeUnit b = A.withScientific "two-byte non-negative integer" (maybe (A.typeMismatch "" b) return . toBoundedInteger) b
141 parseCodeUnit b = A.withScientific "two-byte non-negative integer" (maybe (A.typeMismatch "" b) return . toBoundedInteger) b