-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathLex.hs
285 lines (243 loc) · 8.8 KB
/
Lex.hs
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
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- SPDX-License-Identifier: BSD-3-Clause
--
-- Token lexing and comment preservation for the Swarm language.
module Swarm.Language.Parser.Lex (
-- * Parsing with source locations
parseLoc,
parseLocG,
-- * Whitespace + comments
getCommentSituation,
lineComment,
blockComment,
sc,
-- * Tokens
-- ** Lexemes
lexeme,
-- ** Specific token types
symbol,
operator,
reservedWords,
reservedCS,
reserved,
IdentifierType (..),
locIdentifier,
locTmVar,
locTyName,
identifier,
tyVar,
tyName,
tmVar,
textLiteral,
integer,
-- ** Combinators
braces,
parens,
brackets,
) where
import Control.Lens (use, (%=), (.=))
import Control.Monad (void)
import Data.Char (isLower, isUpper)
import Data.Containers.ListUtils (nubOrd)
import Data.List.Extra (enumerate)
import Data.Sequence qualified as Seq
import Data.Set (Set)
import Data.Set qualified as S
import Data.Text (Text)
import Data.Text qualified as T
import Swarm.Language.Parser.Core
import Swarm.Language.Syntax
import Swarm.Language.Syntax.Direction
import Swarm.Language.Types (baseTyName)
import Swarm.Util (failT, squote)
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Megaparsec.Char.Lexer qualified as L
import Witch (from, into)
------------------------------------------------------------
-- Parsing with source locations
-- | Add 'SrcLoc' to a parser
parseLocG :: Parser a -> Parser (SrcLoc, a)
parseLocG pa = do
start <- getOffset
a <- pa
end <- getOffset
pure (SrcLoc start end, a)
-- | Add 'SrcLoc' to a 'Term' parser
parseLoc :: Parser Term -> Parser Syntax
parseLoc pterm = uncurry Syntax <$> parseLocG pterm
------------------------------------------------------------
-- Whitespace
-- Approach for preserving comments taken from https://www.reddit.com/r/haskell/comments/ni4gpm/comment/gz0ipmp/
-- | If we see a comment starting now, is it the first non-whitespace
-- thing on the current line so far, or were there other
-- non-whitespace tokens previously?
getCommentSituation :: Parser CommentSituation
getCommentSituation = do
fl <- use freshLine
return $ if fl then StandaloneComment else SuffixComment
-- | Parse a line comment, while appending it out-of-band to the list of
-- comments saved in the custom state.
lineComment :: Text -> Parser ()
lineComment start = do
cs <- getCommentSituation
(loc, t) <- parseLocG $ do
string start *> takeWhileP (Just "character") (/= '\n')
comments %= (Seq.|> Comment loc LineComment cs t)
-- | Parse a block comment, while appending it out-of-band to the list of
-- comments saved in the custom state.
blockComment :: Text -> Text -> Parser ()
blockComment start end = do
cs <- getCommentSituation
(loc, t) <- parseLocG $ do
void $ string start
manyTill anySingle (string end)
comments %= (Seq.|> Comment loc BlockComment cs (into @Text t))
-- | Skip spaces and comments.
sc :: Parser ()
sc =
-- Typically we would use L.space here, but we have to inline its
-- definition and use our own slight variant, since we need to treat
-- end-of-line specially.
skipMany . choice . map hidden $
[ hspace1
, eol *> (freshLine .= True) -- If we see a newline, reset freshLine to True.
, lineComment "//"
, blockComment "/*" "*/"
]
------------------------------------------------------------
-- Tokens
-- | In general, we follow the convention that every token parser
-- assumes no leading whitespace and consumes all trailing
-- whitespace. Concretely, we achieve this by wrapping every token
-- parser using 'lexeme'.
--
-- Also sets freshLine to False every time we see a non-whitespace
-- token.
lexeme :: Parser a -> Parser a
lexeme p = (freshLine .= False) *> L.lexeme sc p
-- | A lexeme consisting of a literal string.
symbol :: Text -> Parser Text
symbol s = (freshLine .= False) *> L.symbol sc s
-- | A lexeme consisting of a specific string, not followed by any other
-- operator character.
operator :: Text -> Parser Text
operator n = (lexeme . try) (string n <* notFollowedBy operatorChar)
-- | Recognize a single character which is one of the characters used
-- by a built-in operator.
operatorChar :: Parser Text
operatorChar = T.singleton <$> oneOf opChars
where
isOp = \case { ConstMFunc {} -> False; _ -> True } . constMeta
opChars = nubOrd . concatMap (from . syntax) . filter isOp $ map constInfo allConst
-- | Names of base types built into the language.
baseTypeNames :: [Text]
baseTypeNames = map baseTyName enumerate
-- | Names of types built into the language.
primitiveTypeNames :: [Text]
primitiveTypeNames = "Cmd" : baseTypeNames
-- | List of keywords built into the language.
keywords :: [Text]
keywords = T.words "let in def tydef end true false forall require requirements rec"
-- | List of reserved words that cannot be used as variable names.
reservedWords :: Set Text
reservedWords =
S.fromList $
map (syntax . constInfo) (filter isUserFunc allConst)
++ map directionSyntax allDirs
++ primitiveTypeNames
++ keywords
-- | Parse a reserved word, given a string recognizer (which can
-- /e.g./ be case sensitive or not), making sure it is not a prefix
-- of a longer variable name, and allowing the parser to backtrack
-- if it fails.
reservedGen :: (Text -> Parser a) -> Text -> Parser ()
reservedGen str w = (lexeme . try) $ str w *> notFollowedBy (alphaNumChar <|> char '_')
-- | Parse a case-sensitive reserved word.
reservedCS :: Text -> Parser ()
reservedCS = reservedGen string
-- | Parse a case-insensitive reserved word.
reserved :: Text -> Parser ()
reserved = reservedGen string'
-- | What kind of identifier are we parsing?
data IdentifierType = IDTyVar | IDTyName | IDTmVar
deriving (Eq, Ord, Show)
-- | Parse an identifier together with its source location info.
locIdentifier :: IdentifierType -> Parser LocVar
locIdentifier idTy =
uncurry LV <$> parseLocG ((lexeme . try) (p >>= check) <?> "variable name")
where
p = (:) <$> (letterChar <|> char '_') <*> many (alphaNumChar <|> char '_' <|> char '\'')
check (into @Text -> t)
| IDTyVar <- idTy
, T.toTitle t `S.member` reservedWords =
failT ["Reserved type name", squote t, "cannot be used as a type variable name; perhaps you meant", squote (T.toTitle t) <> "?"]
| IDTyName <- idTy
, t `S.member` reservedWords =
failT ["Reserved type name", squote t, "cannot be redefined."]
| t `S.member` reservedWords || T.toLower t `S.member` reservedWords =
failT ["Reserved word", squote t, "cannot be used as a variable name"]
| IDTyName <- idTy
, isLower (T.head t) =
failT ["Type synonym names must start with an uppercase letter"]
| IDTyVar <- idTy
, isUpper (T.head t) =
failT ["Type variable names must start with a lowercase letter"]
| otherwise = return t
-- | Parse a term variable together with its source location info.
locTmVar :: Parser LocVar
locTmVar = locIdentifier IDTmVar
-- | Parse a user-defined type name together with its source location
-- info.
locTyName :: Parser LocVar
locTyName = locIdentifier IDTyName
-- | Parse an identifier, i.e. any non-reserved string containing
-- alphanumeric characters and underscores, not starting with a
-- digit. The Bool indicates whether we are parsing a type variable.
identifier :: IdentifierType -> Parser Var
identifier = fmap lvVar . locIdentifier
-- | Parse a type variable, which must start with an underscore or
-- lowercase letter and cannot be the lowercase version of a type
-- name.
tyVar :: Parser Var
tyVar = identifier IDTyVar
-- | Parse a (user-defined) type constructor name, which must start
-- with an uppercase letter.
tyName :: Parser Var
tyName = identifier IDTyName
-- | Parse a term variable, which can start in any case and just
-- cannot be the same (case-insensitively) as a lowercase reserved
-- word.
tmVar :: Parser Var
tmVar = identifier IDTmVar
-- | Parse a text literal (including escape sequences) in double quotes.
textLiteral :: Parser Text
textLiteral = into <$> lexeme (char '"' >> manyTill L.charLiteral (char '"'))
-- | Parse a positive integer literal token, in decimal, binary,
-- octal, or hexadecimal notation. Note that negation is handled as
-- a separate operator.
integer :: Parser Integer
integer =
label "integer literal" $
lexeme $ do
n <-
string "0b"
*> L.binary
<|> string "0o"
*> L.octal
<|> string "0x"
*> L.hexadecimal
<|> L.decimal
notFollowedBy alphaNumChar
return n
------------------------------------------------------------
-- Combinators
braces :: Parser a -> Parser a
braces = between (symbol "{") (symbol "}")
parens :: Parser a -> Parser a
parens = between (symbol "(") (symbol ")")
brackets :: Parser a -> Parser a
brackets = between (symbol "[") (symbol "]")