-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.scala
880 lines (804 loc) · 27.6 KB
/
Main.scala
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
import scala.util.chaining.scalaUtilChainingOps
import Ast.LetInExpr
import Ast.Node
import Ast.LiteralExpr
import scala.math.Ordering
import scala.math.Ordered.orderingToOrdered
import scala.annotation.varargs
import Ast.BinaryOp
import Ast.UnaryOp
import Ast.FnDef
import Ast.FnArgs
import Ast.FnCall
import Evaluator.EvaluatedIdentifier
import scala.io.Source
import Ast.IfExpr
import Ast.MatchExpr
import Ast.CaseExpr
type SpannedIx = Either[Int, (Int, Int)]
trait Spanned {
def position: SpannedIx
}
sealed trait Token
// Binary Ops
case class Assign(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"="
}
case class Add(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"+"
}
case class Mul(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"*"
}
case class Div(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"/"
}
case class Sub(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"-"
}
case class Concat(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"<>"
}
case class GT(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f">"
}
case class GTE(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f">="
}
case class LT(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"<"
}
case class LTE(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"<="
}
case class Eq(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"=="
}
case class NotEq(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"!="
}
case class And(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"&&"
}
case class Or(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"||"
}
case class Pipe(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"|>"
}
case class Let(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"let"
}
case class In(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"in"
}
case class True(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"true"
}
case class False(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"false"
}
case class Match(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"match"
}
case class With(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"with"
}
case class Case(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"|"
}
case class RArrow(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"->"
}
case class If(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"if"
}
case class Then(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"then"
}
case class Else(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"else"
}
case class LBrace(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"{"
}
case class RBrace(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"}"
}
case class LParen(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"("
}
case class RParen(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f")"
}
case class Comma(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f","
}
case class EndLine(position: SpannedIx) extends Token with Spanned {
override def toString(): String = f";"
}
case class Integer(value: Int, position: SpannedIx) extends Token with Spanned {
override def toString(): String = f"$value"
}
case class StringVal(value: String, position: SpannedIx)
extends Token
with Spanned {
override def toString(): String = f"\"$value\""
}
case class Identifier(value: String, position: SpannedIx)
extends Token
with Spanned {
override def toString(): String = f"$value"
}
type Tokenized = Either[String, (List[Char], List[Token])]
object Tokens {
def isDoubleCharOperator(h: Char, t: Char): Boolean = {
(h, t) match {
case (
('!', '=') | ('=', '=') | ('|', '|') | ('&', '&') | ('|', '>') |
('<', '>') | ('>', '=') | ('<', '=') | ('-', '>')
) =>
true
case _ => false
}
}
def isSingleCharOperator(c: Char): Boolean = {
c match {
case '+' | '-' | '/' | '=' | '*' | '<' | '>' | '|' => true
case _ => false
}
}
def getOpToken(h: Char, t: Char, ix: Int): Token = {
(h, t) match {
case ('!', '=') => NotEq(position = Right(ix, ix + 1))
case ('=', '=') => Eq(position = Right(ix, ix + 1))
case ('|', '|') => Or(position = Right(ix, ix + 1))
case ('&', '&') => And(position = Right(ix, ix + 1))
case ('|', '>') => Pipe(position = Right(ix, ix + 1))
case ('<', '>') => Concat(position = Right(ix, ix + 1))
case ('<', '=') => LTE(position = Right(ix, ix + 1))
case ('>', '=') => GTE(position = Right(ix, ix + 1))
case ('-', '>') => RArrow(position = Right(ix, ix + 1))
}
}
def getOpToken(c: Char, ix: Int): Token = {
c match {
case '+' => Add(position = Left(ix))
case '-' => Sub(position = Left(ix))
case '*' => Mul(position = Left(ix))
case '/' => Div(position = Left(ix))
case '=' => Assign(position = Left(ix))
case '<' => LT(position = Left(ix))
case '>' => GT(position = Left(ix))
case '|' => Case(position = Left(ix))
}
}
def tokenize(
chars: List[Char],
tokens: List[Token] = List(),
ix: Int = 0
): Tokenized = {
chars match {
case Nil => Right(Nil, tokens.reverse)
case opH :: opT :: remaining if isDoubleCharOperator(opH, opT) =>
tokenize(remaining, getOpToken(opH, opT, ix) :: tokens, ix + 2)
case op :: remaining if isSingleCharOperator(op) =>
tokenize(remaining, getOpToken(op, ix) :: tokens, ix + 1)
case content @ (c :: _) if c.isLetter || c == '_' =>
tokenizeIdentifier(content, tokens, ix)
case content @ (c :: _) if c.isDigit => tokenizeNum(content, tokens, ix)
case ';' :: remaining =>
tokenize(remaining, EndLine(position = Left(ix)) :: tokens, ix + 1)
case ',' :: remaining =>
tokenize(remaining, Comma(position = Left(ix)) :: tokens, ix + 1)
case '{' :: remaining =>
tokenize(remaining, LBrace(position = Left(ix)) :: tokens, ix + 1)
case '}' :: remaining =>
tokenize(remaining, RBrace(position = Left(ix)) :: tokens, ix + 1)
case '(' :: remaining =>
tokenize(remaining, LParen(position = Left(ix)) :: tokens, ix + 1)
case ')' :: remaining =>
tokenize(remaining, RParen(position = Left(ix)) :: tokens, ix + 1)
case '"' :: remaining => tokenizeString(remaining, tokens, ix + 1)
case (' ' | '\n' | '\t') :: remaining =>
tokenize(remaining, tokens, ix + 1)
case x :: _ => Left(f"Unknown token $x")
}
}
def isIdentifierChar(c: Char): Boolean = {
return c.isDigit || c.isLetter || c == '_'
}
def tokenizeIdentifier(
chars: List[Char],
tokens: List[Token],
ix: Int
): Tokenized = {
val identifier = chars.takeWhile(c => isIdentifierChar(c)).mkString
val endIx = ix + identifier.length() - 1
val tok = getKeyword(identifier, ix, endIx) match {
case Some(keyword) => keyword
case None => {
val position = if ix == endIx then Left(ix) else Right(ix, endIx)
Identifier(value = identifier, position = position)
}
}
val remaining = chars.slice(identifier.length(), chars.length)
return tokenize(remaining, tok :: tokens, endIx + 1)
}
def getKeyword(identifier: String, ix: Int, endIx: Int): Option[Token] = {
identifier match {
case "let" => Some(Let(position = Right(ix, endIx)))
case "in" => Some(In(position = Right(ix, endIx)))
case "if" => Some(If(position = Right(ix, endIx)))
case "then" => Some(Then(position = Right(ix, endIx)))
case "else" => Some(Else(position = Right(ix, endIx)))
case "true" => Some(True(position = Right(ix, endIx)))
case "false" => Some(False(position = Right(ix, endIx)))
case "match" => Some(Match(position = Right(ix, endIx)))
case "with" => Some(With(position = Right(ix, endIx)))
case _ => None
}
}
def tokenizeString(
chars: List[Char],
tokens: List[Token],
ix: Int
): Tokenized = {
val stringVal = chars.takeWhile(c => c != '"').mkString
val endIx = ix + stringVal.length
val tok = StringVal(
value = stringVal,
position = Right(ix, endIx)
)
val remaining =
chars.slice(from = stringVal.length() + 1, until = chars.length)
return tokenize(remaining, tok :: tokens, endIx + 1)
}
def tokenizeNum(
chars: List[Char],
tokens: List[Token],
ix: Int
): Tokenized = {
val digits = chars.takeWhile(c => c.isDigit)
val intValue = digits.mkString.toIntOption
val endIx = ix + digits.length - 1
intValue match {
case Some(value) => {
val tok =
Integer(value = value, position = Right(ix, endIx))
val remaining =
chars.slice(from = digits.length, until = chars.length)
return tokenize(remaining, tok :: tokens, endIx + 1)
}
case None => Left(f"failed to parse integer $digits")
}
}
}
type Parsed = Either[String, (Node, List[Token])]
enum DType:
case Int, String, Bool, Fn
enum Precedence:
case Lowest, In, Addition, Multiplication, Paren, ThenElse, Comp
given Ordering[Precedence] with
def compare(x: Precedence, y: Precedence): Int = x.ordinal compare y.ordinal
given Ordering[DType] with
def compare(x: DType, y: DType): Int = x.ordinal compare y.ordinal
object Ast {
sealed trait Node
case class LetInExpr(name: Node, value: Node, scope: Node) extends Node {
// override def toString(): String = f"LetInExpr(\n\t[$name = $value] in\n\t( $scope )\n)"
}
case class FnCall(name: Identifier, args: FnArgs) extends Node
case class FnDef(name: Identifier, args: FnArgs) extends Node
case class FnArgs(args: List[Node]) extends Node
case class IfExpr(cond: Node, thenExpr: Node, elseExpr: Node) extends Node {
// override def toString(): String =
// f"if ( $cond )\nthen ( $thenExpr )\nelse ( $elseExpr )"
}
case class BinaryOp(op: Token, l: Node, r: Node) extends Node {
// override def toString(): String = f"( $l $op $r )"
}
case class UnaryOp(op: Token, r: Token) extends Node
case class LiteralExpr(value: Token) extends Node {
// override def toString(): String = f"$value"
}
case class MatchExpr(pattern: Node, caseExprs: List[CaseExpr]) extends Node
case class CaseExpr(caseStructure: Node, branchExpr: Node) extends Node
}
object Parser {
def parse(
tokens: List[Token],
precedence: Precedence = Precedence.Lowest
): Parsed = {
tokens match {
case Nil => Left("None")
case Match(_) :: t => parseMatch(t)
case Let(_) :: (ident @ (Identifier(_, _))) :: Assign(_) :: t =>
parseLet(toIdentNode(ident), t)
case Let(_) :: (ident @ (Identifier(_, _))) :: LParen(_) :: t =>
parseFnDef(ident, t)
.flatMap((fnVal, remaining) => parseLet(fnVal, remaining))
case (fn @ (Identifier(_, _))) :: LParen(_) :: t => parseFnCall(fn, t)
case If(_) :: t => parseIf(t, precedence)
case LParen(_) :: t => parse(t)
case (intval @ Integer(_, _)) :: t => parseIdent(intval, t, precedence)
case (strval @ StringVal(_, _)) :: t => parseIdent(strval, t, precedence)
case (ident @ Identifier(_, _)) :: t => parseIdent(ident, t, precedence)
case (bv @ True(_)) :: t => parseIdent(bv, t, precedence)
case (bv @ False(_)) :: t => parseIdent(bv, t, precedence)
case e :: _ => Left(f"Parsing Error at $e")
}
}
def parseIf(tokens: List[Token], precedence: Precedence): Parsed = {
for {
(condition, remaining) <- parse(tokens, Precedence.Lowest)
(thenExpr, remaining) <- remaining match {
case Then(_) :: t => parse(t, Precedence.ThenElse)
case x =>
Left(
f"expected 'then' expression after 'if condition': $condition - found $x"
)
}
(elseExpr, remaining) <-
remaining match {
case Else(_) :: t => parse(t, Precedence.Lowest)
case x =>
Left(
f"expected 'else' expression after 'then' expression: $thenExpr- found $x"
)
}
} yield (
IfExpr(cond = condition, thenExpr = thenExpr, elseExpr = elseExpr),
remaining
)
}
def parseFnCall(fnIdent: Identifier, tokens: List[Token]): Parsed = {
for {
(args, remaining) <- parseArgs(tokens)
} yield (FnCall(name = fnIdent, args = args), remaining)
}
def toIdentNode(ident: Identifier): LiteralExpr = {
LiteralExpr(value = ident)
}
def parseArgs(
tokens: List[Token],
acc: List[Node] = List()
): Either[String, (FnArgs, List[Token])] = {
// Lambda
tokens match {
case RParen(_) :: t =>
val args = FnArgs(args = acc.reverse)
Right((args, t))
case Comma(_) :: t =>
parse(t)
.flatMap((parsedArg, remaining) =>
parseArgs(remaining, parsedArg :: acc)
)
case total @ (h :: t) =>
parse(total)
.flatMap((parsedArg, remaining) =>
parseArgs(remaining, parsedArg :: acc)
)
case Nil => Left("Unexpectedly reached end of program")
}
}
def parseFnDef(identifier: Identifier, tokens: List[Token]): Parsed = {
for {
(args, remaining) <- parseArgs(tokens)
result <- remaining match {
case Assign(_) :: t =>
val fnDef = FnDef(name = identifier, args = args)
Right(fnDef, t)
case _ => Left("Expected fn declaration to be followed by definition")
}
} yield (result)
}
def parseWith(
l: Node,
tokens: List[Token],
precedence: Precedence
): Parsed = {
tokens match {
case Nil => Right(l, Nil)
case h :: t if isBinaryOp(h) =>
parseBinaryOp(l, h, t, precedence)
case _ => Right(l, tokens)
}
}
def parseIdent(
identifier: Token,
tokens: List[Token],
precedence: Precedence
): Parsed = {
val literal = LiteralExpr(value = identifier)
tokens match {
case h :: t if isBinaryOp(h) =>
parseBinaryOp(literal, h, t, precedence) match {
case l @ Left(_) => l
case Right(value, remaining) =>
// Handle the cases where we have a new binary to parse
remaining match {
case h :: t if isBinaryOp(h) =>
parseWith(value, remaining, precedence)
case RParen(_) :: t =>
parseWith(value, t, precedence)
case _ =>
Right(value, remaining)
}
}
case remaining @ (_ :: t) =>
val expr = LiteralExpr(value = identifier)
Right(expr, remaining)
case Nil =>
val expr = LiteralExpr(value = identifier)
Right(expr, List())
}
}
def opToPrecendence(op: Token): Precedence = {
op match {
case Add(_) | Sub(_) | Concat(_) => Precedence.Addition
case Div(_) | Mul(_) => Precedence.Multiplication
case RParen(_) => Precedence.Paren
case GT(_) | LT(_) | GTE(_) | LTE(_) | Eq(_) | NotEq(_) => Precedence.Comp
case _ => Precedence.Lowest
}
}
def parseBinaryOp(
l: Node,
op: Token,
tokens: List[Token],
precedence: Precedence
): Parsed = {
val operatorPrecedence = opToPrecendence(op)
if operatorPrecedence < precedence then return Right(l, op :: tokens)
parse(tokens, operatorPrecedence) match {
case Right(r, remaining) =>
Right((BinaryOp(op = op, l = l, r = r), remaining))
case l @ Left(_) => l
}
}
def parseMatch(tokens: List[Token]): Parsed = {
for {
(valToMatch, remaining) <- parse(tokens)
(casesToParse) <- remaining match {
case With(_) :: t => Right(t)
case _ => Left(f"Expected 'with' after match expression $valToMatch")
}
(cases, remaining) <- parseMatchCases(casesToParse)
} yield (MatchExpr(pattern = valToMatch, caseExprs = cases), remaining)
}
def parseMatchCases(
tokens: List[Token],
acc: List[CaseExpr] = List()
): Either[String, (List[CaseExpr], List[Token])] = {
tokens match {
case Nil => Right(acc.reverse, tokens)
case Case(_) :: t =>
for {
(caseExpr, remaining) <- parse(t)
(branchToParse) <- remaining match {
case RArrow(_) :: t => Right(t)
case _ => Left("Expected -> after case branch structure")
}
(branchExpr, remaining) <- parse(branchToParse)
result <-
var expr =
CaseExpr(caseStructure = caseExpr, branchExpr = branchExpr)
parseMatchCases(remaining, expr :: acc)
} yield result
case _ => Right((acc.reverse, tokens))
}
}
def parseLet(
ident: Node,
tokens: List[Token]
): Parsed = {
return parse(tokens) match {
case Right((expr, remaining)) =>
remaining match {
case In(_) :: t =>
parse(t).map((r, remaining) =>
(LetInExpr(name = ident, value = expr, scope = r), remaining)
)
case rest @ (x :: _) =>
Left(
f"Let expression must be followed by scope, found $x in $rest"
)
case Nil => Left("Unexpectedly Reached End")
}
case left @ Left(value) => left
}
}
def isBinaryOp(token: Token): Boolean = {
token match {
case Add(_) | Mul(_) | Div(_) | Sub(_) | Eq(_) | NotEq(_) | And(_) | Or(
_
) | Pipe(_) | GT(_) | LT(_) | LTE(_) | GTE(_) | Concat(_) =>
true
case _ => false
}
}
}
object Evaluator {
sealed trait Evaluated
case class EvaluatedInt(value: Int) extends Evaluated {
override def toString(): String = f"$value"
}
case class EvaluatedBool(value: Boolean) extends Evaluated {
override def toString(): String = f"$value"
}
case class EvaluatedString(value: String) extends Evaluated {
override def toString(): String = f"$value"
}
case class EvaluatedIdentifier(value: String) extends Evaluated
case class Lazy(value: Node, args: FnArgs) extends Evaluated
type Context = Map[String, Evaluated]
def evalNode(
node: Node,
context: Context = Map.empty[String, Evaluated]
): Either[String, Evaluated] = {
node match {
case LiteralExpr(value) => evalLiteral(value, context)
case BinaryOp(op, l, r) => evalBinary(op, l, r, context)
case MatchExpr(mp, caseExprs) => evalMatchExpr(mp, caseExprs, context)
case LetInExpr(LiteralExpr(Identifier(name, _)), value, scope) =>
for {
assignedVal <- evalNode(value, context)
result <- evalNode(scope, addToContext(name, assignedVal, context))
} yield result
case LetInExpr(FnDef(ident @ Identifier(name, _), args), value, scope) =>
for {
fnVal <- evalFnDef(ident, args, value, context)
result <- evalNode(scope, addToContext(name, fnVal, context))
} yield result
case FnCall(Identifier(name, _), args) =>
for {
evalArgs <- evalFnArgs(args, context)
result <-
evalFnCall(name, evalArgs, context)
} yield result
case IfExpr(cond, thenExpr, elseExpr) =>
for {
condition <- evalNode(cond, context)
concreteCondition <- getConcreteValue(condition, context)
result <- concreteCondition match {
case EvaluatedBool(true) => evalNode(thenExpr, context)
case EvaluatedBool(false) => evalNode(elseExpr, context)
case x =>
val msg =
f"Invalid If Expression: Expected Boolean condition, found: $x"
Left(msg)
}
} yield result
case x => Left(f"Error when evaluating $x")
}
}
def evalMatchExpr(
pattern: Node,
cases: List[CaseExpr],
context: Context
): Either[String, Evaluated] = {
for {
evalutatedPattern <- evalNode(pattern, context)
concretePattern <- getConcreteValue(evalutatedPattern, context)
result <- evalCasesUntilMatch(concretePattern, cases, context)
} yield result
}
def evalCasesUntilMatch(
evaluatedMatch: Evaluated,
cases: List[CaseExpr],
context: Context
): Either[String, Evaluated] = {
cases match {
case Nil => Left("Should be unreachable! -- Failed to match any cases")
case CaseExpr(caseStructure, branchExpr) :: t =>
for {
evaluatedCase <- evalNode(caseStructure)
result <-
if evaluatedCase == evaluatedMatch
then evalNode(branchExpr, context)
else evalCasesUntilMatch(evaluatedMatch, t, context)
} yield result
}
}
def evalFnCall(
name: String,
args: List[Evaluated],
context: Context
): Either[String, Evaluated] = {
context.get(name) match {
case None => Left(f"Function $name not found")
case Some(Lazy(value, fnArgs)) =>
for {
fnContext <- makeFnContext(context, args, fnArgs)
result <- evalNode(value, fnContext)
} yield result
case Some(x) => Left(f"Invalid function found: $x")
}
}
def makeFnContext(
context: Context,
callArgs: List[Evaluated],
defArgs: FnArgs
): Either[String, Context] = {
for {
matchedArgs <- checkFnArgs(callArgs, defArgs.args, context = context)
} yield matchedArgs.foldRight[Context](context)((toAdd, context) =>
val (k, v) = toAdd
addToContext(k, v, context)
)
}
def checkFnArgs(
callArgs: List[Evaluated],
defArgs: List[Node],
acc: List[(String, Evaluated)] = List(),
context: Context
): Either[String, List[(String, Evaluated)]] = {
(callArgs, defArgs) match {
case (Nil, _ :: _) | (_ :: _, Nil) => Left("Wrong Number of args")
case (
evaluated :: restCallArgs,
LiteralExpr(Identifier(name, _)) :: restDefArgs
) =>
for {
evaluatedArg <- getConcreteValue(evaluated, context)
result <- checkFnArgs(
restCallArgs,
restDefArgs,
(name, evaluatedArg) :: acc,
context
)
} yield result
case (Nil, Nil) => Right(acc.reverse)
case (a, b) => Left(f"Error evaluaing function args $a, $b")
}
}
def evalFnArgs(
args: FnArgs,
context: Context
): Either[String, List[Evaluated]] = {
args.args
.map(a => evalNode(a, context))
.foldRight[Either[String, List[Evaluated]]](Right(Nil))((either, acc) =>
for {
list <- acc
value <- either
} yield value :: list
)
}
def intoLazy(node: Node, args: FnArgs): Lazy = {
// returns an 'evaluated value' that can be further evaluated
Lazy(value = node, args = args)
}
def evalFnDef(
name: Identifier,
args: FnArgs,
body: Node,
context: Context
): Either[String, Evaluated] = {
Right(intoLazy(body, args))
}
def addToContext(key: String, value: Evaluated, context: Context): Context = {
context + (key -> value)
}
def evalLiteral(value: Token, context: Context): Either[String, Evaluated] = {
value match {
case Integer(value, _) => Right(EvaluatedInt(value = value))
case StringVal(value, _) => Right(EvaluatedString(value = value))
case Identifier(value, _) => Right(EvaluatedIdentifier(value = value))
case True(value) => Right(EvaluatedBool(value = true))
case False(value) => Right(EvaluatedBool(value = false))
case e => Left(f"Invalid Literal: $e")
}
}
def getConcreteValue(
node: Evaluated,
context: Context
): Either[String, Evaluated] = {
node match {
case EvaluatedIdentifier(name) =>
context.get(name) match {
case Some(v) => Right(v)
case None => Left(f"Identifier $name not defined")
}
case x => Right(x)
}
}
def evalBinary(
operator: Token,
l: Node,
r: Node,
context: Context
): Either[String, Evaluated] = {
for {
lEvaluated <- evalNode(l, context)
rEvaluated <- evalNode(r, context)
lConcrete <- getConcreteValue(lEvaluated, context)
rConcrete <- getConcreteValue(rEvaluated, context)
result <- (lConcrete, rConcrete) match {
case (EvaluatedString(lval), EvaluatedString(rval)) =>
evalStringBinary(lval, rval, operator)
case (EvaluatedInt(lval), EvaluatedInt(rval)) =>
evalIntegerBinary(lval, rval, operator)
case (EvaluatedBool(lval), EvaluatedBool(rval)) =>
evalBooleanBinary(lval, rval, operator)
case _ => Left("Invalid Evaluated")
}
} yield result
}
def evalStringBinary(
l: String,
r: String,
op: Token
): Either[String, EvaluatedString] = {
val value = op match {
case Concat(_) => Some(l + r)
case x => None
}
value match {
case Some(v) => Right(EvaluatedString(value = v))
case None => Left(f"Invalid Operator $op for strings $l and $r")
}
}
def evalIntegerBinary(
l: Int,
r: Int,
op: Token
): Either[String, Evaluated] = {
val value = op match {
case Add(_) => Some(l + r)
case Sub(_) => Some(l - r)
case Mul(_) => Some(l * r)
case Div(_) => Some(l / r)
case LT(_) => Some(l < r)
case Eq(_) => Some(l == r)
case NotEq(_) => Some(l == r)
case LTE(_) => Some(l <= r)
case GT(_) => Some(l > r)
case GTE(_) => Some(l >= r)
case x => None
}
value match {
case Some(v: Int) => Right(EvaluatedInt(value = v))
case Some(v: Boolean) => Right(EvaluatedBool(value = v))
case None => Left(f"Invalid Operator $op for integers $l and $r")
}
}
def evalBooleanBinary(
l: Boolean,
r: Boolean,
op: Token
): Either[String, Evaluated] = {
val value = op match {
case Eq(_) => Some(l == r)
case NotEq(_) => Some(l != r)
case And(_) => Some(l && r)
case Or(_) => Some(l || r)
case x => None
}
value match {
case Some(v: Boolean) => Right(EvaluatedBool(value = v))
case None => Left(f"Invalid Operator $op for booleans $l and $r")
}
}
}
object MiniFP {
def main(args: Array[String]) = {
val filename = "examples/match.mfp"
val input = Source.fromFile(filename).getLines().mkString("\n")
val result = Tokens
.tokenize(input.toList)
.flatMap((_, c) => {
Parser.parse(c)
})
val evaluated = result match {
case l @ Left(value) => l
case Right(node, _) =>
Evaluator.evalNode(node)
}
evaluated match {
case Left(err) => println(f"Error: $err")
case Right(evaluated) => println(f"Evaluated to: $evaluated")
}
}
}