Source

xilocaml / UnitTests.hs

Full commit
  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
module UnitTests where
import Test.HUnit
import qualified Data.Map as Map
import Control.Monad.State
import AbsXilocaml
import ParXilocaml
import ErrM
import Semantics
import Interpreter
import TypeEnvironment
import RunEnvironment
import Unification
import Common
import PrettyShow
import Position
import Main hiding (main)

tests =
	TestList [
		TestLabel "Semantics" $ TestList [
			TestLabel "Primitive types" $ TestList [
				assertParsedTypeEquals "1" TInt,
				assertParsedTypeEquals "1.0" TFloat,
				assertParsedTypeEquals "1." TFloat,
				assertParsedTypeEquals "true" TBool
			],
			TestLabel "Arithmentic, logical and comparison operations" $ TestList [
				assertParsedTypeEquals "not true" TBool,
				assertParsedBadSemantics "not 1.0",
				assertParsedTypeEquals "true || false" TBool,
				assertParsedBadSemantics "1 <= 1.0",
				assertParsedTypeEquals "1 * 3" TInt,
				assertParsedTypeEquals "1.0 +. 3.0" TFloat,
				assertParsedBadSemantics "1.0 + 2.0",
				assertParsedTypeEquals "-. 1.0" TFloat,
				assertParsedBadSemantics "+. 1",
				assertParsedTypeEquals "1 + 1 > 2 && 2. *. 3. <= 2. || true && not false" TBool
			],
			TestLabel "Unary operators" $ TestList [
				assertParsedTypeEquals "-1" TInt,
				assertParsedTypeEquals "-1.0" TFloat,
				assertParsedTypeEquals "-. -. +. 1." TFloat,
				assertParsedTypeEquals "+ - - + 1" TInt,
				assertParsedTypeEquals "+ -. - +. + - 1." TFloat
			],
			TestLabel "If-then-else" $ TestList [
				assertParsedTypeEquals "if 1 > 2 then 1 else 4" TInt,
				assertParsedTypeEquals "if true then false else true" TBool,
				assertParsedBadSemantics "if 1 then false else true",
				assertParsedBadSemantics "if true then 1 else 1.0"
			],
			TestLabel "Undefined variable" $ assertParsedBadSemantics "a",
			TestLabel "Explicit types" $ TestList [
				assertParsedTypeEquals "(1 : int)" TInt,
				assertParsedBadSemantics "(1 : bool)",
				assertParsedTypeEquals "(1+1*1 : int)" TInt,
				assertParsedTypeEquals "(1 : 'a)" TInt,
				assertParsedTypeEquals "(fun x -> x : 'a -> 'a)" $
					TFun basicPolyType basicPolyType,
				assertParsedTypeEquals "([] : 'a list)" $ TList basicPolyType,
				assertParsedTypeEquals "(fun x -> x : 'a -> 'b)" $ TFun basicPolyType basicPolyType,
				assertParsedTypeEquals "(fun x -> x : ('a -> 'a) -> ('b -> 'b))" $
					TFun (TFun basicPolyType basicPolyType) (TFun basicPolyType basicPolyType)
			],
			TestLabel "Lists" $ TestList [
				assertParsedTypeEquals "[]" $ TList $ basicPolyType,
				assertParsedTypeEquals "[1]" $ TList TInt,
				assertParsedTypeEquals "[[]]" $ TList $ TList basicPolyType,
				assertParsedTypeEquals "1::[1]" $ TList TInt,
				assertParsedTypeEquals "1::[]" $ TList TInt,
				assertParsedTypeEquals "[]::[]" $ TList $ TList basicPolyType,
				assertParsedTypeEquals "hd [1]" TInt,
				assertParsedTypeEquals "hd [[]]" $ TList basicPolyType,
				assertParsedTypeEquals "hd []" $ basicPolyType,
				assertParsedTypeEquals "tl [1.0]" $ TList TFloat,
				assertParsedTypeEquals "tl [[1.0]]" $ TList $ TList TFloat,
				assertParsedTypeEquals "tl []" $ TList basicPolyType
			],
			TestLabel "Lambda" $ TestList [
				assertParsedTypeEquals "fun (x : int) -> x" $ TFun TInt TInt,
				assertParsedBadSemantics "fun (x : int) -> y",
				assertParsedBadSemantics "fun (x : int) -> not x",
				assertParsedTypeEquals "fun (x : int) (y : int) -> x + y" $ TFun TInt (TFun TInt TInt),
				assertParsedTypeEquals "fun (x : int) -> fun (y : int) -> x * y" $ TFun TInt (TFun TInt TInt),
				assertParsedTypeEquals "(fun (x : int) -> x : int -> int)" $ TFun TInt TInt,
				assertParsedTypeEquals "fun (f : int -> int) -> f" $ TFun (TFun TInt TInt) (TFun TInt TInt)
			],
			TestLabel "Function application" $ TestList [
				assertParsedTypeEquals "(fun (x : int) -> 2 * x) 3" TInt,
				assertParsedTypeEquals "(fun x -> 2 * x) 3" TInt,
				assertParsedTypeEquals "let f (x : int) = x in f 2" TInt
			],
			TestLabel "Let in" $ TestList [
				assertParsedTypeEquals "let a = 2 in a" TInt,
				assertParsedBadSemantics "let a = 2 in b",
				assertParsedBadSemantics "let a = a in a",
				assertParsedTypeEquals "let a : int = 2 in a" TInt,
				assertParsedBadSemantics "let a : bool = 2 in a",
				assertParsedTypeEquals "let a (x : int) = x in a" $ TFun TInt TInt,
				assertParsedBadSemantics "let a (x : int) = not x in a",
				assertParsedBadSemantics "let a (x : int) : bool = x in a",
				assertParsedTypeEquals "let a (x : int) : int = 2 in a" $ TFun TInt TInt,
				assertParsedTypeEquals "let a (x : int) : int = x in a" $ TFun TInt TInt
			],
			TestLabel "Let rec" $ TestList [
				assertParsedTypeEquals "let rec x : int = 2 in x" TInt,
				assertParsedTypeEquals "let rec l : 'a list = [] in l" $ TList basicPolyType,
				assertParsedTypeEquals "let rec f (x : int) : int = x in f" $ TFun TInt TInt,
				assertParsedTypeEquals "let rec f (x : int) : int = g x and g (x : int) : int = f x in f" $ TFun TInt TInt,
				assertParsedTypeEquals "let rec a : int = 2 and f (x : int) : int = a * x in f 3" TInt
			],
			TestLabel "Let rec helper functions" $ TestList [
				execStateT (prepareRecDecls
					[LocalVarDecl (buildOIdent "a") (buildEInt 1), LocalVarDeclExplType (buildOIdent "b") TInt $ buildEInt 2])
					(TypeEnvironment Map.empty Map.empty 0) ~?=
					(Ok $ TypeEnvironment (Map.fromList [("a", UInt), ("b", UInt)]) Map.empty 0),
				execStateT (prepareRecDecls
					[LocalFunDecl (buildOIdent "f") [FunArg $ buildOIdent "x"] $ buildEVar "x"])
					(TypeEnvironment Map.empty Map.empty 0) ~?=
					(Ok $ TypeEnvironment (Map.fromList [("f", UFun (UTerm 1) (UTerm 0))]) Map.empty 2),
				execStateT (prepareRecDecls
					[LocalFunDecl (buildOIdent "f") [FunArgExplType (buildOIdent "x") basicPolyType] $ buildEVar "x"])
					(TypeEnvironment Map.empty Map.empty 0) ~?=
					(Ok $ TypeEnvironment (Map.fromList [("f", UFun (UTerm 1) (UTerm 0))]) Map.empty 2),
				execStateT (prepareRecDecls
					[LocalFunDecl (buildOIdent "f") [FunArgExplType (buildOIdent "x") TInt, FunArg $ buildOIdent "y"] $ buildEVar "x"])
					(TypeEnvironment Map.empty Map.empty 0) ~?=
					(Ok $ TypeEnvironment (Map.fromList [("f", UFun UInt (UFun (UTerm 1) (UTerm 0)))]) Map.empty 2),
				execStateT (addRecFunDecls
					[LocalFunDecl (buildOIdent "f") [FunArg $ buildOIdent "x"] $ buildEInt 1])
					(TypeEnvironment (Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)]) Map.empty 2) ~?=
					(Ok $ TypeEnvironment
						(Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)])
						(Map.fromList [(UTerm 0, UInt)]) 2),
				execStateT (addRecFunDecls
					[LocalFunDecl (buildOIdent "f") [FunArg $ buildOIdent "x"] $ buildEVar "x"])
					(TypeEnvironment (Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)]) Map.empty 2) ~?=
					(Ok $ TypeEnvironment
						(Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)])
						(Map.fromList [(UTerm 0, UTerm 1)]) 2),
				execStateT (addRecFunDecls
					[LocalFunDecl (buildOIdent "f") [FunArg $ buildOIdent "x"] $
						EIfThenElse
							(ECmp (buildEVar "x") OLeq (buildEInt 42))
							(buildEVar "x")
							(EAppl (buildEVar "f") (buildEVar "x"))])
					(TypeEnvironment (Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)]) Map.empty 2) ~?=
					(Ok $ TypeEnvironment
						(Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)])
						(Map.fromList [(UTerm 0, UInt), (UTerm 1, UInt), (UTerm 2, UInt)]) 3),
				execStateT (addRecPolymorphism
					[LocalFunDecl (buildOIdent "f") [FunArg $ buildOIdent "x"] $ buildEVar "x"])
					(TypeEnvironment
						(Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)])
						(Map.fromList [(UTerm 0, UTerm 1)]) 2) ~?=
					(Ok $ TypeEnvironment
						(Map.fromList [("f", UFun (UTerm 1) (UTerm 0)), ("x", UTerm 1)])
						(Map.fromList [(UTerm 0, UTerm 1),(UTerm 1, UPoly 1)]) 2)
			],
			TestLabel "Function type checker" $ TestList [
				assertTypeEquals (checkFun [] (buildEInt 3)) startTEnv UInt,
				assertBadSemantics (checkFun [] (buildEVar "x")) startTEnv,
				assertTypeEquals (checkFun [FunArgExplType (buildOIdent "x") TInt] (buildEInt 2)) startTEnv $ UFun UInt UInt,
				assertTypeEquals (checkFun [FunArgExplType (buildOIdent "x") TInt] (buildEVar "x")) startTEnv $ UFun UInt UInt,
				assertTypeEquals (checkFun [] (buildEVar "x"))
					(TypeEnvironment (Map.fromList[("x", UInt)]) Map.empty 0) UInt,
				assertTypeEquals (checkFun [FunArgExplType (buildOIdent "x") TBool] (buildEVar "x"))
					(TypeEnvironment (Map.fromList [("x", UInt)]) Map.empty 0) $ UFun UBool UBool
			],
			TestLabel "Type inference" $ TestList [
				assertParsedTypeEquals "1" TInt,
				assertParsedTypeEquals "[[];[1]]" $ TList $ TList TInt,
				assertParsedTypeEquals "[[];[[]]]" $ TList $ TList $ TList basicPolyType,
				assertParsedTypeEquals "fun x -> x" $ TFun basicPolyType basicPolyType,
				assertParsedTypeEquals "fun x y -> x" $ TFun basicPolyType $ TFun basicPolyType' basicPolyType,
				assertParsedTypeEquals "let f x = x in f" $ TFun basicPolyType basicPolyType,
				assertParsedTypeEquals "let l = [] in l" $ TList basicPolyType,
				assertParsedTypeEquals "let rec l = [] in l" $ TList basicPolyType,
				assertParsedTypeEquals "let rec f x = f x in f" $ TFun basicPolyType basicPolyType'
			],
			TestLabel "Limitations of type inference in recursion" $ TestList [
				assertParsedTypeEquals "let rec l = [] and l' = 1::l in l" $ TList TInt,
				assertParsedBadSemantics "let rec l = [] and l' = 1::l and l'' = []::l in l"
			],
			TestLabel "Function comparison" $ TestList [
				TestLabel "Limitation for polymorphic functions" $
					assertParsedTypeEquals "let cmp (x : 'a) (y : 'a) : bool = x < y in cmp (fun x -> 3 * x) (fun x -> 2 * x)" TBool,
				assertParsedBadSemantics "(fun x -> 3 * x) < (fun x -> 2 * x)"
			],
			TestLabel "Unification - without testing environment" $ TestList [
				assertUnifiedTypesEqual UInt UInt UInt,
				assertUnificationFails UInt UBool,
				assertUnifiedTypesEqual (UTerm 0) UInt UInt,
				assertUnifiedTypesEqual (UTerm 0) (UTerm 1) (UTerm 0),
				assertUnifiedTypesEqual (UTerm 0) (UTerm 1) (UTerm 1),
				assertUnifiedTypesEqual (UList $ UTerm 0) (UList UInt) (UList UInt),
				assertUnifiedTypesEqual (UFun UInt UInt) (UFun UInt UInt) (UFun UInt UInt),
				assertUnificationFails (UFun UInt UBool) (UFun UInt UInt),
				assertUnificationFails (UFun UBool UInt) (UFun UInt UInt),
				assertUnifiedTypesEqual (UTerm 0) (UList $ UTerm 1) (UList $ UTerm 1),
				assertUnifiedTypesEqual (UFun (UTerm 0) UInt) (UFun UBool UInt) (UFun UBool UInt),
				assertUnificationFails (UFun (UTerm 0) (UTerm 0)) (UFun (UTerm 1) (UFun (UTerm 1) (UTerm 1))),
				assertUnifiedTypesEqual
					(UFun (UFun (UTerm 0) (UTerm 0)) (UTerm 0))
					(UFun (UTerm 1) (UFun (UTerm 2) (UTerm 2)))
					(UFun (UFun (UFun (UTerm 2) (UTerm 2)) (UFun (UTerm 2) (UTerm 2))) (UFun (UTerm 2) (UTerm 2))),
				assertUnifiedTypesEqual
					(UFun (UList $ UFun (UTerm 0) (UTerm 0)) (UTerm 0))
					(UFun (UList $ UTerm 1) UInt)
					(UFun (UList $ UFun UInt UInt) UInt),
				assertUnificationFails (UFun (UList (UTerm 0)) (UTerm 0)) (UFun (UTerm 0) (UList (UTerm 0))),
				assertUnifiedTypesEqual
					(UFun (UTerm 0) (UTerm 0))
					(UFun (UFun (UTerm 1) (UTerm 1)) (UFun (UTerm 2) (UTerm 2)))
					(UFun (UFun (UTerm 1) (UTerm 1)) (UFun (UTerm 1) (UTerm 1)))
			],
			TestLabel "Unification - with testing environment" $ TestList [
				runStateT (unify "" (UList UInt) (UList UInt))
					(TypeEnvironment Map.empty Map.empty 0) ~?=
					Ok (UList UInt, TypeEnvironment Map.empty Map.empty 0),
				runStateT (unify "" (UTerm 0) (UTerm 1))
					(TypeEnvironment Map.empty Map.empty 2) ~?=
					Ok (UTerm 1, TypeEnvironment Map.empty (Map.fromList [(UTerm 0, UTerm 1)]) 2),
				runStateT (unify "" (UTerm 0) (UTerm 1))
					(TypeEnvironment Map.empty (Map.fromList [(UTerm 0, UTerm 2)]) 3) ~?=
					Ok (UTerm 1, TypeEnvironment Map.empty (Map.fromList [(UTerm 2, UTerm 1), (UTerm 0, UTerm 2)]) 3),
				runStateT (unify "" (UTerm 0) (UTerm 1))
					(TypeEnvironment Map.empty (Map.fromList [(UTerm 0, UList $ UTerm 2)]) 3) ~?=
					Ok (UList $ UTerm 2, TypeEnvironment Map.empty (Map.fromList [(UTerm 1, UList $ UTerm 2), (UTerm 0, UList $ UTerm 2)]) 3),
				runStateT (unify "" (UTerm 0) (UTerm 1))
					(TypeEnvironment Map.empty (Map.fromList [(UTerm 0, UTerm 1)]) 3) ~?=
					Ok (UTerm 1, TypeEnvironment Map.empty (Map.fromList [(UTerm 0, UTerm 1)]) 3),
				assertBad $ runStateT (unify "" (UTerm 0) (UTerm 1))
					(TypeEnvironment Map.empty (Map.fromList [(UTerm 0, UList $ UTerm 1)]) 3),
				evalStateT (unify ""
						(UFun (UTerm 0) (UTerm 0))
						(UFun (UFun (UPoly 0) (UPoly 0)) (UFun (UPoly 1) (UPoly 1)))
						>>= lookupType)
					(TypeEnvironment Map.empty Map.empty 7) ~?=
					Ok (UFun (UFun (UTerm 8) (UTerm 8)) (UFun (UTerm 8) (UTerm 8)))
			],
			TestLabel "Normalization" $ TestList [
				normalize (TFun TInt TInt) ~?= TFun TInt TInt,
				normalize (TPoly $ OPolyIdent "'a") ~?= TPoly (OPolyIdent "'a"),
				normalize
					(TFun (TFun (TList $ TPoly $ OPolyIdent "'x") TInt) (TFun (TPoly $ OPolyIdent "'y") (TPoly $ OPolyIdent "'x"))) ~?=
					(TFun (TFun (TList $ TPoly $ OPolyIdent "'a") TInt) (TFun (TPoly $ OPolyIdent "'b") (TPoly $ OPolyIdent "'a")))
			],
			TestLabel "Helper functions" $ TestList [
				occurs (UTerm 2) (UFun UInt (UList $ UTerm 2)) ~?= True,
				occurs (UTerm 1) (UFun (UFun (UPoly 1) (UTerm 2)) (UList $ UFun UInt (UTerm 3))) ~?= False
			],
			TestLabel "UType -> Type conversion" $ TestList [
				convertUTypeToType (UFun (UFun UInt UBool) (UList $ UFun UFloat UFloat)) ~?=
					TFun (TFun TInt TBool) (TList $ TFun TFloat TFloat),
				convertUTypeToType (UFun (UTerm 2) (UList $ UTerm 2)) ~?=
					TFun (TPoly $ OPolyIdent "2") (TList $ TPoly $ OPolyIdent "2"),
				normalize (convertUTypeToType $ UFun UInt (UFun (UPoly 2) (UList $ UFun (UPoly 1) (UPoly 2)))) ~?=
					TFun TInt (TFun (basicPolyType) (TList $ TFun (basicPolyType') (basicPolyType)))
			],
			TestLabel "UTerm -> UPoly conversion for identifiers" $ TestList [
				runStateT (convertIdTypeToPoly "x")
					(TypeEnvironment (Map.fromList [("x", UFun UInt UBool)]) Map.empty 0) ~?=
					Ok (UFun UInt UBool, TypeEnvironment (Map.fromList [("x", UFun UInt UBool)]) Map.empty 0),
				runStateT (convertIdTypeToPoly "x")
					(TypeEnvironment (Map.fromList [("x", UTerm 1)]) Map.empty 2) ~?=
					Ok (UPoly 1, TypeEnvironment (Map.fromList [("x", UPoly 1)]) (Map.fromList [(UTerm 1, UPoly 1)]) 2),
				evalStateT (convertIdTypeToPoly "x")
					(TypeEnvironment
						(Map.fromList [("x", UTerm 2)])
						(Map.fromList [(UTerm 2, UTerm 1)]) 3) ~?=
					(Ok $ UPoly 1),
				evalStateT (convertIdTypeToPoly "x")
					(TypeEnvironment
						(Map.fromList [("x", UTerm 3)])
						(Map.fromList [(UTerm 3, UTerm 1), (UTerm 1, UFun UBool (UTerm 0))]) 4) ~?=
					(Ok $ UFun UBool (UPoly 0)),
				evalStateT (convertIdTypeToPoly "x")
					(TypeEnvironment
						(Map.fromList [("x", UTerm 1), ("y", UTerm 2)])
						(Map.fromList [(UTerm 2, UTerm 1)]) 4) ~?=
					(Ok $ UPoly 1)
			],
			TestLabel "UPoly -> UTerm conversion" $ TestList [
				runStateT (convertPolyToTerm $ UFun UInt UBool)
					(TypeEnvironment Map.empty Map.empty 0) ~?=
					Ok (UFun UInt UBool, TypeEnvironment Map.empty Map.empty 0),
				runStateT (convertPolyToTerm $ UFun (UPoly 1) (UPoly 2))
					(TypeEnvironment Map.empty Map.empty 3) ~?=
					Ok (UFun (UTerm 3) (UTerm 4), TypeEnvironment Map.empty Map.empty 5),
				runStateT (convertPolyToTerm $ UFun (UPoly 1) (UPoly 1))
					(TypeEnvironment Map.empty Map.empty 5) ~?=
					Ok (UFun (UTerm 5) (UTerm 5), TypeEnvironment Map.empty Map.empty 6),
				runStateT (convertPolyToTerm $ UFun (UFun UBool (UPoly 1)) (UFun (UPoly 2) (UList $ UPoly 1)))
					(TypeEnvironment Map.empty Map.empty 3) ~?=
					Ok (UFun (UFun UBool (UTerm 3)) (UFun (UTerm 4) (UList $ UTerm 3)), TypeEnvironment Map.empty Map.empty 5)
			],
			TestLabel "Type -> UType conversion" $ TestList [
				runStateT (convertTypeToUType $ TFun TBool TBool) startTEnv ~?=
					Ok (UFun UBool UBool, TypeEnvironment Map.empty Map.empty 0),
				runStateT (convertTypeToUType $ TFun (TFun basicPolyType basicPolyType') basicPolyType) startTEnv ~?=
					Ok (UFun (UFun (UTerm 0) (UTerm 1)) (UTerm 0), TypeEnvironment Map.empty Map.empty 2),
				runStateT (convertTypeToUType $ TFun (TFun basicPolyType basicPolyType) (TFun basicPolyType basicPolyType)) startTEnv ~?=
					Ok (UFun (UFun (UTerm 0) (UTerm 0)) (UFun (UTerm 0) (UTerm 0)), TypeEnvironment Map.empty Map.empty 1),
				runState (convertTypeToPolyUType $ TFun (TList TInt) (TFun (TList $ basicPolyType) (TList $ TFun basicPolyType basicPolyType'))) startMapEnv ~?=
					(UFun (UList UInt) (UFun (UList $ UPoly 0) (UList $ UFun (UPoly 0) (UPoly 1))),
						Map.fromList [(OPolyIdent "'a", UPoly 0), (OPolyIdent "'b", UPoly 1)])
			],
			TestLabel "Hard cases" $ TestList [
				assertParsedBadSemantics "fun x -> x x",
				assertParsedBadSemantics "fun x y -> x x y"
			],
			TestLabel "Program structure" $ TestList [
				assertParsedTypeEquals "open List;; hd [1];;" TInt,
				assertParsedTypeEquals "hd [1];;" TInt,
				assertParsedTypeEquals "open List;; hd [1]" TInt,
				assertParsedTypeEquals "hd [1]" TInt
			]
		],
		TestLabel "Interpreter" $ TestList [
			TestLabel "Primitive types" $ TestList [
				assertParsedValueEquals "42" $ VInt 42,
				assertParsedValueEquals "true" $ VBool True,
				assertParsedValueEquals "false" $ VBool False,
				assertParsedValueEquals "42.0" $ VFloat 42.0,
				assertParsedValueEquals "42." $ VFloat 42.0,
				assertParsedValueEquals "42.e0" $ VFloat 42.0,
				assertParsedValueEquals "4.2E1" $ VFloat 42.0,
				assertParsedValueEquals ".42e2" $ VFloat 42.0,
				assertParsedValueEquals "4.2e+1" $ VFloat 42.0,
				assertParsedValueEquals "420e-1" $ VFloat 42.0
			],
			TestLabel "Arithmentic, logical and comparison operations" $ TestList [
				assertParsedValueEquals "not true" $ VBool False,
				assertParsedValueEquals "true || false" $ VBool True,
				assertParsedValueEquals "false || false" $ VBool False,
				assertParsedValueEquals "true || true" $ VBool True,
				assertParsedValueEquals "true && true" $ VBool True,
				assertParsedValueEquals "true && false" $ VBool False,
				assertParsedValueEquals "false && false" $ VBool False,
				assertParsedValueEquals "true || true && false" $ VBool True,
				assertParsedValueEquals "2 + 2 * 2" $ VInt 6,
				assertParsedValueEquals "3 / 1 - 1" $ VInt 2,
				assertParsedRuntimeError "1 / 0",
				assertParsedRuntimeError "0 / 0",
				assertParsedValueEquals "1 + 2 <= 3" $ VBool True,
				assertParsedValueEquals "2 > 2 && 2 < 5" $ VBool False,
				assertParsedValueEquals "3 = 5 || 3 >= 4" $ VBool False,
				assertParsedValueEquals "2 >= 3 || 2 = 3 || 3 > 4 && 3 < 4 || 2 <> 2" $ VBool False,
				assertParsedValueEquals "1 = 1 || 1 = 1 / 0" $ VBool True,
				assertParsedValueEquals "1 = 0 && 1 = 1 / 0" $ VBool False
			],
			TestLabel "If-then-else" $ TestList [
				assertParsedValueEquals "if 1 > 2 then 1 else 4" $ VInt 4,
				assertParsedValueEquals "if true then false else true" $ VBool False,
				assertParsedValueEquals "if true then 1 else 1 / 0" $ VInt 1,
				assertParsedRuntimeError "if true then 0 / 0 else 2"
			],
			TestLabel "Unary operators" $ TestList [
				assertParsedValueEquals "-1" $ VInt (-1),
				assertParsedValueEquals "-1.0" $ VFloat (-1.0)
			],
			TestLabel "Explicit types" $ TestList [
				assertParsedValueEquals "(1 : int)" $ VInt 1,
				assertParsedValueEquals "(1+1*1 : int)" $ VInt 2,
				assertParsedValueEquals "([] : 'a list)" $ VList []
			],
			TestLabel "Lists" $ TestList [
				assertParsedValueEquals "[]" $ VList [],
				assertParsedValueEquals "[1]" $ VList [VInt 1],
				assertParsedValueEquals "[true; false]" $ VList [VBool True, VBool False],
				assertParsedValueEquals "1::[1]" $ VList [VInt 1, VInt 1],
				assertParsedValueEquals "1::[]" $ VList [VInt 1],
				assertParsedValueEquals "[]::[]" $ VList [VList []],
				assertParsedValueEquals "hd [1]" $ VInt 1,
				assertParsedValueEquals "hd [[]]" $ VList [],
				assertParsedRuntimeError "hd []",
				assertParsedValueEquals "tl [1.0]" $ VList [],
				assertParsedValueEquals "tl [[1.0]]" $ VList [],
				assertParsedValueEquals "tl [[1;2];[3]]" $ VList [VList [VInt 3]],
				assertParsedRuntimeError "tl []",
				assertParsedRuntimeError "2::[1+1;1/0]"
			],
			TestLabel "Lambda" $ TestList [
				assertParsedValueEquals "fun (x : int) -> x" $ VFun startREnv ["x"] $ buildEVar "x",
				assertParsedValueEquals "fun (x : int) (y : int) -> x + y" $ VFun startREnv ["x", "y"] $ EInfixWeak (buildEVar "x") OAdd (buildEVar "y"),
				assertParsedValueEquals "fun (x : int) -> fun (y : int) -> x * y" $ VFun startREnv ["x"] $ ELambda [FunArgExplType (buildOIdent "y") TInt] $ EInfixStrong (buildEVar "x") OMul (buildEVar "y"),
				assertParsedValueEquals "fun (f : int -> int) -> f" $ VFun startREnv ["f"] $ buildEVar "f",
				assertParsedValueEquals "fun (x : int) -> x / 0" $ VFun startREnv ["x"] $ EInfixStrong (buildEVar "x") ODiv (buildEInt 0)
			],
			TestLabel "Function application" $ TestList [
				assertParsedValueEquals "(fun (x : int) -> 2 * x) 3" $ VInt 6,
				assertParsedValueEquals "(fun (x : int) (y : bool) -> if y then 2 * x else 3 * x) 2 false" $ VInt 6,
				assertParsedValueEquals "(fun (x : int) (y : int) -> x * y) 2" $ VFun (createEnv [("x", VInt 2)]) ["y"] $ EInfixStrong (buildEVar "x") OMul (buildEVar "y"),
				assertParsedValueEquals "(fun (x : int) (y : bool) -> fun (x : int) -> 2 * x) 2 true" $ VFun (createEnv [("y", VBool True), ("x", VInt 2)]) ["x"] $ EInfixStrong (buildEInt 2) OMul (buildEVar "x")
			],
			TestLabel "Comparison of functions" $ assertParsedRuntimeError "(fun x -> x = x) (fun x -> x)",
			TestLabel "Let in" $ TestList [
				assertParsedValueEquals "let a = 2 in a" $ VInt 2,
				assertParsedValueEquals "let a : int = 2 in a" $ VInt 2,
				assertParsedValueEquals "let a (x : int) = x in a" $ VFun startREnv ["x"] $ buildEVar "x",
				assertParsedValueEquals "let a (x : int) : int = 2 in a" $ VFun startREnv ["x"] $ buildEInt 2,
				assertParsedValueEquals "let a (x : int) : int = x in a" $ VFun startREnv ["x"] $ buildEVar "x",
				assertParsedValueEquals "1 + (let a = 2 in a + a)" $ VInt 5
			],
			TestLabel "Let rec" $ TestList [
				assertParsedValueEquals "let rec a = 2 in a" $ VInt 2,
				assertParsedValueEquals "let rec f (x : int) : int = if x <= 0 then -1 else 1 + f (x / 2) in f 1024" $ VInt 10,
				assertParsedValueEquals "let rec f (x : int) : int = if x <= 1 then 1 else x * f (x - 1) in f 6" $ VInt 720,
				assertParsedValueEquals "let rec a (x : int) : int = 2 and f (x : int) : int = x * a 3 in f 21" $ VInt 42,
				assertParsedValueEquals "let rec f (x : int) : int = g (x-1) and g (x : int) : int = if x <= 0 then 0 else f x in f 10" $ VInt 0,
				assertParsedValueEquals "(let y = 2 in let rec f (x : int) : int = g (x-1) and g (x : int) : int = if x = 0 then y else f x in f) 20" $ VInt 2,
				assertParsedValueEquals "let f = 2 in let g (x : int) = f * x in let rec f (x : int) : int = if x = 0 then 1 else f (x-1) in g (f 3)" $ VInt 2,
				assertParsedValueEquals "let rec res = 0 and f x = if x <= 0 then res else f (x - 1) in f 10" $ VInt 0
			],
			TestLabel "Looping environment" $ TestList [
				assertVariableFound ["x"] $ Ok $ createEnv [("x", VInt 1)],
				assertVariableFound ["f", "y"] $ Ok $ createEnv [("f", VFun (createEnv [("y", VInt 1)]) [] someExpression)],
				assertVariableFound ["f"] $
					execStateT (loopEnvironment ["f"]) $ createEnv
						[("f", VFun startREnv [] someExpression)],
				assertVariableFound ["f", "f", "f", "f", "f"] $
					execStateT (loopEnvironment ["f"]) $
					createEnv [("f", VFun startREnv [] someExpression)],
				assertVariableFound ["f", "f", "f", "f", "a"] $
					execStateT (loopEnvironment ["f"]) $ createEnv
						[("f", VFun startREnv [] someExpression),
						("a", VInt 1)],
				assertVariableFound ["f", "f", "g", "f", "g"] $
					execStateT (loopEnvironment ["f", "g"]) $ createEnv
						[("f", VFun startREnv [] someExpression),
						("g", VFun startREnv [] someExpression),
						("a", VInt 1)],
				assertVariableFound ["g", "f", "g", "f", "f", "h", "h", "f", "a"] $
					execStateT (loopEnvironment ["f", "g", "h"]) $ createEnv
						[("f", VFun startREnv [] someExpression),
						("g", VFun startREnv [] someExpression),
						("h", VFun startREnv [] someExpression),
						("a", VInt 1),
						("b", VBool True)]
			]
		],
		TestLabel "Position detection" $ TestList [
			position (EInt $ OInteger ((0,0), "42")) ~?= At 0 0,
			position (EList []) ~?= Somewhere,
			position (ELambda [FunArg $ OIdent ((1,12), "x")] (EVar $ OIdent ((1, 20), "x"))) ~?= At 1 12,
			position (EIfThenElse (ECmp (EList []) OEq (EList [])) (EList []) (EList [ListElement $ EList []])) ~?= Somewhere,
			position (EIfThenElse (ECmp (EList []) OEq (EList [])) (EList [ListElement $ EInt $ OInteger ((2,15), "42")]) (EList [ListElement $ EInt $ OInteger ((3,1), "44")])) ~?= At 2 15
		],
		TestLabel "Pretty printer" $ TestList [
			TestLabel "Position" $ TestList [
				prettyShow Somewhere ~?= "somewhere",
				prettyShow (At 3 2) ~?= "line 3 around column 2"
			],
			TestLabel "Types" $ TestList [
				prettyShow (TInt) ~?= "int",
				prettyShow (TFun TInt (TFun TBool TFloat)) ~?= "int -> bool -> float",
				prettyShow (TFun (TFun TInt TBool) TBool) ~?= "(int -> bool) -> bool",
				prettyShow (TList $ TList TBool) ~?= "bool list list",
				prettyShow (TList $ TFun TBool TInt) ~?= "(bool -> int) list",
				prettyShow (TFun basicPolyType basicPolyType') ~?= "'a -> 'b"
			],
			TestLabel "Values" $ TestList [
				prettyShow (VInt 42) ~?= "42",
				prettyShow (VFun startREnv [] someExpression) ~?= "<fun>",
				prettyShow (VList [VBool True, VBool False]) ~?= "[true;false]",
				prettyShow (VList [VBool True]) ~?= "[true]",
				prettyShow (VList []) ~?= "[]",
				prettyShow (VList [VFun startREnv [] someExpression, VFun startREnv [] someExpression]) ~?= "[<fun>;<fun>]"
			],
			TestLabel "UTypes" $ TestList [
				prettyShow (UFun UInt (UList UBool)) ~?= "int -> bool list",
				prettyShow (UFun (UPoly 1) (UPoly 2)) ~?= "'a -> 'b",
				prettyShow (UFun (UList $ UTerm 1) (UTerm 3)) ~?= "'a list -> 'b",
				prettyShow (UFun (UPoly 2) (UFun (UPoly 1) (UPoly 2))) ~?= "'a -> 'b -> 'a",
				prettyShow (UFun (UFun (UPoly 1) (UPoly 2)) (UFun (UPoly 1) (UPoly 2))) ~?= "('a -> 'b) -> 'a -> 'b"
			]
		],
		TestLabel "Main program" $ TestList [
			printResult "1+1" ~?= "2 : int",
			printResult "[let f (x : int) = 2 * x in f];;" ~?= "[<fun>] : (int -> int) list"
		],
		TestLabel "Full check for examples/" $ TestList [
			TestLabel "arithmetic.ml" $ printResult "1 - 1 - 1 + 11 + 2 * 4 / 2 * 8 + 6 / 3 mod 2;; (* = 42 *)" ~?= "42 : int",
			TestLabel "factorial.ml" $ printResult
				"let rec factorial n = \
				\    if n <= 1 then \
				\        1 \
				\    else \
				\        n * factorial (n-1) \
				\in factorial 6;;" ~?= "720 : int",
			TestLabel "identity.ml" $ printResult "let f x = x in f;;" ~?= "<fun> : 'a -> 'a",
			TestLabel "unary.ml" $ printResult "- -. - + +. + + - - -. - 1.0;;" ~?= "-1.0 : float",
			TestLabel "factorization.ml" $ printResult
				"let factorization n = \
				\    let rec fact n div acc = \
				\        if n mod div = 0 then \
				\            fact (n / div) div (div::acc) \
				\        else if n < div then \
				\            acc \
				\        else \
				\            fact n (div + 1) acc \
				\    in fact n 2 [] \
				\in factorization 48;;" ~?= "[3;2;2;2;2] : int list",
			TestLabel "fold_left.ml" $ printResult
				"open List;; \
				\let rec fold_left (f : 'a -> 'b -> 'a) (acc : 'a) (t : 'b list) : 'a = \
				\    if t = [] then \
				\        acc \
				\    else \
				\        fold_left f (f acc (hd t)) (tl t) \
				\in fold_left (fun acc e -> acc + e) 0 [1;2;3;4;5];; (* sum of 1..5 *)" ~?= "15 : int"
		]
	]


main = runTestTT tests

someExpression = EBool $ OBool ((0,0),"true")

buildEInt n = EInt $ OInteger ((0,0), show n)
buildEVar = EVar . buildOIdent
buildOIdent ident = OIdent ((0,0), ident)

basicPolyType = TPoly $ OPolyIdent "'a"
basicPolyType' = TPoly $ OPolyIdent "'b"

parsed input = do
	tree <- pProgram $ myLexer input
	t <- checkSemantics tree
	return $ normalize t

interpreted input = do
	tree <- pProgram $ myLexer input
	return $ interpret tree

assertParsedTypeEquals :: String -> Type -> Test
assertParsedTypeEquals input expectedType =
	case parsed input of
		Ok t -> t ~?= expectedType
		Bad s -> TestCase $ assertFailure $ "No type, but expected " ++ (show expectedType) ++ " in " ++ input ++ ". Error message: " ++ s ++ "."

assertParsedBadSemantics :: String -> Test
assertParsedBadSemantics input =
	case parsed input of
		Ok t -> TestCase $ assertFailure $ "Detected type " ++ (show t) ++ ", but expected type error in " ++ input ++ "."
		Bad s -> TestCase $ assertBool "" True

assertBad :: Show t => Err t -> Test
assertBad e =
	case e of
		Ok x -> TestCase $ assertFailure $ "Expected bad in " ++ (show e)
		Bad s -> TestCase $ assertBool "" True

assertTypeEquals :: EnvType UType -> TypeEnvironment -> UType -> Test
assertTypeEquals envType env expectedType =
	evalStateT envType env ~?= Ok expectedType

assertTypesEquals :: EnvType [UType] -> TypeEnvironment -> [UType] -> Test
assertTypesEquals envType env expectedTypes =
	evalStateT envType env ~?= Ok expectedTypes

assertBadSemantics :: EnvType UType -> TypeEnvironment -> Test
assertBadSemantics envType env =
	assertBad $ evalStateT envType env

assertParsedValueEquals :: String -> Value -> Test
assertParsedValueEquals input expectedValue =
	case interpreted input of
		Ok (Ok t) -> (removePosition t) ~?= expectedValue
		Ok (Bad s) -> TestCase $ assertFailure $ "Runtime error, but expected " ++ (show expectedValue) ++ " in " ++ input ++ ". Error message: " ++ s ++ "."
		Bad s -> TestCase $ assertFailure s

assertParsedRuntimeError :: String -> Test
assertParsedRuntimeError input =
	case interpreted input of
		Ok (Ok t) -> TestCase $ assertFailure $ "Detected value " ++ (show t) ++ ", but expected runtime error in " ++ input ++ "."
		Ok (Bad s) -> TestCase $ assertBool "" True
		Bad s -> TestCase $ assertFailure s

-- Input is sequence of identifiers of which every but last must be a function type.
assertVariableFound :: [String] -> Err RunEnvironment -> Test
assertVariableFound _ (Bad s) = TestCase $ assertFailure s
assertVariableFound idents (Ok env) = let
		lookupVariable :: [Ident] -> EnvRun ()
		lookupVariable [] = return ()
		lookupVariable [ident] = do
			v <- tryLookupEnv ident
			case v of
				Nothing -> lift $ Bad $ "Looked up variable " ++ ident ++ " doesn't exist."
				Just _ -> return ()
		lookupVariable (ident:idents) = do
			v <- tryLookupEnv ident
			case v of
				Nothing -> lift $ Bad $ "Looked up variable " ++ ident ++ " doesn't exist."
				Just (VFun env _ _) -> do
					put env
					lookupVariable idents
				Just _ -> lift $ Bad $ "Looked up variable " ++ ident ++ " is not a function."
		found = evalStateT (lookupVariable idents) env
	in case found of
		Ok _ -> TestCase $ assertBool "" True
		Bad s -> TestCase $ assertFailure s


createEnv :: [(String, t)] -> Map.Map Ident t
createEnv = Map.fromList

assertUnifiedTypesEqual :: UType -> UType -> UType -> Test
assertUnifiedTypesEqual t1 t2 expected =
	case evalStateT runTest startTEnv of
		Ok test -> test
		Bad s -> TestCase $ assertFailure s
	where
		runTest :: EnvType Test
		runTest = do
			t' <- unify "" t1 t2
			t'' <- lookupType t'
			t1' <- lookupType t1
			t2' <- lookupType t2
			expected' <- lookupType expected
			return $ TestLabel "Unification test internals" $ TestList [
					t'' ~?= expected',
					t1' ~?= expected',
					t2' ~?= expected'
				]

assertUnificationFails :: UType -> UType -> Test
assertUnificationFails t1 t2 =
	assertBad $ evalStateT (unify "" t1 t2) startTEnv


class RemoveablePosition t where
	removePosition :: t -> t

instance RemoveablePosition Exp where
	removePosition exp = case exp of
		ELetIn loc exp1 -> ELetIn (removePosition loc) (removePosition exp1)
		ELetRecIn loc exp1 -> ELetRecIn (removePosition loc) (removePosition exp1)
		ELambda args exp1 -> ELambda (removePosition args) (removePosition exp1)
		EIfThenElse exp1 exp2 exp3 -> EIfThenElse (removePosition exp1) (removePosition exp2) (removePosition exp3)
		EOr exp1 exp2 -> EOr (removePosition exp1) (removePosition exp2)
		EAnd exp1 exp2 -> EAnd (removePosition exp1) (removePosition exp2)
		ECmp exp1 cmp exp2 -> ECmp (removePosition exp1) cmp (removePosition exp2)
		EPrepend exp1 exp2 -> EPrepend (removePosition exp1) (removePosition exp2)
		EInfixWeak exp1 op exp2 -> EInfixWeak (removePosition exp1) op (removePosition exp2)
		EInfixStrong exp1 op exp2 -> EInfixStrong (removePosition exp1) op (removePosition exp2)
		EUnary op exp1 -> EUnary op (removePosition exp1)
		ENot exp1 -> ENot (removePosition exp1)
		EHead exp1 -> EHead (removePosition exp1)
		ETail exp1 -> ETail (removePosition exp1)
		EAppl exp1 exp2 -> EAppl (removePosition exp1) (removePosition exp2)
		EInt (OInteger ((_,_), str)) -> EInt $ OInteger ((0,0), str)
		EFloat (OFloat ((_,_), str)) -> EFloat $ OFloat ((0,0), str)
		EBool (OBool ((_,_), str)) -> EBool $ OBool ((0,0), str)
		EList elems -> EList (removePosition elems)
		EVar (OIdent ((_,_), str)) -> EVar $ OIdent ((0,0), str)
		EExplType exp1 explType -> EExplType (removePosition exp1) explType

instance RemoveablePosition t => RemoveablePosition [t] where
	removePosition = map removePosition

instance RemoveablePosition LocDecl where
	removePosition loc = case loc of
		LocalVarDecl (OIdent ((_,_), str)) exp ->
			LocalVarDecl (OIdent ((0,0), str)) (removePosition exp)
		LocalVarDeclExplType (OIdent ((_,_), str)) explType exp ->
			LocalVarDeclExplType (OIdent ((0,0), str)) explType (removePosition exp)

instance RemoveablePosition Argument where
	removePosition arg = case arg of
		FunArg (OIdent ((_,_), str)) ->
			FunArg (OIdent ((0,0), str))
		FunArgExplType (OIdent ((_,_), str)) explType ->
			FunArgExplType (OIdent ((0,0), str)) explType

instance RemoveablePosition ListElem where
	removePosition (ListElement exp) = ListElement $ removePosition exp

instance RemoveablePosition Value where
	removePosition val = case val of
		VFun fenv fargs fexp -> VFun (Map.map removePosition fenv) fargs (removePosition fexp)
		VList lelems -> VList $ removePosition lelems
		_ -> val