-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathModeller.fs
2140 lines (1976 loc) · 83.2 KB
/
Modeller.fs
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <summary>
/// The main part of the converter from Starling's language AST to
/// its internal representation.
/// </summary>
module Starling.Lang.Modeller
open Chessie.ErrorHandling
open Starling
open Starling.Collections
open Starling.Core
open Starling.Core.Definer
open Starling.Core.TypeSystem
open Starling.Core.Expr
open Starling.Core.Var
open Starling.Core.Var.Env
open Starling.Core.Var.VarMap
open Starling.Core.Symbolic
open Starling.Core.Model
open Starling.Core.View
open Starling.Core.Command
open Starling.Core.Command.Create
open Starling.Core.Instantiate
open Starling.Core.Traversal
open Starling.Lang.AST
open Starling.Lang.Collator
open Starling.Lang.ViewDesugar
/// <summary>
/// Types used only in the modeller and adjacent pipeline stages.
/// </summary>
[<AutoOpen>]
module Types =
/// A conditional (flat or if-then-else) func.
type CFunc =
| ITE of SVBoolExpr * CView * CView
| Func of SVFunc
override this.ToString() = sprintf "CFunc(%A)" this
/// A conditional view, or multiset of CFuncs.
and CView = Multiset<IteratedContainer<CFunc, Sym<Var> option>>
/// A partially resolved command.
type PartCmd<'view> =
| Prim of Starling.Core.Command.Types.Command
| While of
isDo : bool
* expr : SVBoolExpr
* inner : FullBlock<'view, PartCmd<'view>>
| ITE of
expr : SVBoolExpr
* inTrue : FullBlock<'view, PartCmd<'view>>
* inFalse : FullBlock<'view, PartCmd<'view>> option
override this.ToString() = sprintf "PartCmd(%A)" this
/// <summary>
/// Internal context for the method modeller.
/// </summary>
type MethodContext =
{ /// <summary>
/// The environment of visible variables.
/// </summary>
Env : Env
/// <summary>
/// A definer containing the visible view prototypes.
/// </summary>
ViewProtos : FuncDefiner<ProtoInfo> }
type ModellerViewExpr = ViewExpr<CView>
type ModellerPartCmd = PartCmd<ModellerViewExpr>
type ModellerBlock = FullBlock<ModellerViewExpr, PartCmd<ModellerViewExpr>>
/// <summary>
/// A type, or maybe just a string description of one.
/// </summary>
type FuzzyType =
/// <summary>A definite type.</summary>
| Exact of Type
/// <summary>A not so definite type.</summary>
| Fuzzy of string
/// <summary>
/// An error originating from the type system.
/// </summary>
type TypeError =
/// <summary>
/// Two items that should have been the same type were not.
/// We know the expected type completely.
/// </summary>
| TypeMismatch of expected : FuzzyType * got : FuzzyType
/// <summary>
/// A language type literal is inexpressible in Starling.
/// </summary>
| ImpossibleType of lit : TypeLiteral * why : string
// TODO(CaptainHayashi): more consistent constructor names
/// Represents an error when converting an expression.
type ExprError =
/// <summary>
/// The expression failed the type checker.
/// </summary>
| ExprBadType of err : TypeError
/// <summary>
/// A variable in the expression failed the type checker.
/// </summary>
| VarBadType of var : Var * err : TypeError
/// A variable usage in the expression produced a `VarMapError`.
| Var of var : Var * err : VarMapError
/// A substitution over the variable produced a `TraversalError`.
| BadSub of err : TraversalError<unit>
/// A symbolic expression appeared in an ambiguous position.
| AmbiguousSym of sym : Symbolic<Expression>
override this.ToString() = sprintf "%A" this
/// Represents an error when converting a view prototype.
type ViewProtoError =
/// A parameter name was used more than once in the same view prototype.
| VPEDuplicateParam of DesugaredViewProto * param : string
/// <summary>
/// A view prototype had parameters of incorrect type in it.
/// </summary>
| BadParamType of proto : ViewProto * par : Param * err : TypeError
/// Represents an error when converting a view or view def.
type ViewError =
/// An expression in the view generated an `ExprError`.
| BadExpr of expr : AST.Types.Expression * err : ExprError
/// A view was requested that does not exist.
| NoSuchView of name : string
/// A view lookup failed.
| LookupError of name : string * err : Core.Definer.Error
/// A view used variables in incorrect ways, eg by duplicating.
| BadVar of err : VarMapError
/// A viewdef conflicted with the shared variables.
| SVarConflict of err : VarMapError
override this.ToString () = sprintf "%A" this
/// Represents an error when converting a constraint.
type ConstraintError =
/// The view definition in the constraint generated a `ViewError`.
| CEView of vdef : AST.Types.ViewSignature * err : ViewError
/// The expression in the constraint generated an `ExprError`.
| CEExpr of expr : AST.Types.Expression * err : ExprError
/// Represents an error when converting a prim.
type PrimError =
/// <summary>
/// A prim needed a lvalue but got a non-lvalue expression.
/// </summary>
| NeedLValue of expr : AST.Types.Expression
/// A prim contained a bad expression.
| BadExpr of expr : AST.Types.Expression * err : ExprError
/// A prim tried to increment an expression.
| IncExpr of expr : AST.Types.Expression
/// A prim tried to decrement an expression.
| DecExpr of expr : AST.Types.Expression
/// A prim tried to increment a Boolean.
| IncBool of expr : AST.Types.Expression
/// A prim tried to decrement a Boolean.
| DecBool of expr : AST.Types.Expression
/// A prim tried to atomic-load from a non-lvalue expression.
| LoadNonLV of expr : AST.Types.Expression
/// A prim has no effect.
| Useless
/// <summary>A prim is not yet implemented in Starling.</summary>
| PrimNotImplemented of what : string
/// <summary>Handling variables in symbolic prims caused an error.</summary>
| SymVarError of err : VarMapError
/// <summary>An atomic branch contains a bad if-then-else condition.</summary>
| BadAtomicITECondition of expr: AST.Types.Expression * err: ExprError
/// Represents an error when converting a method.
type MethodError =
/// The method contains a semantically invalid local assign.
| BadAssign of dest : AST.Types.Expression
* src : AST.Types.Expression
* err : PrimError
/// The method contains a semantically invalid atomic action.
| BadAtomic of atom : Atomic * err : PrimError
/// The method contains a bad if-then-else condition.
| BadITECondition of expr: AST.Types.Expression * err: ExprError
/// The method contains a bad while condition.
| BadWhileCondition of expr: AST.Types.Expression * err: ExprError
/// The method contains a bad view.
| BadView of view : ViewExpr<AST.Types.View> * err : ViewError
/// The method contains an command not yet implemented in Starling.
| CommandNotImplemented of cmd : FullCommand
/// Represents an error when converting a model.
type ModelError =
/// A view prototype in the program generated a `ViewProtoError`.
| BadVProto of proto : DesugaredViewProto * err : ViewProtoError
/// A view prototype's parameter in the program generated a `TypeError`.
| BadVProtoParamType of proto : ViewProto * param : Param * err : TypeError
/// A constraint in the program generated a `ConstraintError`.
| BadConstraint of constr : AST.Types.ViewSignature * err : ConstraintError
/// A method in the program generated an `MethodError`.
| BadMethod of methname : string * err : MethodError
/// A variable in the program generated a `VarMapError`.
| BadVar of scope: string * err : VarMapError
/// A variable declaration in the program generated a `TypeError`.
| BadVarType of var: string * err : TypeError
/// <summary>
/// Pretty printers for the modeller types.
/// </summary>
module Pretty =
open Starling.Core.Pretty
open Starling.Collections.Multiset.Pretty
open Starling.Core.TypeSystem.Pretty
open Starling.Core.Var.Pretty
open Starling.Core.Model.Pretty
open Starling.Core.Expr.Pretty
open Starling.Core.Command.Pretty
open Starling.Core.Traversal.Pretty
open Starling.Core.Symbolic.Pretty
open Starling.Core.View.Pretty
open Starling.Lang.AST.Pretty
open Starling.Lang.ViewDesugar.Pretty
/// Pretty-prints a CFunc.
let rec printCFunc : CFunc -> Doc =
function
| CFunc.ITE(i, t, e) ->
hsep [ String "if"
printSVBoolExpr i
String "then"
t |> printCView |> ssurround "[" "]"
String "else"
e |> printCView |> ssurround "[" "]" ]
| Func v -> printSVFunc v
/// Pretty-prints a CView.
and printCView : CView -> Doc =
printMultiset
(printIteratedContainer printCFunc (maybe Nop (printSym printVar)))
>> ssurround "[|" "|]"
/// Pretty-prints a part-cmd at the given indent level.
let rec printPartCmd (pView : 'view -> Doc) (pc : PartCmd<'view>) : Doc =
let pfb = printFullBlock pView (printPartCmd pView)
match pc with
| PartCmd.Prim prim -> Command.Pretty.printCommand prim
| PartCmd.While(isDo, expr, inner) ->
cmdHeaded (hsep [ String(if isDo then "Do-while" else "While")
(printSVBoolExpr expr) ])
[ pfb inner ]
| PartCmd.ITE(expr, inTrue, inFalse) ->
cmdHeaded (hsep [ String "begin if"; printSVBoolExpr expr ])
[ headed "True" [ pfb inTrue ]
maybe Nop (fun f -> headed "False" [ pfb f]) inFalse ]
/// <summary>
/// Pretty-prints fuzzy type identifiers.
/// </summary>
/// <param name="ft">The fuzzy type to print.</param>
/// <returns>
/// A pretty-printer command that prints <paramref name="ft" />.
/// </returns>
let printFuzzyType (ft : FuzzyType) : Doc =
match ft with
| Fuzzy descr -> String descr
| Exact ty -> quoted (printType ty)
/// <summary>
/// Pretty-prints type errors.
/// </summary>
/// <param name="err">The error to print.</param>
/// <returns>
/// A pretty-printer command that prints <paramref name="err" />.
/// </returns>
let printTypeError (err : TypeError) : Doc =
match err with
| TypeMismatch (expected, got) ->
errorStr "expected"
<+> error (printFuzzyType expected)
<&> errorStr "got"
<+> error (printFuzzyType got)
| ImpossibleType (lit, why) ->
let header =
errorStr "type literal"
<+> quoted (printTypeLiteral lit)
<&> errorStr "cannot be expressed in Starling"
cmdHeaded header [ errorInfoStr why ]
/// <summary>
/// Pretty-prints expression conversion errors.
/// </summary>
/// <param name="err">The error to print.</param>
/// <returns>
/// A pretty-printer command that prints <paramref name="err" />.
/// </returns>
let printExprError (err : ExprError) : Doc =
match err with
| ExprBadType err ->
cmdHeaded (errorStr "type error in expression")
[ printTypeError err ]
| VarBadType (lv, err) ->
let header =
errorStr "type error in variable" <+> quoted (String lv)
cmdHeaded header [ printTypeError err ]
| Var(var, err) -> wrapped "variable" (var |> String) (err |> printVarMapError)
| BadSub err ->
fmt "Substitution error: {0}" [ printTraversalError (fun _ -> String "()") err ]
| AmbiguousSym sym ->
fmt
"symbolic var '{0}' has ambiguous type: \
place it inside an expression with non-symbolic components"
[ printSymbolic sym ]
/// Pretty-prints view conversion errors.
let printViewError : ViewError -> Doc =
function
| ViewError.BadExpr(expr, err) ->
wrapped "expression" (printExpression expr) (printExprError err)
| NoSuchView name -> fmt "no view prototype for '{0}'" [ String name ]
| LookupError(name, err) ->
wrapped "lookup for view"
(String name)
(Definer.Pretty.printError err)
| ViewError.BadVar err ->
colonSep [ "invalid variable usage" |> String
err |> printVarMapError ]
| SVarConflict err ->
colonSep [ "parameters conflict with shared variables" |> String
err |> printVarMapError ]
/// Pretty-prints constraint conversion errors.
let printConstraintError : ConstraintError -> Doc =
function
| CEView(vdef, err) ->
wrapped "view definition" (printViewSignature vdef) (printViewError err)
| CEExpr(expr, err) ->
wrapped "expression" (printExpression expr) (printExprError err)
/// Pretty-prints view prototype conversion errors
let printViewProtoError : ViewProtoError -> Doc =
function
| VPEDuplicateParam(vp, param) ->
fmt "view proto '{0}' has duplicate param {1}"
[ printGeneralViewProto printTypedVar vp; String param ]
| BadParamType (proto, par, err) ->
cmdHeaded
(errorStr "parameter"
<+> quoted (printParam par)
<+> errorStr "in view proto"
<+> quoted (printGeneralViewProto printParam proto)
<+> errorStr "has bad type")
[ printTypeError err ]
/// Pretty-prints prim errors.
let printPrimError (err : PrimError) : Doc =
match err with
| NeedLValue expr ->
errorStr "expected lvalue here, but got"
<+> quoted (printExpression expr)
| BadExpr (expr, err : ExprError) ->
wrapped "expression" (printExpression expr)
(printExprError err)
| IncExpr expr ->
fmt "cannot increment an expression ('{0}')"
[ printExpression expr ]
| DecExpr expr ->
fmt "cannot decrement an expression ('{0}')"
[ printExpression expr ]
| IncBool expr ->
fmt "cannot increment a Boolean ('{0}')"
[ printExpression expr ]
| DecBool expr ->
fmt "cannot decrement a Boolean ('{0}')"
[ printExpression expr ]
| LoadNonLV expr ->
fmt "cannot load from non-lvalue expression '{0}'"
[ printExpression expr ]
| Useless -> String "command has no effect"
| PrimNotImplemented what ->
errorStr "primitive command"
<+> quoted (String what)
<+> errorStr "not yet implemented"
| SymVarError err ->
errorStr "error in translating symbolic command"
<&> printVarMapError err
| BadAtomicITECondition (expr, err) ->
wrapped "if-then-else condition" (printExpression expr)
(printExprError err)
/// Pretty-prints method errors.
let printMethodError (err : MethodError) : Doc =
match err with
| BadAssign (dest, src, err) ->
wrapped "local assign" (printAssign dest src) (printPrimError err)
| BadAtomic (atom, err) ->
wrapped "atomic action" (printAtomic atom) (printPrimError err)
| BadITECondition (expr, err) ->
wrapped "if-then-else condition" (printExpression expr)
(printExprError err)
| BadWhileCondition (expr, err) ->
wrapped "while-loop condition" (printExpression expr)
(printExprError err)
| BadView (view, err) ->
wrapped "view expression" (printViewExpr printView view)
(printViewError err)
| CommandNotImplemented cmd ->
fmt "command {0} not yet implemented" [ printFullCommand cmd ]
/// Pretty-prints model conversion errors.
let printModelError (err : ModelError) : Doc =
match err with
| BadConstraint(constr, err) ->
wrapped "constraint" (printViewSignature constr)
(printConstraintError err)
| BadVar(scope, err) ->
wrapped "variables in scope" (String scope) (printVarMapError err)
| BadMethod(methname, err) ->
wrapped "method" (String methname) (printMethodError err)
| BadVProto(vproto, err) ->
wrapped "view prototype" (printGeneralViewProto printTypedVar vproto)
(printViewProtoError err)
| BadVProtoParamType(vproto, param, err) ->
let head =
errorStr "type of param"
<+> quoted (printParam param)
<+> errorStr "in view prototype"
<+> quoted (printGeneralViewProto printParam vproto)
cmdHeaded head [ printTypeError err ]
| BadVarType(name, err) ->
wrapped "type of variable" (String name) (printTypeError err)
(*
* Starling imperative language semantics
*)
/// Creates a prim from a name, results list, and arguments list.
let mkPrim (name : string) (results : TypedVar list) (args : TypedVar list)
(body : Microcode<TypedVar, Var> list)
: PrimSemantics =
{ Name = name; Results = results; Args = args; Body = body }
/// <summary>
/// The core semantic function for the imperative language.
/// </summary>
/// <remarks>
/// <para>
/// The functions beginning with '!' have special syntax in the
/// imperative language.
/// </para>
/// </remarks>
let coreSemantics : PrimSemanticsMap =
// TODO(CaptainHayashi): specify this in the language (standard library?).
// TODO(CaptainHayashi): generic functions?
// TODO(CaptainHayashi): add shared/local/expr qualifiers to parameters?
List.fold (fun m (a : PrimSemantics) -> Map.add a.Name a m) Map.empty
<| [
(*
* CAS
*)
(mkPrim "ICAS" [ normalIntVar "destA"; normalIntVar "testA" ] [ normalIntVar "destB"; normalIntVar "testB"; normalIntVar "set" ]
[ Branch
(iEq (IVar "destB") (IVar "testB"),
[ normalIntVar "destA" *<- normalIntExpr (IVar "set")
normalIntVar "testA" *<- normalIntExpr (IVar "testB") ],
[ normalIntVar "destA" *<- normalIntExpr (IVar "destB")
normalIntVar "testA" *<- normalIntExpr (IVar "destB") ] ) ] )
// Boolean CAS
(mkPrim "BCAS" [ normalBoolVar "destA"; normalBoolVar "testA" ] [ normalBoolVar "destB"; normalBoolVar "testB"; normalBoolVar "set" ]
[ Branch
(bEq (BVar "destB") (BVar "testB"),
[ normalBoolVar "destA" *<- normalBoolExpr (BVar "set")
normalBoolVar "testA" *<- normalBoolExpr (BVar "testB") ],
[ normalBoolVar "destA" *<- normalBoolExpr (BVar "destB")
normalBoolVar "testA" *<- normalBoolExpr (BVar "destB") ] ) ] )
(*
* Atomic load
*)
// Integer load
(mkPrim "!ILoad" [ normalIntVar "dest" ] [ normalIntVar "src" ]
[ normalIntVar "dest" *<- normalIntExpr (IVar "src") ] )
// Integer load-and-increment
(mkPrim "!ILoad++" [ normalIntVar "dest"; normalIntVar "srcA" ] [ normalIntVar "srcB" ]
[ normalIntVar "dest" *<- normalIntExpr (IVar "srcB")
normalIntVar "srcA" *<- normalIntExpr (mkAdd2 (IVar "srcB") (IInt 1L)) ] )
// Integer load-and-decrement
(mkPrim "!ILoad--" [ normalIntVar "dest"; normalIntVar "srcA" ] [ normalIntVar "srcB" ]
[ normalIntVar "dest" *<- normalIntExpr (IVar "srcB")
normalIntVar "srcA" *<- normalIntExpr (mkSub2 (IVar "srcB") (IInt 1L)) ] )
// Integer increment
(mkPrim "!I++" [ normalIntVar "srcA" ] [ normalIntVar "srcB" ]
[ normalIntVar "srcA" *<- normalIntExpr (mkAdd2 (IVar "srcB") (IInt 1L)) ] )
// Integer decrement
(mkPrim "!I--" [ normalIntVar "srcA" ] [ normalIntVar "srcB" ]
[ normalIntVar "srcA" *<- normalIntExpr (mkSub2 (IVar "srcB") (IInt 1L)) ] )
// Boolean load
(mkPrim "!BLoad" [ normalBoolVar "dest" ] [ normalBoolVar "src" ]
[ normalBoolVar "dest" *<- normalBoolExpr (BVar "src") ] )
(*
* Atomic store
*)
// Integer store
(mkPrim "!IStore" [ normalIntVar "dest" ] [ normalIntVar "src" ]
[ normalIntVar "dest" *<- normalIntExpr (IVar "src") ] )
// Boolean store
(mkPrim "!BStore" [ normalBoolVar "dest" ] [ normalBoolVar "src" ]
[ normalBoolVar "dest" *<- normalBoolExpr (BVar "src") ] )
(*
* Local set
*)
// Integer local set
(mkPrim "!ILSet" [ normalIntVar "dest" ] [ normalIntVar "src" ]
[ normalIntVar "dest" *<- normalIntExpr (IVar "src") ] )
// Boolean store
(mkPrim "!BLSet" [ normalBoolVar "dest" ] [ normalBoolVar "src" ]
[ normalBoolVar "dest" *<- normalBoolExpr (BVar "src") ] )
(*
* Assumptions
*)
// Identity
(mkPrim "Id" [] [] [])
// Assume
(mkPrim "Assume" [] [normalBoolVar "expr"] [ Microcode.Assume (BVar "expr") ]) ]
(*
* Expression translation
*)
/// <summary>
/// Constructs an expression-level type mismatch error.
/// </summary>
/// <param name="expected">The expected type of the expression.</param>
/// <param name="got">The actual type of the expression.</param>
/// <returns>An <see cref="ExprError"/> representing a type mismatch.</returns>
let exprTypeMismatch (expected : FuzzyType) (got : FuzzyType) : ExprError =
ExprBadType (TypeMismatch (expected = expected, got = got))
/// <summary>
/// Constructs a primitive-level expression type mismatch error.
/// </summary>
/// <param name="expr">The AST of the expression being modelled.</param>
/// <param name="expected">The expected type of the expression.</param>
/// <param name="got">The actual type of the expression.</param>
/// <returns>An <see cref="PrimError"/> representing a type mismatch.</returns>
let primTypeMismatch
(expr : Expression) (expected : FuzzyType) (got : FuzzyType) : PrimError =
BadExpr (expr, exprTypeMismatch expected got)
// <summary>
// Given a subtyped integer expression, check whether it can be used as a
// 'normal'-typed integer expression.
//
// <para>
// This is used whenever integer expressions need to be used as
// indices to arrays.
// </para>
// </summary>
// <param name="int">The integer to check for type compatibility.</param>
// <typeparam name="Var">The type of variables in the expression.</typeparm>
// <returns>
// If the expression is compatible with 'int', the modelled expression.
// Else, a type error.
// </returns>
let checkIntIsNormalType (int : TypedIntExpr<'Var>)
: Result<IntExpr<'Var>, TypeError> =
if primTypeRecsCompatible int.SRec normalRec
then ok int.SExpr
else
fail
(TypeMismatch
(expected = Exact (Typed.Int (normalRec, ())),
got = Exact (Typed.Int (int.SRec, ()))))
// <summary>
// Given a subtyped Boolean expression, check whether it can be used as a
// 'normal'-typed Boolean expression.
//
// <para>
// This is used whenever Boolean expressions need to be used as
// predicates, ie as view conditions or view definitions.
// </para>
// </summary>
// <param name="bool">The Boolean to check for type compatibility.</param>
// <typeparam name="Var">The type of variables in the expression.</typeparm>
// <returns>
// If the expression is compatible with 'bool', the modelled expression.
// Else, a type error.
// </returns>
let checkBoolIsNormalType (bool : TypedBoolExpr<'Var>)
: Result<BoolExpr<'Var>, TypeError> =
if primTypeRecsCompatible bool.SRec normalRec
then ok bool.SExpr
else
fail
(TypeMismatch
(expected = Exact (Typed.Bool (normalRec, ())),
got = Exact (Typed.Bool (bool.SRec, ()))))
/// <summary>
/// Models a Starling expression as an <c>Expr</c>.
///
/// <para>
/// Whenever we find a variable, we check the given environment
/// to make sure it both exists and is being used in a type-safe
/// manner. Thus, this part of the modeller implements much of
/// Starling's type checking.
/// </para>
/// <para>
/// Since <c>modelExpr</c> and its Boolean and integral
/// equivalents are used to create expressions over both
/// <c>Var</c> and <c>MarkedVar</c>, we allow variable lookups
/// to be modified by a post-processing function.
/// </para>
/// </summary>
/// <param name="env">The <see cref="Env"/> of variables in the program.</param>
/// <param name="scope">
/// The level of variable scope at which this expression occurs.
/// </param>
/// <param name="varF">
/// A function to transform any variables after they are looked-up,
/// but before they are placed in the modelled expression. Use this
/// to apply markers on variables, etc.
/// </param>
/// <param name="idxEnv">
/// The <c>VarMap</c> of variables available to any array subscripts in this
/// expression. This is almost always the thread-local variables.
/// </param>
/// <typeparam name="var">
/// The type of variables in the <c>Expr</c>, achieved by
/// applying <paramref name="varF"/> to <c>Var</c>s.
/// </typeparam>
/// <returns>
/// A function taking <c>Expression</c>s. This function will return
/// a <c>Result</c>, over <c>ExprError</c>, containing the modelled
/// <c>Expr</c> on success. The exact type parameters of the
/// expression depend on <paramref name="varF"/>.
/// </returns>
let rec modelExpr
(env : Env)
(scope : Scope)
(varF : Var -> 'var)
(e : Expression)
: Result<Expr<Sym<'var>>, ExprError> =
match e.Node with
(* First, if we have a variable, the type of expression is
determined by the type of the variable. If the variable is
symbolic, then we have ambiguity. *)
| Identifier v ->
bind
(liftWithoutContext
(varF >> Reg >> ok)
(tliftOverCTyped >> tliftToExprDest)
>> mapMessages BadSub)
(wrapMessages Var (Env.lookup env scope) v)
| Symbolic sym ->
fail (AmbiguousSym sym)
(* If we have an array, then work out what the type of the array's
elements are, then walk back from there. *)
| ArraySubscript (arr, idx) ->
let arrR = modelArrayExpr env scope varF arr
// Indices always have to be of type 'int', and be in local scope.
let idxuR = modelIntExpr env (indexScopeOf scope) varF idx
let idxR = bind (checkIntIsNormalType >> mapMessages ExprBadType) idxuR
lift2
(fun arrE idxE ->
match arrE.SRec.ElementType with
| AnIntR r -> Expr.Int (r, IIdx (arrE, idxE))
| ABoolR r -> Expr.Bool (r, BIdx (arrE, idxE))
| AnArrayR r -> Expr.Array (r, AIdx (arrE, idxE)))
arrR idxR
(* We can use the active patterns above to figure out whether we
* need to treat this expression as arithmetic or Boolean.
*)
| ArithExp' _ -> lift (liftTypedSub Expr.Int) (modelIntExpr env scope varF e)
| BoolExp' _ -> lift (liftTypedSub Expr.Bool) (modelBoolExpr env scope varF e)
| _ -> failwith "unreachable[modelExpr]"
/// <summary>
/// Models a Starling Boolean expression as a <c>BoolExpr</c>.
///
/// <para>
/// See <c>modelExpr</c> for more information.
/// </para>
/// </summary>
/// <param name="env">The <see cref="Env"/> of variables in the program.</param>
/// <param name="scope">
/// The level of variable scope at which this expression occurs.
/// </param>
/// <param name="varF">
/// A function to transform any variables after they are looked-up,
/// but before they are placed in <c>IVar</c>. Use this to apply
/// markers on variables, etc.
/// </param>
/// <param name="expr">
/// An expression previously judged as Boolean, to be modelled.
/// </param>
/// <param name="idxEnv">
/// The <c>VarMap</c> of variables available to any array subscripts in this
/// expression. This is almost always the thread-local variables.
/// </param>
/// <typeparam name="var">
/// The type of variables in the <c>BoolExpr</c>, achieved by
/// applying <paramref name="varF"/> to <c>Var</c>s.
/// </typeparam>
/// <returns>
/// A <c>Result</c>, over <c>ExprError</c>, containing the modelled
/// <c>BoolExpr</c> on success.
/// The exact type parameters of the expression depend on
/// <paramref name="varF"/>.
/// </returns>
and modelBoolExpr
(env : Env)
(scope : Scope)
(varF : Var -> 'var)
(expr : Expression) : Result<TypedBoolExpr<Sym<'var>>, ExprError> =
let mi = modelIntExpr env scope varF
let me = modelExpr env scope varF
let ma = modelArrayExpr env scope varF
let rec mb e : Result<TypedBoolExpr<Sym<'var>>, ExprError> =
match e.Node with
// These two have a indefinite subtype.
| True -> ok (indefBool BTrue)
| False -> ok (indefBool BFalse)
| Identifier v ->
(* Look-up the variable to ensure it a) exists and b) is of a
* Boolean type.
*)
bind
(function
| Typed.Bool (t, vn) ->
ok (mkTypedSub t (BVar (Reg (varF vn))))
| vr ->
fail
(VarBadType
(v,
TypeMismatch
(expected = Fuzzy "bool", got = Exact (typeOf vr)))))
(wrapMessages Var (Env.lookup env scope) v)
| Symbolic sa ->
(* Symbols have an indefinite subtype, and can include thread-local
scope. *)
lift
(fun a -> indefBool (BVar (Sym a)))
(tryMapSym (modelExpr env (symbolicScopeOf scope) varF) sa)
| ArraySubscript (arr, idx) ->
let arrR = ma arr
// Indices always have to be of type 'int', and in local scope.
let idxuR = modelIntExpr env (indexScopeOf scope) varF idx
let idxR = bind (checkIntIsNormalType >> mapMessages ExprBadType) idxuR
bind2
(fun arrE idxE ->
match arrE.SRec.ElementType with
| ABoolR r -> ok (mkTypedSub r (BIdx (arrE, idxE)))
| t -> fail (exprTypeMismatch (Fuzzy "bool[]") (Exact t)))
arrR idxR
| BopExpr(BoolOp as op, l, r) ->
match op with
| ArithIn as o ->
let oper =
match o with
| Gt -> mkGt
| Ge -> mkGe
| Le -> mkLe
| Lt -> mkLt
| _ -> failwith "unreachable[modelBoolExpr::ArithIn]"
// We don't know the subtype of this yet...
lift indefBool (lift2 oper (mi l) (mi r))
| BoolIn as o ->
let oper =
match o with
| And -> mkAnd2
| Or -> mkOr2
| Imp -> mkImplies
| _ -> failwith "unreachable[modelBoolExpr::BoolIn]"
(* Both sides of the expression need to be unifiable to the
same type. *)
bind2
(fun ml mr ->
match unifyPrimTypeRecs [ ml.SRec; mr.SRec ] with
| Some t ->
ok (mkTypedSub t (oper (stripTypeRec ml) (stripTypeRec mr)))
| None ->
fail
(ExprBadType
(TypeMismatch
(expected = Exact (Type.Bool (ml.SRec, ())),
got = Exact (Type.Bool (mr.SRec, ()))))))
(mb l)
(mb r)
| AnyIn as o ->
let oper =
match o with
| Eq -> mkEq
| Neq -> mkNeq
| _ -> failwith "unreachable[modelBoolExpr::AnyIn]"
(* If at least one of the operands is a symbol, we need to
try infer its type from the other operand. Simply modelling
both expressions will result in an ambiguity error. *)
let modelExprWithType template e =
match template with
| Int _ -> lift (liftTypedSub Int) (mi e)
| Bool _ -> lift (liftTypedSub Bool) (mb e)
| Array _ -> lift (liftTypedSub Array) (ma e)
let lR, rR =
match (l.Node, r.Node) with
| Symbolic _, _ ->
let rR = me r
let lR = bind (fun r -> modelExprWithType r l) rR
(lR, rR)
| _, Symbolic _ ->
let lR = me l
let rR = bind (fun l -> modelExprWithType l r) lR
(lR, rR)
| _ -> (me l, me r)
// We don't know the subtype of this yet...
lift indefBool (lift2 oper lR rR)
| UopExpr (Neg,e) -> lift (mapTypedSub mkNot) (mb e)
| _ ->
fail
(ExprBadType
(TypeMismatch (expected = Fuzzy "bool", got = Fuzzy "unknown non-bool")))
mb expr
/// <summary>
/// Models a Starling integral expression as an <c>IntExpr</c>.
///
/// <para>
/// See <c>modelExpr</c> for more information.
/// </para>
/// </summary>
/// <param name="env">The <see cref="Env"/> of variables in the program.</param>
/// <param name="scope">
/// The level of variable scope at which this expression occurs.
/// </param>
/// <param name="varF">
/// A function to transform any variables after they are looked-up,
/// but before they are placed in <c>IVar</c>. Use this to apply
/// markers on variables, etc.
/// </param>
/// <param name="expr">
/// An expression previously judged as integral, to be modelled.
/// </param>
/// <typeparam name="var">
/// The type of variables in the <c>IntExpr</c>, achieved by
/// applying <paramref name="varF"/> to <c>Var</c>s.
/// </typeparam>
/// <returns>
/// A <c>Result</c>, over <c>ExprError</c>, containing the modelled
/// <c>IntExpr</c> on success.
/// The exact type parameters of the expression depend on
/// <paramref name="varF"/>.
/// </returns>
and modelIntExpr
(env : Env)
(scope : Scope)
(varF : Var -> 'var)
(expr : Expression) : Result<TypedIntExpr<Sym<'var>>, ExprError> =
let me = modelExpr env scope varF
let ma = modelArrayExpr env scope varF
let rec mi e =
match e.Node with
// Numbers have indefinite subtype.
| Num i -> ok (indefInt (IInt i))
| Identifier v ->
(* Look-up the variable to ensure it a) exists and b) is of an
* arithmetic type.
*)
v
|> wrapMessages Var (Env.lookup env scope)
|> bind (function
| Typed.Int (ty, vn) ->
ok (mkTypedSub ty (IVar (Reg (varF vn))))
| vr ->
fail
(VarBadType
(v,
TypeMismatch
(expected = Fuzzy "int", got = Exact (typeOf vr)))))
| Symbolic sa ->
// Symbols have indefinite subtype.
lift
(fun a -> indefInt (IVar (Sym a)))
(tryMapSym (modelExpr env (symbolicScopeOf scope) varF) sa)
| ArraySubscript (arr, idx) ->
let arrR = ma arr
// Indices always have to be of type 'int' and local scope.
let idxuR = modelIntExpr env (indexScopeOf scope) varF idx
let idxR = bind (checkIntIsNormalType >> mapMessages ExprBadType) idxuR
bind2
(fun arrE idxE ->
match arrE.SRec.ElementType with
| AnIntR ty -> ok (mkTypedSub ty (IIdx (arrE, idxE)))
| t -> fail (exprTypeMismatch (Fuzzy "int[]") (Exact (typeOf (liftTypedSub Array arrE)))))
arrR idxR
| BopExpr(ArithOp as op, l, r) ->
let oper =
match op with
| Mul -> mkMul2
| Mod -> mkMod
| Div -> mkDiv
| Add -> mkAdd2
| Sub -> mkSub2
| _ -> failwith "unreachable[modelIntExpr]"
bind2
(fun ll lr ->
(* We need to make sure that 'll' 'lr' have compatible inner
type by unifying their extended type records. *)
match unifyPrimTypeRecs [ ll.SRec; lr.SRec ] with
| Some srec ->
ok (mkTypedSub srec (oper (stripTypeRec ll) (stripTypeRec lr)))
| None ->
fail
(ExprBadType
(TypeMismatch
(expected = Exact (typeOf (liftTypedSub Int ll)),
got = Exact (typeOf (liftTypedSub Int lr))))))
(mi l) (mi r)
| _ -> fail (exprTypeMismatch (Fuzzy "int") (Fuzzy "unknown non-int"))
mi expr
/// <summary>
/// Models a Starling array expression as an <c>ArrayExpr</c>.
///
/// <para>
/// See <c>modelExpr</c> for more information.
/// </para>
/// </summary>
/// <param name="env">The <see cref="Env"/> of variables in the program.</param>
/// <param name="scope">
/// The level of variable scope at which this expression occurs.
/// </param>
/// <param name="varF">
/// A function to transform any variables after they are looked-up,
/// but before they are placed in <c>AVar</c>. Use this to apply
/// markers on variables, etc.
/// </param>
/// <param name="expr">
/// An expression previously judged as integral, to be modelled.
/// </param>
/// <typeparam name="var">
/// The type of variables in the <c>ArrayExpr</c>, achieved by
/// applying <paramref name="varF"/> to <c>Var</c>s.
/// </typeparam>
/// <returns>
/// A <c>Result</c>, over <c>ExprError</c>, containing the modelled
/// <c>ArrayExpr</c> on success.
/// The exact type parameters of the expression depend on
/// <paramref name="varF"/>.
/// </returns>
and modelArrayExpr
(env : Env)
(scope : Scope)
(varF : Var -> 'var)
(expr : Expression)
: Result<TypedArrayExpr<Sym<'var>>, ExprError> =
let mi = modelIntExpr env scope varF
let rec ma e =
match e.Node with
| Identifier v ->
(* Look-up the variable to ensure it a) exists and b) is of an
* array type.
*)
v
|> wrapMessages Var (Env.lookup env scope)
|> bind (function
| Typed.Array (t, vn) ->
ok (mkTypedSub t (AVar (Reg (varF vn))))
| vr ->
fail
(VarBadType
(v,
TypeMismatch
(expected = Fuzzy "array", got = Exact (typeOf vr)))))
| Symbolic sym ->
(* TODO(CaptainHayashi): a symbolic array is ambiguously typed.
Maybe when modelling we should take our 'best guess' at
eltype and length from any subscripting expression? *)