-
Notifications
You must be signed in to change notification settings - Fork 463
/
ParserCommon.hs
377 lines (320 loc) · 11.9 KB
/
ParserCommon.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
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
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_GHC -Wno-deferred-out-of-scope-variables #-}
-- | Common functions for parsers of UPLC, PLC, and PIR.
module PlutusCore.Parser.ParserCommon where
import Data.Char (isAlphaNum)
import Data.Map qualified as M
import Data.Text qualified as T
import PlutusPrelude
import Text.Megaparsec hiding (ParseError, State, parse, some)
import Text.Megaparsec.Char (char, hexDigitChar, letterChar, space1)
import Text.Megaparsec.Char.Lexer qualified as Lex
import Control.Monad.State (MonadState (get, put), StateT, evalStateT)
import Data.ByteString.Lazy (ByteString)
import Data.ByteString.Lazy.Internal (unpackChars)
import PlutusCore.Core.Type
import PlutusCore.Default
import PlutusCore.Error
import PlutusCore.Name
import PlutusCore.Quote
newtype ParserState = ParserState { identifiers :: M.Map T.Text Unique }
deriving (Show)
type Parser =
ParsecT ParseError T.Text (StateT ParserState Quote)
instance (Stream s, MonadQuote m) => MonadQuote (ParsecT e s m)
initial :: ParserState
initial = ParserState M.empty
-- | Return the unique identifier of a name.
-- If it's not in the current parser state, map the name to a fresh id
-- and add it to the state. Used in the Name parser.
intern :: (MonadState ParserState m, MonadQuote m)
=> T.Text -> m Unique
intern n = do
st <- get
case M.lookup n (identifiers st) of
Just u -> return u
Nothing -> do
fresh <- freshUnique
let identifiers' = M.insert n fresh $ identifiers st
put $ ParserState identifiers'
return fresh
parse :: Parser a -> String -> T.Text -> Either (ParseErrorBundle T.Text ParseError) a
parse p file str = runQuote $ parseQuoted p file str
-- | Generic parser function.
parseGen :: Parser a -> ByteString -> Either (ParseErrorBundle T.Text ParseError) a
parseGen stuff bs = parse stuff "test" $ (T.pack . unpackChars) bs
parseQuoted ::
Parser a -> String -> T.Text ->
Quote (Either (ParseErrorBundle T.Text ParseError) a)
parseQuoted p file str = flip evalStateT initial $ runParserT p file str
-- | Space consumer.
whitespace :: Parser ()
whitespace = Lex.space space1 (Lex.skipLineComment "--") (Lex.skipBlockCommentNested "{-" "-}")
lexeme :: Parser a -> Parser a
lexeme = Lex.lexeme whitespace
symbol :: T.Text -> Parser T.Text
symbol = Lex.symbol whitespace
-- | A PLC @Type@ to be parsed. ATM the parser only works
-- for types in the @DefaultUni@ with @DefaultFun@.
type PType = Type TyName DefaultUni SourcePos
varType :: Parser PType
varType = TyVar <$> getSourcePos <*> tyName
funType :: Parser PType
funType = TyFun <$> wordPos "fun" <*> pType <*> pType
allType :: Parser PType
allType = TyForall <$> wordPos "all" <*> tyName <*> kind <*> pType
lamType :: Parser PType
lamType = TyLam <$> wordPos "lam" <*> tyName <*> kind <*> pType
ifixType :: Parser PType
ifixType = TyIFix <$> wordPos "ifix" <*> pType <*> pType
builtinType :: Parser PType
builtinType = TyBuiltin <$> wordPos "con" <*> defaultUniType
appType :: Parser PType
appType = do
pos <- getSourcePos
fn <- pType
args <- some pType
pure $ tyApps pos fn args
tyApps :: SourcePos -> PType -> [PType] -> PType
tyApps _ _t [] = error "tyApps: A type application without an argument."
tyApps loc ty [ty'] = TyApp loc ty ty'
tyApps loc ty (ty' : tys) = TyApp loc (tyApps loc ty (ty':init tys)) (last tys)
kind :: Parser (Kind SourcePos)
kind = inParens (typeKind <|> funKind)
where
typeKind = Type <$> wordPos "type"
funKind = KindArrow <$> wordPos "fun" <*> kind <*> kind
-- | Parser for @PType@.
pType :: Parser PType
pType = choice
[inParens pType
, funType
, ifixType
, allType
, builtinType
, lamType
, inBrackets appType
, varType
]
defaultUniType :: Parser (SomeTypeIn DefaultUni)
defaultUniType = choice $ map try
[ inParens defaultUniType
, SomeTypeIn DefaultUniInteger <$ symbol "integer"
, SomeTypeIn DefaultUniByteString <$ symbol "bytestring"
, SomeTypeIn DefaultUniString <$ symbol "string"
, SomeTypeIn DefaultUniUnit <$ symbol "unit"
, SomeTypeIn DefaultUniBool <$ symbol "bool"
-- , SomeTypeIn DefaultUniList <$ symbol "list"
-- , SomeTypeIn DefaultUniProtoPair <$ symbol "pair"
]
inParens :: Parser a -> Parser a
inParens = between (symbol "(") (symbol ")")
inBrackets :: Parser a -> Parser a
inBrackets = between (symbol "[") (symbol "]")
inBraces :: Parser a-> Parser a
inBraces = between (symbol "{") (symbol "}")
isIdentifierChar :: Char -> Bool
isIdentifierChar c = isAlphaNum c || c == '_' || c == '\''
-- | Create a parser that matches the input word and returns its source position.
-- This is for attaching source positions to parsed terms/programs.
wordPos ::
-- | The word to match
T.Text -> Parser SourcePos
wordPos w = lexeme $ try $ getSourcePos <* symbol w
-- | The list of parsable default functions and their pretty print correspondence.
builtinFnList :: [(DefaultFun, T.Text)]
builtinFnList =
[ (AddInteger,"addInteger")
, (SubtractInteger,"subtractInteger")
, (MultiplyInteger,"multiplyInteger")
, (DivideInteger,"divideInteger")
, (QuotientInteger,"quotientInteger")
, (RemainderInteger,"remainderInteger")
, (ModInteger,"modInteger")
, (EqualsInteger,"equalsInteger")
, (LessThanInteger,"lessThanInteger")
, (LessThanEqualsInteger,"lessThanEqualsInteger")
, (AppendByteString,"appendByteString")
, (ConsByteString,"consByteString")
, (SliceByteString,"sliceByteString")
, (LengthOfByteString,"lengthOfByteString")
, (IndexByteString,"indexByteString")
, (EqualsByteString,"equalsByteString")
, (LessThanByteString,"lessThanByteString")
, (LessThanEqualsByteString,"lessThanEqualsByteString")
, (Sha2_256,"sha2_256")
, (Sha3_256,"sha3_256")
, (Blake2b_256,"blake2b_256")
, (VerifySignature,"verifySignature")
, (AppendString,"appendString")
, (EqualsString,"equalsString")
, (EncodeUtf8,"encodeUtf8")
, (DecodeUtf8,"decodeUtf8")
, (IfThenElse,"ifThenElse")
, (ChooseUnit,"chooseUnit")
, (Trace,"trace")
, (FstPair,"fstPair")
, (SndPair,"sndPair")
, (ChooseList,"chooseList")
, (MkCons,"mkCons")
, (HeadList,"headList")
, (TailList,"tailList")
, (NullList,"nullList")
, (ChooseData,"chooseData")
, (ConstrData,"constrData")
, (MapData,"mapData")
, (ListData,"listData")
, (IData,"iData")
, (BData,"bData")
, (UnConstrData,"unConstrData")
, (UnMapData,"unMapData")
, (UnListData,"unListData")
, (UnIData,"unIData")
, (UnBData,"unBData")
, (EqualsData,"equalsData")
, (MkPairData,"mkPairData")
, (MkNilData,"mkNilData")
, (MkNilPairData,"mkNilPairData")
]
builtinFunction :: Parser DefaultFun
builtinFunction =
choice $
map
(try . (\(fn, text) -> fn <$ symbol text))
builtinFnList
version :: Parser (Version SourcePos)
version = lexeme $ do
p <- getSourcePos
x <- Lex.decimal
void $ char '.'
y <- Lex.decimal
void $ char '.'
Version p x y <$> Lex.decimal
name :: Parser Name
name = lexeme $ try $ do
void $ lookAhead letterChar
str <- takeWhileP (Just "identifier") isIdentifierChar
Name str <$> intern str
tyName :: Parser TyName
tyName = TyName <$> name
-- | Turn a parser that can succeed without consuming any input into one that fails in this case.
enforce :: Parser a -> Parser a
enforce p = do
(input, x) <- match p
guard . not $ T.null input
pure x
conParser :: SomeTypeIn DefaultUni -> Parser (Some (ValueOf DefaultUni))
conParser (SomeTypeIn DefaultUniInteger) = conInt
conParser (SomeTypeIn DefaultUniByteString) = conChar
conParser (SomeTypeIn DefaultUniString) = conText
conParser (SomeTypeIn DefaultUniUnit) = conUnit
conParser (SomeTypeIn DefaultUniBool) = conBool
conParser (SomeTypeIn (DefaultUniList a)) = conList a
conParser (SomeTypeIn (DefaultUniPair _ _)) = conPair
conParser (SomeTypeIn DefaultUniProtoList ) = conEmpty
conParser (SomeTypeIn DefaultUniProtoPair ) = conEmpty
conParser (SomeTypeIn (DefaultUniApply _ _)) = conEmpty
conParser (SomeTypeIn DefaultUniData) = conEmpty
signedInteger :: ParsecT ParseError T.Text (StateT ParserState Quote) Integer
signedInteger = Lex.signed whitespace (lexeme Lex.decimal)
-- | Parser for integer constants.
conInt :: Parser (Some (ValueOf DefaultUni))
conInt = do
con::Integer <- signedInteger
pure $ someValue con
-- | Parser for bytestring constants. They start with "#".
conChar :: Parser (Some (ValueOf DefaultUni))
conChar = do
con <- char '#' *> Text.Megaparsec.many hexDigitChar
pure $ someValue $ T.pack con
-- | Parser for string constants. They are wrapped in double quotes.
-- Even though @takeWhile@ is more efficient, @manyTill@ is easier to use
-- here and we don't care much about efficiency.
conText :: Parser (Some (ValueOf DefaultUni))
conText = do
con <- char '\"' *> manyTill Lex.charLiteral (char '\"')
pure $ someValue $ T.pack con
-- | Parser for unit.
conUnit :: Parser (Some (ValueOf DefaultUni))
conUnit = someValue () <$ symbol "()"
-- | Parser for bool.
conBool :: Parser (Some (ValueOf DefaultUni))
conBool = choice
[ someValue True <$ symbol "True"
, someValue False <$ symbol "False"
]
constants :: SomeTypeIn DefaultUni -> Parser [Some (ValueOf DefaultUni)]
constants ty = choice
[ try (cons ty)
, do
oneCon <- constant
pure [oneCon]
]
where cons dType = do
con <- conParser dType
_ <- symbol ","
maybeCons <- constants dType
pure $ con : maybeCons
-- mkList :: DefaultUni (Esc a) ->
-- Some (ValueOf (DefaultUni (Esc a)) ->
-- Maybe [Some (ValueOf (DefaultUni (Esc a)))] ->
-- Some (ValueOf (DefaultUni (Esc a)))
mkList (SomeTypeIn ty) hd Nothing =
case hd of
(Some (ValueOf uniA x)) ->
if uniA == ty then
Some $ ValueOf (DefaultUniList ty) [x]
else error $ "mkList: item" <> show x <> "in the list has the wrong type."
mkList (SomeTypeIn ty) hd (Just tail) =
case (hd, tail) of
(Some (ValueOf uniA x), [Some (ValueOf uniB y)]) ->
if uniA == uniB && uniA == ty then
Some $ ValueOf (DefaultUniList ty) [x,y]
else error "type error"
(Some (ValueOf ty x), hd:xs) ->
Some $ ValueOf (DefaultUniList ty) $ x:mkList hd xs
(_, _) -> error "mkList: type error, items in the lists are not of the right types."
conList ty = inBraces $ do
conFirst <- constant
list <- constants (SomeTypeIn ty)
pure $ Some $ ValueOf (DefaultUniList ty) [conFirst]
mkPair :: Some (ValueOf DefaultUni) -> Some (ValueOf DefaultUni) -> Some (ValueOf DefaultUni)
mkPair (Some (ValueOf uniA x)) (Some (ValueOf uniB y)) = Some $ ValueOf (DefaultUniPair uniA uniB) (x, y)
consPair :: Parser [Some (ValueOf DefaultUni)]
consPair = choice
[ try cons
, do
oneCon <- constant
pure [oneCon]
]
where cons = do
con <- constant
_ <- symbol ","
maybeCons <- consPair
pure $ con : maybeCons
conPair :: Parser (Some (ValueOf DefaultUni))
conPair = inBrackets $ do
conFirst <- constant
pairConst conFirst <$> consPair
pairConst :: Some (ValueOf DefaultUni) ->
[Some (ValueOf DefaultUni)] -> Some (ValueOf DefaultUni)
pairConst _t [] = error "pairConst: A pair without second."
pairConst t [t'] = mkPair t t'
pairConst t (t' : ts) = mkPair (pairConst t (t':init ts)) (last ts)
-- | Empty parser to complete case matching of conParser.
conEmpty :: Parser (Some (ValueOf DefaultUni)) --FIXME
conEmpty = pure $ someValue $ T.pack "conEmpty: Not Implemented."
constant :: Parser (Some (ValueOf DefaultUni))
constant = choice $ map try
[ inParens constant
, conInt
, conChar
, conText
, conUnit
, conBool
-- , conPair
-- , conList
-- , conData
]