-
-
Notifications
You must be signed in to change notification settings - Fork 125
/
Parser.purs
497 lines (430 loc) · 16 KB
/
Parser.purs
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
-- | This module defines the parser for the Insect language.
module Insect.Parser
( DictEntry(..)
, (==>)
, Dictionary(..)
, commands
, prefixDict
, normalUnitDict
, imperialUnitDict
, parseInsect
) where
import Prelude hiding (degree)
import Control.Alt ((<|>))
import Control.Lazy (fix)
import Quantities (DerivedUnit, (./))
import Quantities as Q
import Data.Array (some, fromFoldable)
import Data.Decimal (Decimal, fromString, fromNumber, isFinite)
import Data.Either (Either, isRight)
import Data.Foldable (foldr, traverse_)
import Data.Foldable as F
import Data.List (List, many, init, last)
import Data.Maybe (Maybe(..), fromMaybe)
import Data.NonEmpty (NonEmpty, (:|), foldl1)
import Data.StrMap (lookup)
import Data.String (fromCharArray, singleton)
import Text.Parsing.Parser (ParserT, Parser, ParseError, runParser, fail)
import Text.Parsing.Parser.Combinators (option, optionMaybe, try, (<?>),
notFollowedBy)
import Text.Parsing.Parser.String (string, char, eof, oneOf)
import Text.Parsing.Parser.Token (GenLanguageDef(..), LanguageDef, TokenParser,
digit, letter, makeTokenParser)
import Insect.Language (BinOp(..), Expression(..), Command(..), Statement(..),
Identifier)
import Insect.Environment (Environment, StoredFunction(..))
-- | A type synonym for the main Parser type with `String` as input.
type P a = Parser String a
-- | Possible characters for the first character of an identifier.
identStart ∷ P Char
identStart = letter <|> char '_'
-- | Possible characters for identifiers (not for the first character).
identLetter ∷ P Char
identLetter = letter <|> digit <|> char '_' <|> char '\''
-- | A list of allowed commands
commands ∷ Array String
commands = ["help", "?", "list", "ls", "ll", "reset", "clear", "cls", "quit", "exit"]
-- | The language definition.
insectLanguage ∷ LanguageDef
insectLanguage = LanguageDef
{ commentStart: ""
, commentEnd: ""
, commentLine: "#"
, nestedComments: false
, identStart: identStart
, identLetter: identLetter
, opStart: oneOf ['+', '-', '*', '·', '⋅', '×', '/', '÷', '%', '^', '!', '→', '➞', '=']
, opLetter: oneOf []
, reservedNames: commands <> ["¹", "²", "³", "⁴", "⁵", "⁻¹", "⁻²", "⁻³", "⁻⁴", "⁻⁵", "to", "per"]
, reservedOpNames: ["->", "+", "-", "*", "·", "⋅", "×", "/", "÷", "%", "^", "!",
"**", "=", ","]
, caseSensitive: true
}
-- | The actual token parser.
token ∷ TokenParser
token = makeTokenParser insectLanguage
-- | Parse something, inside of parens.
parens ∷ ∀ a. P a → P a
parens = token.parens
-- | Parse one of the reserved operators.
reservedOp ∷ String → P Unit
reservedOp = token.reservedOp
-- | Parse a reserverd keyword.
reserved ∷ String → P Unit
reserved = token.reserved
-- | Parse zero or more whitespace characters.
whiteSpace ∷ P Unit
whiteSpace = token.whiteSpace
-- | Parse a number.
number ∷ P Decimal
number = do
intPart ← digits
mFracPart ← optionMaybe (append <$> string "." <*> digits)
let fracPart = fromMaybe "" mFracPart
mExpPart ← optionMaybe $ try do
_ ← string "e"
notFollowedBy identStart
sad ← signAndDigits
pure ("e" <> sad)
let expPart = fromMaybe "" mExpPart
whiteSpace
let floatStr = intPart <> fracPart <> expPart
case fromString floatStr of
Just num →
if isFinite num
then pure num
else fail "This number is too large"
Nothing → fail $ "Parsing of number failed for input '" <> floatStr <> "'"
where
digits ∷ P String
digits = do
ds ← some $ oneOf ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] <?> "a digit"
pure $ fromCharArray (fromFoldable ds)
signAndDigits ∷ P String
signAndDigits = do
sign ← option '+' (oneOf ['+', '-'])
intPart ← digits
pure $ singleton sign <> intPart
-- | A helper type for entries in the dictionary.
data DictEntry a = DictEntry a (Array String)
infix 4 DictEntry as ==>
-- | A dictionary of units and their abbreviations.
data Dictionary a = Dictionary (Array (DictEntry a))
-- | Build a parser from a Dictionary
buildDictParser ∷ ∀ a. Dictionary a → P a
buildDictParser (Dictionary dict) = F.oneOf $ entryParser <$> dict
where
entryParser (x ==> abbrevs) = F.oneOf $ abbrevParser x <$> abbrevs
abbrevParser x abbrev = string abbrev *> pure x
prefixDict ∷ Dictionary (DerivedUnit → DerivedUnit)
prefixDict = Dictionary
[ Q.kibi ==> ["kibi", "Ki"]
, Q.mebi ==> ["mebi", "Mi"]
, Q.gibi ==> ["gibi", "Gi"]
, Q.tebi ==> ["tebi", "Ti"]
, Q.pebi ==> ["pebi", "Pi"]
, Q.exbi ==> ["exbi", "Ei"]
, Q.zebi ==> ["zebi", "Zi"]
, Q.yobi ==> ["yobi", "Yi"]
, Q.atto ==> ["atto", "a"]
, Q.femto ==> ["femto", "f"]
-- peta and mega have to be up here (before pico and milli) in order for the
-- prefixes ('p' and 'm') not to be parsed as 'pico' or 'milli'.
, Q.peta ==> ["peta"]
, Q.mega ==> ["mega"]
, Q.pico ==> ["pico", "p"]
, Q.nano ==> ["nano", "n"]
, Q.micro ==> [ "micro"
, "u" -- u for micro
, "µ" -- Micro sign U+00B5
, "μ" -- Greek small letter mu U+039C
]
, Q.milli ==> ["milli", "m"]
, Q.centi ==> ["centi", "c"]
, Q.deci ==> ["deci", "d"]
, Q.hecto ==> ["hecto", "h"]
, Q.kilo ==> ["kilo", "k"]
, Q.mega ==> ["M"]
, Q.giga ==> ["giga", "G"]
, Q.tera ==> ["tera", "T"]
, Q.peta ==> ["P"]
, Q.exa ==> ["exa", "E"]
]
-- | Parse a SI or IEC prefix like `µ`, `G`, `pico` or `Ki`.
prefix ∷ P (DerivedUnit → DerivedUnit)
prefix = buildDictParser prefixDict <|> pure id
-- | Normal (SI-conform, non-imperial) units
normalUnitDict ∷ Dictionary DerivedUnit
normalUnitDict = Dictionary
[ Q.radian ==> ["radians", "radian", "rad"]
, Q.degree ==> ["degrees", "degree", "deg", "°"]
, Q.hertz ==> ["hertz", "Hz"]
, Q.rpm ==> ["RPM", "rpm"]
, Q.newton ==> ["newton", "N"]
, Q.joule ==> ["joules", "joule", "J"]
, Q.pascal ==> ["pascal", "Pa"]
, Q.volt ==> ["volts", "volt", "V"]
, Q.farad ==> ["farad", "F"]
, Q.ohm ==> ["ohms", "ohm", "Ω"]
, Q.sievert ==> ["sievert", "Sv"]
, Q.weber ==> ["weber", "Wb"]
, Q.tesla ==> ["tesla", "T"]
, Q.henry ==> ["henry", "H"]
, Q.coulomb ==> ["coulomb", "C"]
, Q.siemens ==> ["siemens", "S"]
, Q.lumen ==> ["lumen", "lm"]
, Q.lux ==> ["lux", "lx"]
, Q.becquerel ==> ["becquerel", "Bq"]
, Q.gray ==> ["gray", "Gy"]
, Q.katal ==> ["katal", "kat"]
, Q.hectare ==> ["hectare", "ha"]
, Q.tonne ==> ["tonnes", "tonne", "tons", "ton"]
, Q.electronvolt ==> ["electronvolt", "eV"]
, Q.calorie ==> ["calories", "calorie", "cal"]
, Q.bel ==> ["bel"]
, Q.astronomicalUnit ==> ["AU"]
, Q.parsec ==> ["parsecs", "parsec", "pc"]
, Q.lightyear ==> ["lightyears", "lightyear", "ly"]
, Q.barn ==> ["barn"]
, Q.bar ==> ["bar"]
, Q.angstrom ==> ["angstrom", "Å"]
, Q.gauss ==> ["gauss"]
, Q.ampere ==> ["amperes", "ampere", "A"]
, Q.mole ==> ["mole", "mol"]
, Q.kelvin ==> ["kelvin", "K"]
, Q.candela ==> ["candela", "cd"]
, Q.watt <> Q.hour ==> ["Wh"]
, Q.watt ==> ["watts", "watt", "W"]
, Q.byte ==> ["Bytes", "bytes", "Byte", "byte", "B", "Octets", "octets", "Octet", "octet"]
, Q.bit ==> ["bits", "bit"]
, Q.bit ./ Q.second ==> ["bps"]
, Q.second ==> ["seconds", "second", "sec", "s"]
, Q.minute ==> ["minutes", "minute", "min"]
, Q.hour ==> ["hours", "hour", "h"]
, Q.day ==> ["days", "day"]
, Q.week ==> ["weeks", "week"]
, Q.fortnight ==> ["fortnights", "fortnight"]
, Q.month ==> ["months", "month"]
, Q.year ==> ["years", "year"]
, Q.gram ==> ["grammes", "gramme", "grams", "gram", "g"]
, Q.meter ==> ["metres", "metre", "meters", "meter", "m"]
, Q.liter ==> ["liters", "liter", "litres", "litre", "L", "l"]
, Q.atm ==> ["atm"]
]
-- | Parse a normal (SI-conform, non-imperical) unit, like `N` or `watt`.
normalUnit ∷ P DerivedUnit
normalUnit = buildDictParser normalUnitDict <?> "normal unit"
-- | Imperial units
imperialUnitDict ∷ Dictionary DerivedUnit
imperialUnitDict = Dictionary
[ Q.mile ==> ["miles", "mile"]
, Q.mile ./ Q.hour ==> ["mph"]
, Q.inch ==> ["inches", "inch", "in"]
, Q.yard ==> ["yards", "yard", "yd"]
, Q.foot ==> ["feet", "foot", "ft"]
, Q.ounce ==> ["ounces", "ounce", "oz"]
, Q.lbf ==> ["pound_force", "lbf"]
, Q.pound ==> ["pounds", "pound", "lb"]
, Q.gallon ==> ["gallons", "gallon", "gal"]
, Q.pint ==> ["pints", "pint"]
, Q.cup ==> ["cups", "cup"]
, Q.tablespoon ==> ["tablespoons", "tablespoon", "tbsp"]
, Q.teaspoon ==> ["teaspoons", "teaspoon", "tsp"]
, Q.fluidounce ==> ["fluidounces", "fluidounce", "floz"]
, Q.furlong ==> ["furlong"]
, Q.btu ==> ["BTU"]
, Q.psi ==> ["psi"]
, Q.mmHg ==> ["mmHg"]
, Q.hogshead ==> ["hogsheads", "hogshead"]
, Q.rod ==> ["rods", "rod"]
]
-- | Parse an imperial unit like `ft` of `mile`.
imperialUnit ∷ P DerivedUnit
imperialUnit = buildDictParser imperialUnitDict <?> "imperial unit"
-- | Parse a 'normal' unit with SI prefix, like `km` or `Gb`.
unitWithSIPrefix ∷ P DerivedUnit
unitWithSIPrefix = do
p ← prefix
u ← normalUnit
pure $ p u
specialCases ∷ P DerivedUnit
specialCases =
-- The abbreviation 'd' for 'day' needs to be treated separately. Otherwise,
-- 'cd' will be parsed as 'centi day' instead of 'candela'.
string "d" *> pure Q.day
-- Similarly, the abbreviation 't' for 'tonne' needs special treatment.
-- Otherwise, 'ft' will be parsed as 'femto tonne' instead of 'feet'.
<|> string "t" *> pure Q.tonne
-- | Parse a derived unit, like `km`, `ft`, or `s`.
derivedUnit ∷ P DerivedUnit
derivedUnit =
(
try (augment unitWithSIPrefix)
<|> augment imperialUnit
<|> augment normalUnit
<|> augment specialCases
) <* whiteSpace
where
augment p = p <* notFollowedBy identLetter
-- | Parse the name of a variable, like `my_variable'`.
variable ∷ P Expression
variable = Variable <$> token.identifier
-- | A version of `sepBy1` that returns a `NonEmpty List`.
sepBy1 ∷ ∀ m s a sep. Monad m ⇒ ParserT s m a → ParserT s m sep → ParserT s m (NonEmpty List a)
sepBy1 p sep = do
a ← p
as ← many $ sep *> p
pure (a :| as)
-- | Fold a non-empty structure, collecting results using a binary operation.
foldr1 ∷ ∀ a. (a → a → a) → NonEmpty List a → a
foldr1 f (a :| xs) =
case init xs, last xs of
Just bs, Just b → f a (foldr f b bs)
_, _ → a
-- | Parse a function name and fail if it's not in the environment
function ∷ Environment → P Identifier
function env = do
name ← token.identifier
if name == "sum" || name == "product"
then
pure name
else
case lookup name env.functions of
Just (StoredFunction _ fn) → pure name
Nothing → fail ("Unknown function '" <> name <> "'")
-- | Parse a full mathematical expression.
expression ∷ Environment → P Expression
expression env =
fix \p →
let
atomic ∷ P Expression
atomic = whiteSpace *> (
parens p
<|> (Scalar <$> number)
<|> try (Unit <$> derivedUnit)
<|> try (Apply <$> function env <*> parens (sepBy1 p commaOp))
<|> variable
)
suffixFac ∷ P Expression
suffixFac = do
a ← atomic
mf ← optionMaybe (facOp *> pure Factorial)
case mf of
Just f → pure $ f a
Nothing → pure a
suffixPow ∷ P Expression
suffixPow = do
x ← suffixFac
mFn ← optionMaybe ( reservedOp "¹" *> pure (powPos 1.0)
<|> reservedOp "²" *> pure (powPos 2.0)
<|> reservedOp "³" *> pure (powPos 3.0)
<|> reservedOp "⁴" *> pure (powPos 4.0)
<|> reservedOp "⁵" *> pure (powPos 5.0)
<|> reservedOp "⁻¹" *> pure (powNeg 1.0)
<|> reservedOp "⁻²" *> pure (powNeg 2.0)
<|> reservedOp "⁻³" *> pure (powNeg 3.0)
<|> reservedOp "⁻⁴" *> pure (powNeg 4.0)
<|> reservedOp "⁻⁵" *> pure (powNeg 5.0)
)
case mFn of
Just fn → pure $ fn x
Nothing → pure x
-- The power operator needs special treatment
-- 1) it is right-associative => use foldr1 instead of foldl1
-- 2) the unary minus on the *left* side of the power operator has
-- a lower precedence, i.e. -2^3 = -(2^3). However, unary minus
-- on the *right* side has a higher precedence: 2^-3 = 2^(-3).
sepByPow ∷ P Expression
sepByPow = fix \e → foldr1 (BinOp Pow) <$> list e
where
list e = do
a ← suffixPow
as ← many do
powOp
func ← (subOp *> pure Negate) <|> (addOp *> pure id) <|> pure id
expr ← e
pure (func expr)
pure (a :| as)
sepByMulImplicit ∷ P Expression
sepByMulImplicit = foldl1 (BinOp Mul) <$> sepByPow `sepBy1` pure unit
prefixed ∷ P Expression
prefixed = fix \e →
(subOp *> (Negate <$> e))
<|> (addOp *> e)
<|> sepByMulImplicit
sepByMod ∷ P Expression
sepByMod = foldl1 (BinOp Mod) <$> prefixed `sepBy1` modOp
sepByDiv ∷ P Expression
sepByDiv = foldl1 (BinOp Div) <$> sepByMod `sepBy1` divOp
sepByMul ∷ P Expression
sepByMul = foldl1 (BinOp Mul) <$> sepByDiv `sepBy1` mulOp
sepBySub ∷ P Expression
sepBySub = foldl1 (BinOp Sub) <$> sepByMul `sepBy1` subOp
sepByAdd ∷ P Expression
sepByAdd = foldl1 (BinOp Add) <$> sepBySub `sepBy1` addOp
sepByConv ∷ P Expression
sepByConv = foldl1 (BinOp ConvertTo) <$> sepByAdd `sepBy1` arrOp
in sepByConv
where
commaOp = reservedOp ","
facOp = reservedOp "!"
powOp = reservedOp "^" <|> reservedOp "**"
modOp = reservedOp "%"
divOp = reservedOp "/" <|> reservedOp "÷" <|> reserved "per"
mulOp = reservedOp "*" <|> reservedOp "·" <|> reservedOp "⋅"
<|> reservedOp "×"
subOp = reservedOp "-"
addOp = reservedOp "+"
arrOp = reservedOp "->" <|> reservedOp "→" <|> reservedOp "➞" <|> reserved "to"
powPos s q | s == 1.0 = q
| otherwise = BinOp Pow q (Scalar $ fromNumber s)
powNeg s q = BinOp Pow q (Negate $ Scalar $ fromNumber s)
-- | Parse a mathematical expression (or conversion) like `3m+2in -> cm`.
fullExpression ∷ Environment → P Expression
fullExpression env = do
whiteSpace
expr ← expression env
eof <?> "end of input"
pure $ expr
-- | Parse an Insect command.
command ∷ P Command
command =
(
(reserved "help" <|> reserved "?") *> pure Help
<|> (reserved "list" <|> reserved "ls" <|> reserved "ll") *> pure List
<|> (reserved "reset") *> pure Reset
<|> (reserved "clear" <|> reserved "cls") *> pure Clear
<|> (reserved "quit" <|> reserved "exit") *> pure Quit
) <* eof
-- | Parse a variable- or function assignment.
assignment ∷ Environment → P Statement
assignment env = do
{ name, args, expr } ←
try do
whiteSpace
name ← token.identifier
args ← optionMaybe (parens (sepBy1 token.identifier (reservedOp ",")))
reservedOp "="
expr ← expression env
eof
pure { name: name, args: args, expr: expr }
-- Fail if the name can be parsed as a physical unit
failIfUnit name
case args of
Nothing → pure (VariableAssignment name expr)
Just xs → do
traverse_ failIfUnit xs
pure (FunctionAssignment name xs expr)
where
failIfUnit n =
when (isRight $ runParser n (derivedUnit <* eof)) $
fail ("'" <> n <> "' is reserved for a physical unit")
-- | Parse a statement in the Insect language.
statement ∷ Environment → P Statement
statement env =
(Command <$> command)
<|> assignment env
<|> (Expression <$> fullExpression env)
-- | Run the Insect-parser on a `String` input.
parseInsect ∷ Environment → String → Either ParseError Statement
parseInsect env inp = runParser inp (statement env)