forked from purescript/purescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexer.hs
More file actions
600 lines (511 loc) · 15.6 KB
/
Lexer.hs
File metadata and controls
600 lines (511 loc) · 15.6 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
-- |
-- The first step in the parsing process - turns source code into a list of lexemes
--
module Language.PureScript.Parser.Lexer
( PositionedToken(..)
, Token()
, TokenParser()
, lex
, anyToken
, token
, match
, lparen
, rparen
, parens
, lbrace
, rbrace
, braces
, lsquare
, rsquare
, squares
, indent
, indentAt
, larrow
, rarrow
, lfatArrow
, rfatArrow
, colon
, doubleColon
, equals
, pipe
, tick
, dot
, comma
, semi
, at
, underscore
, holeLit
, semiSep
, semiSep1
, commaSep
, commaSep1
, lname
, lname'
, qualifier
, tyname
, kiname
, dconsname
, uname
, uname'
, mname
, reserved
, symbol
, symbol'
, identifier
, charLiteral
, stringLiteral
, number
, natural
, reservedPsNames
, reservedTypeNames
, isSymbolChar
, isUnquotedKey
)
where
import Prelude.Compat hiding (lex)
import Control.Applicative ((<|>))
import Control.Monad (void, guard)
import Control.Monad.Identity (Identity)
import Data.Char (isSpace, isAscii, isSymbol, isAlphaNum)
import Data.Monoid ((<>))
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Text as T
import Language.PureScript.Comments
import Language.PureScript.Parser.State
import Language.PureScript.PSString (PSString)
import qualified Text.Parsec as P
import qualified Text.Parsec.Token as PT
data Token
= LParen
| RParen
| LBrace
| RBrace
| LSquare
| RSquare
| Indent Int
| LArrow
| RArrow
| LFatArrow
| RFatArrow
| Colon
| DoubleColon
| Equals
| Pipe
| Tick
| Dot
| Comma
| Semi
| At
| Underscore
| LName Text
| UName Text
| Qualifier Text
| Symbol Text
| CharLiteral Char
| StringLiteral PSString
| Number (Either Integer Double)
| HoleLit Text
deriving (Show, Eq, Ord)
prettyPrintToken :: Token -> Text
prettyPrintToken LParen = "("
prettyPrintToken RParen = ")"
prettyPrintToken LBrace = "{"
prettyPrintToken RBrace = "}"
prettyPrintToken LSquare = "["
prettyPrintToken RSquare = "]"
prettyPrintToken LArrow = "<-"
prettyPrintToken RArrow = "->"
prettyPrintToken LFatArrow = "<="
prettyPrintToken RFatArrow = "=>"
prettyPrintToken Colon = ":"
prettyPrintToken DoubleColon = "::"
prettyPrintToken Equals = "="
prettyPrintToken Pipe = "|"
prettyPrintToken Tick = "`"
prettyPrintToken Dot = "."
prettyPrintToken Comma = ","
prettyPrintToken Semi = ";"
prettyPrintToken At = "@"
prettyPrintToken Underscore = "_"
prettyPrintToken (Indent n) = "indentation at level " <> T.pack (show n)
prettyPrintToken (LName s) = T.pack (show s)
prettyPrintToken (UName s) = T.pack (show s)
prettyPrintToken (Qualifier _) = "qualifier"
prettyPrintToken (Symbol s) = s
prettyPrintToken (CharLiteral c) = T.pack (show c)
prettyPrintToken (StringLiteral s) = T.pack (show s)
prettyPrintToken (Number n) = T.pack (either show show n)
prettyPrintToken (HoleLit name) = "?" <> name
data PositionedToken = PositionedToken
{ -- | Start position of this token
ptSourcePos :: P.SourcePos
-- | End position of this token (not including whitespace)
, ptEndPos :: P.SourcePos
-- | End position of the previous token
, ptPrevEndPos :: Maybe P.SourcePos
, ptToken :: Token
, ptComments :: [Comment]
} deriving (Eq)
-- Parsec requires this instance for various token-level combinators
instance Show PositionedToken where
show = T.unpack . prettyPrintToken . ptToken
type Lexer u a = P.Parsec Text u a
lex :: FilePath -> Text -> Either P.ParseError [PositionedToken]
lex f s = updatePositions <$> P.parse parseTokens f s
updatePositions :: [PositionedToken] -> [PositionedToken]
updatePositions [] = []
updatePositions (x:xs) = x : zipWith update (x:xs) xs
where
update PositionedToken { ptEndPos = pos } pt = pt { ptPrevEndPos = Just pos }
parseTokens :: Lexer u [PositionedToken]
parseTokens = whitespace *> P.many parsePositionedToken <* P.skipMany parseComment <* P.eof
whitespace :: Lexer u ()
whitespace = P.skipMany (P.satisfy isSpace)
parseComment :: Lexer u Comment
parseComment = (BlockComment <$> blockComment <|> LineComment <$> lineComment) <* whitespace
where
blockComment :: Lexer u Text
blockComment = P.try $ P.string "{-" *> (T.pack <$> P.manyTill P.anyChar (P.try (P.string "-}")))
lineComment :: Lexer u Text
lineComment = P.try $ P.string "--" *> (T.pack <$> P.manyTill P.anyChar (P.try (void (P.char '\n') <|> P.eof)))
parsePositionedToken :: Lexer u PositionedToken
parsePositionedToken = P.try $ do
comments <- P.many parseComment
pos <- P.getPosition
tok <- parseToken
pos' <- P.getPosition
whitespace
return $ PositionedToken pos pos' Nothing tok comments
parseToken :: Lexer u Token
parseToken = P.choice
[ P.try $ P.string "<-" *> P.notFollowedBy symbolChar *> pure LArrow
, P.try $ P.string "←" *> P.notFollowedBy symbolChar *> pure LArrow
, P.try $ P.string "<=" *> P.notFollowedBy symbolChar *> pure LFatArrow
, P.try $ P.string "⇐" *> P.notFollowedBy symbolChar *> pure LFatArrow
, P.try $ P.string "->" *> P.notFollowedBy symbolChar *> pure RArrow
, P.try $ P.string "→" *> P.notFollowedBy symbolChar *> pure RArrow
, P.try $ P.string "=>" *> P.notFollowedBy symbolChar *> pure RFatArrow
, P.try $ P.string "⇒" *> P.notFollowedBy symbolChar *> pure RFatArrow
, P.try $ P.string "::" *> P.notFollowedBy symbolChar *> pure DoubleColon
, P.try $ P.string "∷" *> P.notFollowedBy symbolChar *> pure DoubleColon
, P.try $ P.char '(' *> pure LParen
, P.try $ P.char ')' *> pure RParen
, P.try $ P.char '{' *> pure LBrace
, P.try $ P.char '}' *> pure RBrace
, P.try $ P.char '[' *> pure LSquare
, P.try $ P.char ']' *> pure RSquare
, P.try $ P.char '`' *> pure Tick
, P.try $ P.char ',' *> pure Comma
, P.try $ P.char '=' *> P.notFollowedBy symbolChar *> pure Equals
, P.try $ P.char ':' *> P.notFollowedBy symbolChar *> pure Colon
, P.try $ P.char '|' *> P.notFollowedBy symbolChar *> pure Pipe
, P.try $ P.char '.' *> P.notFollowedBy symbolChar *> pure Dot
, P.try $ P.char ';' *> P.notFollowedBy symbolChar *> pure Semi
, P.try $ P.char '@' *> P.notFollowedBy symbolChar *> pure At
, P.try $ P.char '_' *> P.notFollowedBy identLetter *> pure Underscore
, HoleLit <$> P.try (P.char '?' *> (T.pack <$> P.many1 identLetter))
, LName <$> parseLName
, parseUName >>= \uName ->
guard (validModuleName uName) *> (Qualifier uName <$ P.char '.')
<|> pure (UName uName)
, Symbol <$> parseSymbol
, CharLiteral <$> parseCharLiteral
, StringLiteral <$> parseStringLiteral
, Number <$> parseNumber
]
where
parseLName :: Lexer u Text
parseLName = T.cons <$> identStart <*> (T.pack <$> P.many identLetter)
parseUName :: Lexer u Text
parseUName = T.cons <$> P.upper <*> (T.pack <$> P.many identLetter)
parseSymbol :: Lexer u Text
parseSymbol = T.pack <$> P.many1 symbolChar
identStart :: Lexer u Char
identStart = P.lower <|> P.oneOf "_"
identLetter :: Lexer u Char
identLetter = P.alphaNum <|> P.oneOf "_'"
symbolChar :: Lexer u Char
symbolChar = P.satisfy isSymbolChar
parseCharLiteral :: Lexer u Char
parseCharLiteral = P.try $ do {
c <- PT.charLiteral tokenParser;
if fromEnum c > 0xFFFF
then P.unexpected "astral code point in character literal; characters must be valid UTF-16 code units"
else return c
}
parseStringLiteral :: Lexer u PSString
parseStringLiteral = fromString <$> (blockString <|> PT.stringLiteral tokenParser)
where
delimiter = P.try (P.string "\"\"\"")
blockString = delimiter *> P.manyTill P.anyChar delimiter
parseNumber :: Lexer u (Either Integer Double)
parseNumber = (consumeLeadingZero *> P.parserZero) <|>
(Right <$> P.try (PT.float tokenParser) <|>
Left <$> P.try (PT.natural tokenParser))
P.<?> "number"
where
-- lookAhead doesn't consume any input if its parser succeeds
-- if notFollowedBy fails though, the consumed '0' will break the choice chain
consumeLeadingZero = P.lookAhead (P.char '0' *>
(P.notFollowedBy P.digit P.<?> "no leading zero in number literal"))
-- |
-- We use Text.Parsec.Token to implement the string and number lexemes
--
langDef :: PT.GenLanguageDef Text u Identity
langDef = PT.LanguageDef
{ PT.reservedNames = []
, PT.reservedOpNames = []
, PT.commentStart = ""
, PT.commentEnd = ""
, PT.commentLine = ""
, PT.nestedComments = True
, PT.identStart = P.parserFail "Identifiers not supported"
, PT.identLetter = P.parserFail "Identifiers not supported"
, PT.opStart = P.parserFail "Operators not supported"
, PT.opLetter = P.parserFail "Operators not supported"
, PT.caseSensitive = True
}
-- |
-- A token parser based on the language definition
--
tokenParser :: PT.GenTokenParser Text u Identity
tokenParser = PT.makeTokenParser langDef
type TokenParser a = P.Parsec [PositionedToken] ParseState a
anyToken :: TokenParser PositionedToken
anyToken = P.token (T.unpack . prettyPrintToken . ptToken) ptSourcePos Just
token :: (Token -> Maybe a) -> TokenParser a
token f = P.token (T.unpack . prettyPrintToken . ptToken) ptSourcePos (f . ptToken)
match :: Token -> TokenParser ()
match tok = token (\tok' -> if tok == tok' then Just () else Nothing) P.<?> T.unpack (prettyPrintToken tok)
lparen :: TokenParser ()
lparen = match LParen
rparen :: TokenParser ()
rparen = match RParen
parens :: TokenParser a -> TokenParser a
parens = P.between lparen rparen
lbrace :: TokenParser ()
lbrace = match LBrace
rbrace :: TokenParser ()
rbrace = match RBrace
braces :: TokenParser a -> TokenParser a
braces = P.between lbrace rbrace
lsquare :: TokenParser ()
lsquare = match LSquare
rsquare :: TokenParser ()
rsquare = match RSquare
squares :: TokenParser a -> TokenParser a
squares = P.between lsquare rsquare
indent :: TokenParser Int
indent = token go P.<?> "indentation"
where
go (Indent n) = Just n
go _ = Nothing
indentAt :: P.Column -> TokenParser ()
indentAt n = token go P.<?> "indentation at level " ++ show n
where
go (Indent n') | n == n' = Just ()
go _ = Nothing
larrow :: TokenParser ()
larrow = match LArrow
rarrow :: TokenParser ()
rarrow = match RArrow
lfatArrow :: TokenParser ()
lfatArrow = match LFatArrow
rfatArrow :: TokenParser ()
rfatArrow = match RFatArrow
colon :: TokenParser ()
colon = match Colon
doubleColon :: TokenParser ()
doubleColon = match DoubleColon
equals :: TokenParser ()
equals = match Equals
pipe :: TokenParser ()
pipe = match Pipe
tick :: TokenParser ()
tick = match Tick
dot :: TokenParser ()
dot = match Dot
comma :: TokenParser ()
comma = match Comma
semi :: TokenParser ()
semi = match Semi
at :: TokenParser ()
at = match At
underscore :: TokenParser ()
underscore = match Underscore
holeLit :: TokenParser Text
holeLit = token go P.<?> "hole literal"
where
go (HoleLit n) = Just n
go _ = Nothing
-- |
-- Parse zero or more values separated by semicolons
--
semiSep :: TokenParser a -> TokenParser [a]
semiSep = flip P.sepBy semi
-- |
-- Parse one or more values separated by semicolons
--
semiSep1 :: TokenParser a -> TokenParser [a]
semiSep1 = flip P.sepBy1 semi
-- |
-- Parse zero or more values separated by commas
--
commaSep :: TokenParser a -> TokenParser [a]
commaSep = flip P.sepBy comma
-- |
-- Parse one or more values separated by commas
--
commaSep1 :: TokenParser a -> TokenParser [a]
commaSep1 = flip P.sepBy1 comma
lname :: TokenParser Text
lname = token go P.<?> "identifier"
where
go (LName s) = Just s
go _ = Nothing
lname' :: Text -> TokenParser ()
lname' s = token go P.<?> show s
where
go (LName s') | s == s' = Just ()
go _ = Nothing
qualifier :: TokenParser Text
qualifier = token go P.<?> "qualifier"
where
go (Qualifier s) = Just s
go _ = Nothing
reserved :: Text -> TokenParser ()
reserved s = token go P.<?> show s
where
go (LName s') | s == s' = Just ()
go (Symbol s') | s == s' = Just ()
go _ = Nothing
uname :: TokenParser Text
uname = token go P.<?> "proper name"
where
go (UName s) | validUName s = Just s
go _ = Nothing
uname' :: Text -> TokenParser ()
uname' s = token go P.<?> "proper name"
where
go (UName s') | s == s' = Just ()
go _ = Nothing
tyname :: TokenParser Text
tyname = token go P.<?> "type name"
where
go (UName s) = Just s
go _ = Nothing
kiname :: TokenParser Text
kiname = token go P.<?> "kind name"
where
go (UName s) = Just s
go _ = Nothing
dconsname :: TokenParser Text
dconsname = token go P.<?> "data constructor name"
where
go (UName s) = Just s
go _ = Nothing
mname :: TokenParser Text
mname = token go P.<?> "module name"
where
go (UName s) | validModuleName s = Just s
go _ = Nothing
symbol :: TokenParser Text
symbol = token go P.<?> "symbol"
where
go (Symbol s) = Just s
go Colon = Just ":"
go LFatArrow = Just "<="
go At = Just "@"
go _ = Nothing
symbol' :: Text -> TokenParser ()
symbol' s = token go P.<?> show s
where
go (Symbol s') | s == s' = Just ()
go Colon | s == ":" = Just ()
go LFatArrow | s == "<=" = Just ()
go _ = Nothing
charLiteral :: TokenParser Char
charLiteral = token go P.<?> "char literal"
where
go (CharLiteral c) = Just c
go _ = Nothing
stringLiteral :: TokenParser PSString
stringLiteral = token go P.<?> "string literal"
where
go (StringLiteral s) = Just s
go _ = Nothing
number :: TokenParser (Either Integer Double)
number = token go P.<?> "number"
where
go (Number n) = Just n
go _ = Nothing
natural :: TokenParser Integer
natural = token go P.<?> "natural"
where
go (Number (Left n)) = Just n
go _ = Nothing
identifier :: TokenParser Text
identifier = token go P.<?> "identifier"
where
go (LName s) | s `notElem` reservedPsNames = Just s
go _ = Nothing
validModuleName :: Text -> Bool
validModuleName s = '_' `notElemT` s
validUName :: Text -> Bool
validUName s = '\'' `notElemT` s
notElemT :: Char -> Text -> Bool
notElemT c = not . T.any (== c)
-- |
-- A list of purescript reserved identifiers
--
reservedPsNames :: [Text]
reservedPsNames = [ "data"
, "newtype"
, "type"
, "foreign"
, "import"
, "infixl"
, "infixr"
, "infix"
, "class"
, "instance"
, "derive"
, "module"
, "case"
, "of"
, "if"
, "then"
, "else"
, "do"
, "let"
, "true"
, "false"
, "in"
, "where"
]
reservedTypeNames :: [Text]
reservedTypeNames = [ "forall", "where" ]
-- |
-- The characters allowed for use in operators
--
isSymbolChar :: Char -> Bool
isSymbolChar c = (c `elem` (":!#$%&*+./<=>?@\\^|-~" :: [Char])) || (not (isAscii c) && isSymbol c)
-- |
-- The characters allowed in the head of an unquoted record key
--
isUnquotedKeyHeadChar :: Char -> Bool
isUnquotedKeyHeadChar c = (c == '_') || isAlphaNum c
-- |
-- The characters allowed in the tail of an unquoted record key
--
isUnquotedKeyTailChar :: Char -> Bool
isUnquotedKeyTailChar c = (c `elem` ("_'" :: [Char])) || isAlphaNum c
-- |
-- Strings allowed to be left unquoted in a record key
--
isUnquotedKey :: Text -> Bool
isUnquotedKey t = case T.uncons t of
Nothing -> False
Just (hd, tl) -> isUnquotedKeyHeadChar hd &&
T.all isUnquotedKeyTailChar tl