forked from purescript/purescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.hs
More file actions
360 lines (309 loc) · 13.2 KB
/
Utils.hs
File metadata and controls
360 lines (309 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
module Language.PureScript.CST.Utils where
import Prelude
import Protolude (headDef)
import Control.Monad (unless)
import Data.Coerce (coerce)
import Data.Foldable (for_)
import Data.Functor (($>))
import Data.List.NonEmpty qualified as NE
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as Text
import Language.PureScript.CST.Errors (ParserErrorType(..))
import Language.PureScript.CST.Monad (Parser, addFailure, parseFail, pushBack)
import Language.PureScript.CST.Positions (TokenRange, binderRange, importDeclRange, recordUpdateRange, typeRange)
import Language.PureScript.CST.Traversals.Type (everythingOnTypes)
import Language.PureScript.CST.Types
import Language.PureScript.Names qualified as N
import Language.PureScript.PSString (PSString, mkString)
-- |
-- A newtype for a qualified proper name whose ProperNameType has not yet been determined.
-- This is a workaround for Happy's limited support for polymorphism; it is used
-- inside the parser to allow us to write just one parser for qualified proper names
-- which can be used for all of the different ProperNameTypes
-- (via a call to getQualifiedProperName).
newtype QualifiedProperName =
QualifiedProperName { getQualifiedProperName :: forall a. QualifiedName (N.ProperName a) }
qualifiedProperName :: QualifiedName (N.ProperName a) -> QualifiedProperName
qualifiedProperName n = QualifiedProperName (N.coerceProperName <$> n)
-- |
-- A newtype for a proper name whose ProperNameType has not yet been determined.
-- This is a workaround for Happy's limited support for polymorphism; it is used
-- inside the parser to allow us to write just one parser for proper names
-- which can be used for all of the different ProperNameTypes
-- (via a call to getProperName).
newtype ProperName =
ProperName { _getProperName :: forall a. Name (N.ProperName a) }
properName :: Name (N.ProperName a) -> ProperName
properName n = ProperName (N.coerceProperName <$> n)
getProperName :: forall a. ProperName -> Name (N.ProperName a)
getProperName pn = _getProperName pn -- eta expansion needed here due to simplified subsumption
-- |
-- A newtype for a qualified operator name whose OpNameType has not yet been determined.
-- This is a workaround for Happy's limited support for polymorphism; it is used
-- inside the parser to allow us to write just one parser for qualified operator names
-- which can be used for all of the different OpNameTypes
-- (via a call to getQualifiedOpName).
newtype QualifiedOpName =
QualifiedOpName { getQualifiedOpName :: forall a. QualifiedName (N.OpName a) }
qualifiedOpName :: QualifiedName (N.OpName a) -> QualifiedOpName
qualifiedOpName n = QualifiedOpName (N.coerceOpName <$> n)
-- |
-- A newtype for a operator name whose OpNameType has not yet been determined.
-- This is a workaround for Happy's limited support for polymorphism; it is used
-- inside the parser to allow us to write just one parser for operator names
-- which can be used for all of the different OpNameTypes
-- (via a call to getOpName).
newtype OpName =
OpName { getOpName :: forall a. Name (N.OpName a) }
opName :: Name (N.OpName a) -> OpName
opName n = OpName (N.coerceOpName <$> n)
placeholder :: SourceToken
placeholder = SourceToken
{ tokAnn = TokenAnn (SourceRange (SourcePos 0 0) (SourcePos 0 0)) [] []
, tokValue = TokLowerName [] "<placeholder>"
}
unexpectedName :: SourceToken -> Name Ident
unexpectedName tok = Name tok (Ident "<unexpected>")
unexpectedQual :: SourceToken -> QualifiedName Ident
unexpectedQual tok = QualifiedName tok Nothing (Ident "<unexpected>")
unexpectedLabel :: SourceToken -> Label
unexpectedLabel tok = Label tok "<unexpected>"
unexpectedExpr :: Monoid a => [SourceToken] -> Expr a
unexpectedExpr toks =
ExprIdent mempty (unexpectedQual (headDef placeholder toks))
unexpectedBinder :: Monoid a => [SourceToken] -> Binder a
unexpectedBinder toks =
BinderVar mempty (unexpectedName (headDef placeholder toks))
unexpectedRecordUpdate :: Monoid a => [SourceToken] -> RecordUpdate a
unexpectedRecordUpdate toks =
RecordUpdateLeaf (unexpectedLabel (headDef placeholder toks)) (headDef placeholder toks) (unexpectedExpr toks)
unexpectedRecordLabeled :: [SourceToken] -> RecordLabeled a
unexpectedRecordLabeled toks =
RecordPun (unexpectedName (headDef placeholder toks))
rangeToks :: TokenRange -> [SourceToken]
rangeToks (a, b) = [a, b]
unexpectedToks :: (a -> TokenRange) -> ([SourceToken] -> b) -> ParserErrorType -> (a -> Parser b)
unexpectedToks toRange toCst err old = do
let toks = rangeToks $ toRange old
addFailure toks err
pure $ toCst toks
separated :: [(SourceToken, a)] -> Separated a
separated = go []
where
go accum [(_, a)] = Separated a accum
go accum (x : xs) = go (x : accum) xs
go _ [] = internalError "Separated should not be empty"
internalError :: String -> a
internalError = error . ("Internal parser error: " <>)
toModuleName :: SourceToken -> [Text] -> Parser (Maybe N.ModuleName)
toModuleName _ [] = pure Nothing
toModuleName tok ns = do
unless (all isValidModuleNamespace ns) $ addFailure [tok] ErrModuleName
pure . Just . N.ModuleName $ Text.intercalate "." ns
upperToModuleName :: SourceToken -> Parser (Name N.ModuleName)
upperToModuleName tok = case tokValue tok of
TokUpperName q a -> do
let ns = q <> [a]
unless (all isValidModuleNamespace ns) $ addFailure [tok] ErrModuleName
pure . Name tok . N.ModuleName $ Text.intercalate "." ns
_ -> internalError $ "Invalid upper name: " <> show tok
toQualifiedName :: (Text -> a) -> SourceToken -> Parser (QualifiedName a)
toQualifiedName k tok = case tokValue tok of
TokLowerName q a
| not (Set.member a reservedNames) -> flip (QualifiedName tok) (k a) <$> toModuleName tok q
| otherwise -> addFailure [tok] ErrKeywordVar $> QualifiedName tok Nothing (k "<unexpected>")
TokUpperName q a -> flip (QualifiedName tok) (k a) <$> toModuleName tok q
TokSymbolName q a -> flip (QualifiedName tok) (k a) <$> toModuleName tok q
TokOperator q a -> flip (QualifiedName tok) (k a) <$> toModuleName tok q
_ -> internalError $ "Invalid qualified name: " <> show tok
toName :: (Text -> a) -> SourceToken -> Parser (Name a)
toName k tok = case tokValue tok of
TokLowerName [] a
| not (Set.member a reservedNames) -> pure $ Name tok (k a)
| otherwise -> addFailure [tok] ErrKeywordVar $> Name tok (k "<unexpected>")
TokString _ _ -> parseFail tok ErrQuotedPun
TokRawString _ -> parseFail tok ErrQuotedPun
TokUpperName [] a -> pure $ Name tok (k a)
TokSymbolName [] a -> pure $ Name tok (k a)
TokOperator [] a -> pure $ Name tok (k a)
TokHole a -> pure $ Name tok (k a)
_ -> internalError $ "Invalid name: " <> show tok
toLabel :: SourceToken -> Label
toLabel tok = case tokValue tok of
TokLowerName [] a -> Label tok $ mkString a
TokString _ a -> Label tok a
TokRawString a -> Label tok $ mkString a
TokForall ASCII -> Label tok $ mkString "forall"
_ -> internalError $ "Invalid label: " <> show tok
toString :: SourceToken -> (SourceToken, PSString)
toString tok = case tokValue tok of
TokString _ a -> (tok, a)
TokRawString a -> (tok, mkString a)
_ -> internalError $ "Invalid string literal: " <> show tok
toChar :: SourceToken -> (SourceToken, Char)
toChar tok = case tokValue tok of
TokChar _ a -> (tok, a)
_ -> internalError $ "Invalid char literal: " <> show tok
toNumber :: SourceToken -> (SourceToken, Either Integer Double)
toNumber tok = case tokValue tok of
TokInt _ a -> (tok, Left a)
TokNumber _ a -> (tok, Right a)
_ -> internalError $ "Invalid number literal: " <> show tok
toInt :: SourceToken -> (SourceToken, Integer)
toInt tok = case tokValue tok of
TokInt _ a -> (tok, a)
_ -> internalError $ "Invalid integer literal: " <> show tok
toBoolean :: SourceToken -> (SourceToken, Bool)
toBoolean tok = case tokValue tok of
TokLowerName [] "true" -> (tok, True)
TokLowerName [] "false" -> (tok, False)
_ -> internalError $ "Invalid boolean literal: " <> show tok
toConstraint :: forall a. Monoid a => Type a -> Parser (Constraint a)
toConstraint = convertParens
where
convertParens :: Type a -> Parser (Constraint a)
convertParens = \case
TypeParens a (Wrapped b c d) -> do
c' <- convertParens c
pure $ ConstraintParens a (Wrapped b c' d)
ty -> convert mempty [] ty
convert :: a -> [Type a] -> Type a -> Parser (Constraint a)
convert ann acc = \case
TypeApp a lhs rhs -> convert (a <> ann) (rhs : acc) lhs
TypeConstructor a name -> do
for_ acc checkNoForalls
pure $ Constraint (a <> ann) (coerce name) acc
ty -> do
let (tok1, tok2) = typeRange ty
addFailure [tok1, tok2] ErrTypeInConstraint
pure $ Constraint mempty (QualifiedName tok1 Nothing (N.ProperName "<unexpected")) []
isConstrained :: Type a -> Bool
isConstrained = everythingOnTypes (||) $ \case
TypeConstrained{} -> True
_ -> False
toBinderConstructor :: Monoid a => NE.NonEmpty (Binder a) -> Parser (Binder a)
toBinderConstructor = \case
BinderConstructor a name [] NE.:| bs ->
pure $ BinderConstructor a name bs
a NE.:| [] -> pure a
a NE.:| _ -> unexpectedToks binderRange unexpectedBinder ErrExprInBinder a
toRecordFields
:: Monoid a
=> Separated (Either (RecordLabeled (Expr a)) (RecordUpdate a))
-> Parser (Either (Separated (RecordLabeled (Expr a))) (Separated (RecordUpdate a)))
toRecordFields = \case
Separated (Left a) as ->
Left . Separated a <$> traverse (traverse unLeft) as
Separated (Right a) as ->
Right . Separated a <$> traverse (traverse unRight) as
where
unLeft (Left tok) = pure tok
unLeft (Right tok) =
unexpectedToks recordUpdateRange unexpectedRecordLabeled ErrRecordUpdateInCtr tok
unRight (Right tok) = pure tok
unRight (Left (RecordPun (Name tok _))) = do
addFailure [tok] ErrRecordPunInUpdate
pure $ unexpectedRecordUpdate [tok]
unRight (Left (RecordField _ tok _)) = do
addFailure [tok] ErrRecordCtrInUpdate
pure $ unexpectedRecordUpdate [tok]
checkFundeps :: ClassHead a -> Parser ()
checkFundeps (ClassHead _ _ _ _ Nothing) = pure ()
checkFundeps (ClassHead _ _ _ vars (Just (_, fundeps))) = do
let
k (TypeVarKinded (Wrapped _ (Labeled (_, a) _ _) _)) = getIdent $ nameValue a
k (TypeVarName (_, a)) = getIdent $ nameValue a
names = k <$> vars
check a
| getIdent (nameValue a) `elem` names = pure ()
| otherwise = addFailure [nameTok a] ErrUnknownFundep
for_ fundeps $ \case
FundepDetermined _ bs -> for_ bs check
FundepDetermines as _ bs -> do
for_ as check
for_ bs check
data TmpModuleDecl a
= TmpImport (ImportDecl a)
| TmpChain (Separated (Declaration a))
deriving (Show)
toModuleDecls :: Monoid a => [TmpModuleDecl a] -> Parser ([ImportDecl a], [Declaration a])
toModuleDecls = goImport []
where
goImport acc (TmpImport x : xs) = goImport (x : acc) xs
goImport acc xs = (reverse acc,) <$> goDecl [] xs
goDecl acc [] = pure $ reverse acc
goDecl acc (TmpChain (Separated x []) : xs) = goDecl (x : acc) xs
goDecl acc (TmpChain (Separated (DeclInstanceChain a (Separated h t)) t') : xs) = do
(a', instances) <- goChain (getName h) a [] t'
goDecl (DeclInstanceChain a' (Separated h (t <> instances)) : acc) xs
goDecl acc (TmpChain (Separated _ t) : xs) = do
for_ t $ \(tok, _) -> addFailure [tok] ErrElseInDecl
goDecl acc xs
goDecl acc (TmpImport imp : xs) = do
unexpectedToks importDeclRange (const ()) ErrImportInDecl imp
goDecl acc xs
goChain _ ann acc [] = pure (ann, reverse acc)
goChain name ann acc ((tok, DeclInstanceChain a (Separated h t)) : xs)
| eqName (getName h) name = goChain name (ann <> a) (reverse ((tok, h) : t) <> acc) xs
| otherwise = do
addFailure [qualTok $ getName h] ErrInstanceNameMismatch
goChain name ann acc xs
goChain name ann acc ((tok, _) : xs) = do
addFailure [tok] ErrElseInDecl
goChain name ann acc xs
getName = instClass . instHead
eqName (QualifiedName _ a b) (QualifiedName _ c d) = a == c && b == d
checkNoWildcards :: Type a -> Parser ()
checkNoWildcards ty = do
let
k = \case
TypeWildcard _ a -> [addFailure [a] ErrWildcardInType]
TypeHole _ a -> [addFailure [nameTok a] ErrHoleInType]
_ -> []
sequence_ $ everythingOnTypes (<>) k ty
checkNoForalls :: Type a -> Parser ()
checkNoForalls ty = do
let
k = \case
TypeForall _ a _ _ _ -> [addFailure [a] ErrToken]
_ -> []
sequence_ $ everythingOnTypes (<>) k ty
revert :: Parser a -> SourceToken -> Parser a
revert p lk = pushBack lk *> p
reservedNames :: Set Text
reservedNames = Set.fromList
[ "ado"
, "case"
, "class"
, "data"
, "derive"
, "do"
, "else"
, "false"
, "forall"
, "foreign"
, "import"
, "if"
, "in"
, "infix"
, "infixl"
, "infixr"
, "instance"
, "let"
, "module"
, "newtype"
, "of"
, "true"
, "type"
, "where"
]
isValidModuleNamespace :: Text -> Bool
isValidModuleNamespace = Text.null . snd . Text.span (\c -> c /= '_' && c /= '\'')
-- | This is to keep the @Parser.y@ file ASCII, otherwise @happy@ will break
-- in non-unicode locales.
--
-- Related GHC issue: https://gitlab.haskell.org/ghc/ghc/issues/8167
isLeftFatArrow :: Text -> Bool
isLeftFatArrow str = str == "<=" || str == "⇐"