love studio / LoveStudio / LuaAnalyzer / Typechecker.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
module LuaAnalyzer.TypeChecker

open Syntax
open System.IO
open System.Windows.Forms
open System.Diagnostics.Contracts

open System.Diagnostics.Contracts
open Type
open TypedSyntax
open ErrorList
open Context
open TypeCollector
open SubtypeGraphBuilder

type GenList<'T> = System.Collections.Generic.List<'T>

/// This holds a context intentionally extracted from a certain location in 
/// the program. For example, whenever the use makes an intellisense query,
/// we extract the context wherever the caret is at.
let refStubContext : Ref<Context> = ref Context.empty

/// This holds a comment description of some program term which was 
/// queried by the user (i.e. the description component of a field or method)
let refStubDesc : Ref<string> = ref ""

/// Holds the type of some program term which was queried by the user
let refStubTy : Ref<Type> = ref NilTy

/// This holds the definition location of some program term which was
/// queried by the user (i.e. the location component of a field or method)
let refStubDefLoc : Ref<DefinitionLocation> = ref NoLocation

let currentFileName : Ref<string> = ref ("")

let refTypeCheckStat : Ref<Context -> TypedStatement -> unit> = ref( fun _ _ -> () )

/// Traverses a statement in order to generate typechecking errors or
/// query for information about a program element or the context at some point 
/// in the program.
let typeCheckStat (ctxt : Context) (stat : TypedStatement) =
    (!refTypeCheckStat) ctxt stat

let refTypeCheckExpr : Ref<Context -> TypedExpr -> Type*Option<Field>> = ref( fun _ _ -> UnknownTy,None )

/// Traverses an expression in order to generate typechecking errors or
/// query for information about a program element or the context at some point
/// in the program.
///
/// Returns a pair (ty,field), where ty is the type of the given expression
/// (or UnknownTy for non-well-typed expressions), and if the expression happens
/// to be a field lookup, field contains the field being looked up.
let typeCheckExpr (ctxt : Context) (expr : TypedExpr) =
    (!refTypeCheckExpr) ctxt expr

/// Takes a type environment, context, l-expression, and target type, 
/// If the target type is a subtype of the l-expression's type and the l-expression
/// is a name chain (see NameChain active pattern), returns a name/type
/// pair which represents a modification to the context containing
/// the extra knowledge gained about the l-expression after we have assigned
/// it to an expression having targetType.
///
/// The following assignment under the given context:
/// Context [self : { x : ?number }]
/// self.x = 3
///
/// would yield ("self", RecordTy(",",",fields.Add(x,NumberTy),"))
/// where " represents an unchanged value from self's old type.
let contextRefinement (ctxt : Context) 
                      (lexp : TypedExpr) 
                      (targetType : Type) 
                      (targetDesc : string)
                      (targetConst : bool)
                      : Option<string*Field> =

    let tenv,venv = ctxt.tenv, ctxt.venv
    let isOpenRecord (ty : Type) =
        match ty with
        | OpenRecordTy(_,_,_,_,_,_,_) ->
            true
        | _ ->
            false
    let getFieldMap (ty : Type) =
        match ty with
        | OpenRecordTy(_,_,_,_,fields,_,_) ->
            fields
        | _ ->
            failwith ""

    match lexp with
    | NameChain([opRecName; keyName]) when 
      ctxt.venv.ContainsKey opRecName && 
      isOpenRecord (venv.Item opRecName).ty &&
      not ((getFieldMap (venv.Item opRecName).ty).ContainsKey keyName) ->
        let opRecVar = venv.Item opRecName
        match Type.Coerce tenv opRecVar.ty with
        | OpenRecordTy(name,desc,srcExp,metamethods,fieldMap,methodMap,loc) ->
            let refinedFieldMap = fieldMap.Add(keyName,{Field.OfType(targetType) with desc = targetDesc; isConst = targetConst })
            let refinedTy = OpenRecordTy(name,desc,srcExp,metamethods,refinedFieldMap,methodMap,loc) 
            Some (opRecName,{opRecVar with ty = refinedTy })
        | _ ->
            failwith ""
    | NameChain(head :: rest) when not rest.IsEmpty ->
        match venv.TryFind head with
        | Some varField ->
            let scanName ((_,field) : string*Field) (name : string) =
                match Type.Coerce ctxt.tenv field.ty with
                | RecordTy(_,_,_,_,fields,_,_) ->
                    match fields.TryFind name with
                    | Some field ->
                        (name, field)
                    | None ->
                        (name, Field.OfType(NilTy))
                /// TODO: this is an awkward way to handle open records
                /// they should be handled separately
                | OpenRecordTy(_,_,_,_,fields,_,_)  ->
                    match fields.TryFind name with
                    | Some subField  ->
                        (name, subField)
                    | None ->
                        (name, { Field.OfType(targetType) with desc = targetDesc })                    
                | _ ->
                    (name, Field.OfType(NilTy))

            let types = List.scan scanName (head,varField) rest
            let types = List.rev types
            let finalKey,finalField = types.Head
            
            let finalField =
                match finalField with
                | { desc = _; ty = DeducedTy(perm,_); loc = _ } ->
                    { finalField with ty = perm }
                | _ ->
                    finalField

            if fst (Type.IsSubtypeOf tenv targetType finalField.ty) then
                let foldField (acc : string*Field) (item : string*Field) =
                    let key,accField = acc
                    let name,oldField = item

                    match oldField.ty with
                    | NillableTy( (RecordTy(a,b,c,d,fields,e,f)) ) when fields.ContainsKey key ->
                        name, {oldField with ty = NillableTy(RecordTy(a,b,c,d,fields.Add(key,accField),e,f)) }
                    | DeducedTy(perm, RecordTy(a,b,c,d,fields,e,f)) when fields.ContainsKey key ->
                        name, {oldField with ty = DeducedTy(perm, RecordTy(a,b,c,d,fields,e,f))}
                    | RecordTy(a,b,c,d,fields,e,f) when fields.ContainsKey key ->
                        name, {oldField with ty=RecordTy(a,b,c,d,fields.Add(key,accField),e,f)}
                    | NillableTy( (OpenRecordTy(a,b,c,d,fields,e,f)) ) ->
                        name, {oldField with ty = NillableTy(OpenRecordTy(a,b,c,d,fields.Add(key,accField),e,f)) }
                    | DeducedTy(perm, OpenRecordTy(a,b,c,d,fields,e,f)) ->
                        name, {oldField with ty = DeducedTy(perm, OpenRecordTy(a,b,c,d,fields,e,f))}
                    | OpenRecordTy(a,b,c,d,fields,e,f) ->
                        name, {oldField with ty=OpenRecordTy(a,b,c,d,fields.Add(key,accField),e,f)}
                    | _ ->
                        name, {oldField with ty=UnknownTy}
                
                let deducedTy = Type.MakeDeducedTy finalField.ty targetType
                let ret = List.fold foldField (finalKey,{finalField with ty=deducedTy}) types.Tail
                Some ret
            else
                None
        | None ->
            None
    | NameExpr(var, rng) ->
        match venv.TryFind var with
        | Some varField ->
            if fst (Type.IsSubtypeOf tenv targetType varField.ty) then
                let deducedTy = Type.MakeDeducedTy varField.ty targetType
                Some (var, {varField with ty = deducedTy})
            else
                None
        | None ->
            if ctxt.addGlobals then
                //TODO: add correct location
                Some(var, { Field.OfType(targetType) with isConst = targetConst; desc= targetDesc })
            else
                None
    | _ ->
        None


/// Given a context and condition expression, returns the
/// supplied context updated with inferences that can be made from the fact that
/// the condition expression evaluates to true under the given context.
///
/// For example, if our condition expression is "x ~= nil" and x has a nillable
/// number type under the given context, then refineContextFromCond returns the 
/// supplied context with x's type updated to number. 
let rec refineContextFromCond (ctxt : Context) (cond : TypedExpr) : Context =
    let venv, tenv = ctxt.venv, ctxt.tenv
    match cond with
    | BinOpExpr(OpNe, exp, Nil(_),_)
    | BinOpExpr(OpNe, Nil(_), exp, _) ->
        let expTy,expField = typeCheckExpr ctxt.DontTrackErrors.IsNotLeftExpr exp
        match expTy with
        | NillableTy(underlyingTy) ->
            let desc = if expField.IsSome then expField.Value.desc else ""
            let isConst = if expField.IsSome then expField.Value.isConst else false
            let refinement = contextRefinement ctxt exp underlyingTy desc isConst
        
            if refinement.IsSome then
                let var,varField = refinement.Value
                ctxt.AddValue(var,varField)
            else
                ctxt
        | _ ->
            ctxt
    | BinOpExpr(OpEq, expA, expB,_) ->
        let tyA,fieldA = typeCheckExpr ctxt.DontTrackErrors.IsNotLeftExpr expA
        let tyB,fieldB = typeCheckExpr ctxt.DontTrackErrors.IsNotLeftExpr expB
        let rA = contextRefinement ctxt expA tyB "" false
        let rB = contextRefinement ctxt expB tyA "" false

        if rA.IsSome then
            ctxt.AddValue(fst rA.Value, snd rA.Value)
        elif rB.IsSome then
            ctxt.AddValue(fst rB.Value, snd rB.Value)
        else
            ctxt
    | BinOpExpr(OpAnd, a, b,_) ->
        let ctxt' = refineContextFromCond ctxt a
        refineContextFromCond ctxt' b
    | BinOpExpr(OpOr, a, b, _) ->
        //TODO: too lazy to implement this now; it will be semi-tricky
        ctxt
    | _ ->
        ctxt

let refGetAllRefinements = ref (fun ctxt locals stat -> Map.empty)

let getAllRefinements (ctxt : Context) (locals : Set<string>) (stat : TypedStatement) : Map<string,Field> =
    (!refGetAllRefinements) ctxt locals stat
    
/// Given a context and statement, return a modified version 
/// of the context, containing any new variable bindings or refinements made 
/// by the statement.
let rec updateCtxt (ctxt : Context) (stat : TypedStatement) =
    let venv, tenv = ctxt.venv, ctxt.tenv

    let undoRefinement (ctxt : Context) (name : string) (_ : Field) =
        if venv.ContainsKey name then
            let field = venv.Item name
            ctxt.AddValue(name, {field with ty=Type.UndoDeductions field.ty})
        else 
            ctxt

    match stat with
    | If(clauses,rng) ->
        // For each variable that is refined in any of the clauses, we 
        // conservatively undo the refinement on that variable. For example,
        // a nillable number variable that is refined to number in the context
        // could be assigned to nil in some clause, in which case the refinement
        // must be removed.
        let clauseRefinements = List.map (getAllRefinements ctxt Set.empty) (List.map snd clauses)
        let refinements = List.fold cover Map.empty clauseRefinements
        Map.fold undoRefinement ctxt refinements
    | Sequence(s0, s1, rng) ->
        let ctxt = updateCtxt ctxt s0
        updateCtxt ctxt s1
    | LocalAssign(annotation,lhs,rhs,rng) ->
        let ldescs,lascripts,isConstList = Type.InterpretVarAnnotation annotation lhs.Length 
        let rctxt = ctxt.DontTrackErrors.IsNotLeftExpr
        let rtypes = List.map (fun expr -> fst (typeCheckExpr rctxt expr)) rhs
        let frtypes = List.collect Type.Flatten rtypes
        let frtypes = coverListOpt frtypes lascripts
        let frtypes = sizeListTo frtypes lhs.Length NilTy

        let foldItem (c : Context) (i : int) =
            let lexp = lhs.[i]
            let ldesc = ldescs.[i]
            let ty = frtypes.[i]

            let (NameExpr(name,rng)) = lexp
            let field = {
                Field.OfType(ty) with
                    desc = ldesc
                    loc = (!currentFileName,rng)
                    isConst = isConstList.[i]
            }
            c.AddValue(name,field)

        List.fold foldItem ctxt [0..lhs.Length-1] 

    | Assign(annotation,lhs,rhs,rng) ->
        let descs,ascriptions,isConstList = Type.InterpretVarAnnotation annotation lhs.Length
        let rctxt = ctxt.DontTrackErrors.IsNotLeftExpr
        let rtypes = List.map (fun expr -> fst (typeCheckExpr rctxt expr)) rhs
        let frtypes = List.collect Type.Flatten rtypes
        let frtypes = coverListOpt frtypes ascriptions
        let frtypes = sizeListTo frtypes lhs.Length NilTy 
        let pairs = List.zip lhs frtypes

        let foldItem (accCtxt : Context) (i : int)  =
            let expr, ty, desc,isConst = lhs.[i], frtypes.[i], descs.[i], isConstList.[i]
            match contextRefinement accCtxt expr ty desc isConst with
            | Some(name,newField) ->
                accCtxt.AddValue(name,newField)
            | None ->
                accCtxt

        List.fold foldItem ctxt [0..lhs.Length-1]
    | Do(body,_)
    | Repeat(_,body,_) ->
        //Because do and repeat statements have the guarantee that their
        //bodies will execute, we carry the refinements made in the bodies
        //out of scope.
        let refinements = getAllRefinements ctxt Set.empty body
        { 
        ctxt with
            venv = cover venv refinements
        }
    | ForNum(_,_,_,_,body,_)
    | ForGeneric(_,_,body,_) ->
        //we have no guarantee that the bodies of these statements will
        //execute (though with a bit more code, we could identify numeric
        //loops for which this is not the case), so we undo all refinements
        //made.
        let refinements = getAllRefinements ctxt Set.empty body
        Map.fold undoRefinement ctxt refinements
    | While(cond, body, _) ->
        //TODO: the fact that the condition is no longer true after
        //the loop should give us some deductions
        let refinements = getAllRefinements ctxt Set.empty body
        Map.fold undoRefinement ctxt refinements
    | _ ->
        ctxt

refGetAllRefinements := fun (ctxt : Context) (locals : Set<string>) (stat : TypedStatement) ->
    let venv, tenv = ctxt.venv, ctxt.tenv
    match stat with
    | If(clauses,_) ->
        let clauseRefinements = List.map (getAllRefinements ctxt locals) (List.map snd clauses)
        List.fold cover Map.empty clauseRefinements
    | While(_,body,_)
    | Do(body,_)
    | ForNum(_,_,_,_,body,_)
    | ForGeneric(_,_,body,_)
    | Repeat(_,body,_) ->
        getAllRefinements ctxt locals body
    | Assign(annotation,lvals,rvals,_) ->
        let descriptions,ascriptions,isConstList = Type.InterpretVarAnnotation annotation lvals.Length
        let rctxt = ctxt.DontTrackErrors.IsNotLeftExpr
        let rtypes = List.map (fun expr -> fst (typeCheckExpr rctxt expr)) rvals
        let frtypes = List.collect Type.Flatten rtypes
        let frtypes = coverListOpt frtypes ascriptions
        let frtypes = sizeListTo frtypes lvals.Length NilTy
        
        let makeQuad (i : int) =
            lvals.[i],
            { 
                desc = descriptions.[i]
                ty = frtypes.[i]
                isConst = isConstList.[i]
                loc = (!currentFileName, getExprRange lvals.[i])
            },
            descriptions.[i],
            isConstList.[i]

        let quads = List.init lvals.Length makeQuad

        let collectField ((expr,f,desc,isConst) : TypedExpr*Field*string*bool) =
            match contextRefinement ctxt expr f.ty desc isConst with
            | Some(name,newField) ->
                match ctxt.venv.TryFind name with
                | Some(oldField) ->
                    [(name, { newField with desc = oldField.desc })]
                | _ ->         
                    //TODO: this only happens in the case of user errors.
                    // how should it be handled?
                    [(name,newField)]
            | None ->
                []

        Map.ofList (List.collect collectField quads)        
    | Sequence(s0,s1,_) ->
        let a0 = getAllRefinements ctxt locals s0
        let ctxt' = updateCtxt ctxt s0

        let locals =
            match s0 with
            | LocalAssign(_,lhs,_,_) ->
                let foldExpr (locals : Set<string>) (expr : TypedExpr) : Set<string> =
                    match expr with
                    | NameExpr(name,_) ->
                        locals.Add(name)
                    | _ ->
                        failwith "this shouldn't happen"

                List.fold foldExpr locals lhs
            | _ ->
                locals

        let a1 = getAllRefinements ctxt' locals s1
        cover a0 a1
    | _ ->
        Map.empty

/// Gets types of all unbound assigns in statement
let rec getAssigns (ctxt : Context) (stat : TypedStatement) : ValueEnvironment =
    let venv,tenv = ctxt.venv, ctxt.tenv
    match stat with
    | If(clauses,rng) ->
        // For if statements, we get only those variables that are assigned in
        // each clause, using the type from the first clause

        let clauseAssigns = List.map (getAssigns ctxt) (List.map snd clauses)
        let clause0 = clauseAssigns.[0]
        
        //remove from acc any key not in other
        let clean (acc : ValueEnvironment) (other : ValueEnvironment) =
            let ret = ref acc
            for kv in acc do
                let k = kv.Key
                if not (other.ContainsKey k) then
                    ret := (!ret).Remove k
            !ret
        
        //remove from clause0 any key not contained in any other clause
        //the gives us a context with only those assigns made by all clauses.
        List.fold clean clause0 clauseAssigns
    | While(_,body,_)
    | Do(body,_)
    | ForNum(_,_,_,_,body,_)
    | ForGeneric(_,_,body,_)
    | Repeat(_,body,_) ->
        getAssigns ctxt body
    | Assign(annotation,lvals,rvals,_) ->
        let descriptions,ascriptions,isConstList = Type.InterpretVarAnnotation annotation lvals.Length 
        let rctxt = ctxt.DontTrackErrors.IsNotLeftExpr
        let rtypes = List.map (fun expr -> fst (typeCheckExpr rctxt expr)) rvals
        let frtypes = List.collect Type.Flatten rtypes
        let frtypes = coverListOpt frtypes ascriptions
        let frtypes = sizeListTo frtypes lvals.Length NilTy

        let makeQuad (i : int) =
            (lvals.[i],frtypes.[i],descriptions.[i],isConstList.[i])

        let quads = List.init lvals.Length makeQuad

        let filter ((lexp,rtype,desc,isConst) : TypedExpr*Type*string*bool) =
            match lexp with
            | NameExpr(name,_) when not (venv.ContainsKey name) ->
                true
            | _ ->
                false

        let newAssigns = List.filter filter quads

        let foldField (mp : ValueEnvironment) (NameExpr(n,rng),ty,desc,isConst) =
            mp.Add(n,{desc=desc;ty=ty;loc=(!currentFileName,rng);isConst=isConst})

        List.fold foldField
                  Map.empty 
                  newAssigns

    | Sequence(s0,s1,_) ->
        let a0 = getAssigns ctxt s0
        let ctxt = 
            {
            ctxt with
                venv = cover venv a0
            }
        let ctxt = updateCtxt ctxt s0
        let a1 = getAssigns ctxt s1
        cover a0 a1
    | _ ->
        Map.empty

/// If expr's type actualTy is a subtype of expected, return true.
/// Otherwise, produce an error (using expr's range), and return false.
let checkType (ctxt : Context) (expr : TypedExpr) (actualTy : Type) (expected : Type) =
    let ret, expl = (Type.IsSubtypeOf ctxt.tenv actualTy expected) 
    if not ret then
        if ctxt.trackErrors then
            addError
                (!currentFileName)
                ("actual type " + actualTy.ToString() + " does not match expected type " + expected.ToString() + expl)
                (getExprRange expr)
        false
    else
        true

let typeCheckField (ctxt : Context) (field : TypedConstructorField) =
    match field with
    | ListField(annotation,expr, _) ->
        let descs, ascs, isConstList = Type.InterpretVarAnnotation annotation 1
        let actualTy,_ = typeCheckExpr ctxt expr
        match ascs.[0] with
        | Some expectedTy ->
            ignore (checkType ctxt expr actualTy expectedTy)
        | None ->
            ()

    | RecField(annotation,keyExpr, valExpr, _) ->
        ignore (typeCheckExpr ctxt keyExpr)

        let descs, ascs,isConstList = Type.InterpretVarAnnotation annotation 1
        let actualTy,_ = typeCheckExpr ctxt valExpr 
        match ascs.[0] with
        | Some expectedTy ->
            ignore (checkType ctxt valExpr actualTy expectedTy)
        | None ->
            ()
    | ErrorField(msg,_) ->
        ()

refTypeCheckStat := fun (ctxt : Context) (stat : TypedStatement) ->
    let venv,tenv = ctxt.venv, ctxt.tenv
    match stat with
    | If(clauses,_) ->
        let checkClause ((cond,body) : TypedExpr*TypedStatement) = 
            let condTy,_ = typeCheckExpr ctxt.IsNotLeftExpr cond
            ignore (checkType ctxt cond condTy BoolTy)
            let ctxt = refineContextFromCond ctxt cond
            typeCheckStat ctxt body
            
        List.iter checkClause clauses
    | While(cond,body,_) ->
        let condTy,_ = typeCheckExpr ctxt.IsNotLeftExpr cond
        ignore (checkType ctxt cond condTy BoolTy)
        typeCheckStat ctxt body
    | Do(body,_) ->
        typeCheckStat ctxt body
    | ForNum(var,start,fin,step,body,_) ->
        match var with
        | NameExpr(name,rng) ->
            let startTy,_ = typeCheckExpr ctxt.IsNotLeftExpr start
            let finTy,_ = typeCheckExpr ctxt.IsNotLeftExpr fin
            let stepTy,_ = typeCheckExpr ctxt.IsNotLeftExpr step

            ignore (checkType ctxt start startTy NumberTy)
            ignore (checkType ctxt fin finTy NumberTy)
            ignore (checkType ctxt step stepTy NumberTy)

            let counterField = {
                desc = "loop counter"
                ty = NumberTy
                loc = (!currentFileName,rng)
                isConst = true
            }

            let ctxt' = ctxt.AddValue(name,counterField)
            typeCheckStat ctxt' body
        | _ ->
            failwith "sgadsgda"
    | ForGeneric(vars,gens,body,_) ->
        let makeNamedField (nameExpr : TypedExpr) =
            let (NameExpr(name,rng)) = nameExpr
            name,
            {
                desc = "loop iteration variable"
                ty = UnknownTy
                loc = (!currentFileName,rng)
                isConst = true
            }

        let iterationFields = List.map makeNamedField vars
        let ctxt' = List.fold (fun (c : Context) ((n,f) : string*Field) -> c.AddValue(n,f)) ctxt iterationFields
        typeCheckStat ctxt' body
    | Repeat(cond,body,_) ->
        let condTy,_ = typeCheckExpr ctxt.IsNotLeftExpr cond
        ignore (checkType ctxt cond condTy BoolTy)
        typeCheckStat ctxt body
    | LocalAssign(annotation,names,exprs,_) ->
        let descriptions,ascriptions,isConstList = 
            Type.InterpretVarAnnotation annotation names.Length
        
        let ascrInd = ref 0
        //gets the next ascription, or UnknownTy if none are left
        let getAscr () =
            let ret =
                if !ascrInd < ascriptions.Length then
                    ascriptions.[!ascrInd]
                else
                    None
            ascrInd := !ascrInd + 1
            ret

        for expr in exprs do
            let ty,_ = typeCheckExpr ctxt.IsNotLeftExpr expr
            match ty with
            | TupleTy(elements) ->
                let checkElement (i : int) (ty : Type) =
                    let ascr = getAscr()
                    if ascr.IsSome then
                        let isSub,expl = Type.IsSubtypeOf tenv ty ascr.Value
                        if not isSub && ctxt.trackErrors then
                            addError
                                !currentFileName
                                ((i+1).ToString() + "th return type '" + ty.ToString() + "' does not match ascribed type '" + ascr.ToString() + "'" + expl)
                                (getExprRange expr)
                List.iteri checkElement elements
            | _ ->
                let ascr = getAscr()
                if ascr.IsSome then
                    ignore (checkType ctxt expr ty ascr.Value)
    | Assign(annotation,lvals, rvals,_) ->
        let descriptions,ascriptions,isConstList = 
            Type.InterpretVarAnnotation annotation lvals.Length 

        let ascrInd = ref 0
        //gets the next ascription, or UnknownTy if none are left
        let getAscr () =
            let ret =
                if !ascrInd < ascriptions.Length then
                    ascriptions.[!ascrInd]
                else
                    None
            ascrInd := !ascrInd + 1
            ret

        for expr in rvals do
            let ty,_ = typeCheckExpr ctxt.IsNotLeftExpr expr
            match ty with
            | TupleTy(elements) ->
                let checkElement (i : int) (ty : Type) =
                    let ascr = getAscr()
                    if ascr.IsSome then
                        let ascr = ascr.Value
                        let isSub, expl = Type.IsSubtypeOf tenv ty ascr
                        if (not isSub) && ctxt.trackErrors then
                            addError
                                !currentFileName
                                ((i+1).ToString() + "th return type '" + ty.ToString() + "' does not match ascribed type '" + ascr.ToString() + "'" + expl)
                                (getExprRange expr)
                List.iteri checkElement elements
            | _ ->
                let ascr = getAscr()
                if ascr.IsSome then
                    ignore (checkType ctxt expr ty ascr.Value)

        let rctxt = ctxt.IsNotLeftExpr.DontTrackErrors
        let rtypes = List.map (fun expr -> fst (typeCheckExpr rctxt expr)) rvals
        let frtypes = List.collect Type.Flatten rtypes
        let frtypes = coverListOpt frtypes ascriptions
        let frtypes = sizeListTo frtypes lvals.Length NilTy

        let ltypeFields = List.map (fun expr -> typeCheckExpr ctxt.IsLeftExpr expr) lvals
        let ltypes,lfields = List.unzip ltypeFields
        let lranges = List.map getExprRange lvals
        
        let check (i : int) =
            let rtype = frtypes.[i]
            let ltype = ltypes.[i]
            let lrange = lranges.[i]
            let lfield = lfields.[i]

            if lfield.IsSome && lfield.Value.isConst then
                if ctxt.trackErrors then
                    addError
                        !currentFileName
                        "cannot assign constants"
                        lrange                  
            else
                let isSub, expl = Type.IsSubtypeOf tenv rtype ltype
                if not isSub && ctxt.trackErrors then
                    addError
                        !currentFileName
                        ("right-hand type " + rtype.ToString() + " is not a subtype of left-hand type " + ltype.ToString()+expl) 
                        lrange

        List.iter check [0..ltypes.Length-1]
    | Return(rets,_) ->
        List.iter (fun expr -> ignore (typeCheckExpr ctxt expr)) rets
    | Break(_) ->
        ()
    | Call(callExp,_) ->
        ignore (typeCheckExpr ctxt.IsNotLeftExpr callExp)
    | Sequence(s0,s1,_) ->
        typeCheckStat ctxt s0
        let ctxt' = updateCtxt ctxt s0
        typeCheckStat ctxt' s1
    | DoNothing(_) ->
        ()
    | ErrorStatement(_) ->
        ()

// given a function type's formals return the range for the potential number
// of arguments that it may take
// let getFunctionTyArgRange (formals : List<type>)
refTypeCheckExpr := fun (ctxt : Context) (expr : TypedExpr) ->
    let venv, tenv = ctxt.venv, ctxt.tenv
    match expr with
    | CallExpr(NameExpr("lucbdnioua",_),[],_) ->
        refStubContext := ctxt
        UnknownTy,None
    | CallExpr(NameExpr("require",_), [String(moduleName,_)], rng) ->
        if tenv.consMap.ContainsKey moduleName then
            tenv.consMap.Item moduleName,None
        else
            UnknownTy,None
    | Number(_,rng) ->
        NumberTy,None
    | String(_,rng) ->
        Type.Unfold tenv (UserDefinedTy("string")),None       
    | Nil(rng) ->
        NilTy,None
    | True(rng) ->
        BoolTy,None      
    | False(rng) ->
        BoolTy,None
    | VarArgs(rng) ->
        TupleTy([UnknownTy;UnknownTy;UnknownTy;UnknownTy;UnknownTy;UnknownTy;UnknownTy;UnknownTy;UnknownTy;UnknownTy]),None
    | Constructor(fields,rng) ->
        
        List.iter (fun x -> (typeCheckField ctxt x)) fields

        /// Returns true iff the field has literal string keys
        let rec isStructural (field : TypedConstructorField) =
            match field with
            | RecField(_,String(k,_),v,_) ->
                true
            | _ ->
                false

        /// Returns true iff the field is a list field
        /// TODO: fields should not be a disjoint union: list fields can be expressed with
        /// rec fields... though error fields cannot
        let rec isListField (field : TypedConstructorField) =
            match field with
            | ListField(_,_,_)
            | RecField(_,Number(_,_),_,_) ->
                true
            | _ ->
                false
        
        /// so that we can attach comments (and ascriptions?) to them
        let getLabelAndTy (field : TypedConstructorField) =
            match field with
            | RecField(ann,String(k,_),v,rng) ->
                let desc,ascs,isConstList = Type.InterpretVarAnnotation ann 1
                
                let ctxt = ctxt.IsNotLeftExpr.DontTrackErrors

                let field = 
                    match ascs.[0] with
                    | Some ty -> 
                        {
                            desc = desc.[0]
                            ty = (fst >> Type.Untuple) (typeCheckExpr ctxt (Ascription(v,ty,rng)))
                            loc = (!currentFileName,rng)
                            isConst = isConstList.[0]
                        }
                    | None -> 
                        {
                            desc = desc.[0]
                            ty = (fst >> Type.Untuple) (typeCheckExpr ctxt v)
                            loc = (!currentFileName,rng)
                            isConst = isConstList.[0]
                        }

                (k, field)
            | _ ->
                failwith "only structural fields allowed"


        if fields.Length > 0 && List.forall isStructural fields then
            RecordTy(
                "*UnnamedRecord*", 
                "",
                true,
                MetamethodSet.empty, 
                new Map<string,Field>(List.map getLabelAndTy fields),
                new Map<string,Method>([]), 
                (!currentFileName,rng)
            ),
            None
        elif fields.Length > 0 && List.forall isListField fields then 
            let fieldTy0 = 
                match fields.[0] with
                | ListField(_,v,_) 
                | RecField(_,Number(_,_),v,_) ->
                    Type.Untuple (fst (typeCheckExpr ctxt.IsNotLeftExpr.DontTrackErrors v))

            let checkListElement (field : TypedConstructorField) =
                let fieldTy,rng = 
                    match field with
                    | ListField(_,v,rng) 
                    | RecField(_,Number(_,_),v,rng) ->
                        Type.Untuple (fst (typeCheckExpr ctxt.IsNotLeftExpr.DontTrackErrors v)), rng

                if not (Type.IsEqual tenv fieldTy fieldTy0) then
                    addError
                        !currentFileName
                        ("Element does not have expected type " + fieldTy0.ToString() + ".")
                        rng

            List.iter checkListElement fields

            let metaset = {
                MetamethodSet.empty with
                    Index = Some("index into table", NumberTy, fieldTy0)
            }

            RecordTy(
                "*UnnamedRecord*",
                "",
                true,
                metaset,
                Map.empty,
                Map.empty,
                (!currentFileName, rng)
            ),
            None
        else
            UnknownTy, None

    | Function(desc,selfName,formals,hasVarArgs,rets,body,rng) ->
        let ty = FunctionTy(desc,formals,rets,false,(!currentFileName,rng))

        let foldFormal (c : Context) (nm,desc,ty) = 
            let newField = {
                desc = desc
                ty = Type.Unfold c.tenv ty
                loc = (!currentFileName,rng)
                isConst = false
            }

            c.AddValue(nm,newField)

        let funcField = {
            desc = desc
            ty = ty
            loc = (!currentFileName,rng)
            isConst = false
        }

        let ctxt = List.fold foldFormal ctxt formals 
        let ctxt =
            match selfName with
            | Some name ->
                ctxt.AddValue(name, funcField)
            | _ ->
                ctxt
             
        typeCheckStat ctxt.UndoAllDeductions body
        ty,None
    | UnOpExpr(unop,operand,rng) ->
        let operandTy = Type.Coerce tenv (fst (typeCheckExpr ctxt operand))
        
        match operandTy with
        | UnknownTy ->
            UnknownTy,None
        | _ ->
            let metaset = getMetamethodSet ctxt.tenv operandTy
            let operatorTy = getUnOp metaset unop

            match operatorTy with
            | Some(desc,ty) ->
                ty,None
            | None ->
                UnknownTy,None

    | BinOpExpr(binop, opA, opB, rng) ->
        let tyA,_ = typeCheckExpr ctxt opA
        match (Type.Coerce tenv tyA,binop,opB) with
        | (UnknownTy,OpInd,_)
        | (UnknownTy,OpMethInd,_) ->
            UnknownTy,None
        | (UnknownTy,_,_) ->
            ignore (typeCheckExpr ctxt opB)
            UnknownTy,None
        | (ArrayTy(retTy),OpInd,opB) ->
            let tyB = Type.Coerce tenv (fst (typeCheckExpr ctxt opB))
            if tyB = NumberTy then
                retTy,None
            else
                UnknownTy,None
        | (OpenRecordTy(_,_,_,_,fields,_,_),OpInd,String(str,srng))
        | (RecordTy(_,_,_,_,fields,_,_),OpInd,String(str,srng)) when fields.ContainsKey str ->
            let field = fields.Item str
            if ctxt.queryPos.IsSome && inRange ctxt.queryPos.Value srng then
                refStubDesc := field.desc
                refStubDefLoc := field.loc
                refStubTy := field.ty

            field.ty,Some(field)
        | (RecordTy(name,_,_,_,_,_,_),OpInd,String(str,_)) ->
            if ctxt.trackErrors then
                addError
                    !currentFileName
                    (name + " does not have a field called " + str)
                    rng
            UnknownTy,None
        | (OpenRecordTy(_,_,_,_,_,methods,_),OpMethInd, String(str,mrng))
        | (RecordTy(_,_,_,_,_,methods,_),OpMethInd, String(str,mrng)) when methods.ContainsKey str ->
            let meth = methods.Item str
            if ctxt.queryPos.IsSome && inRange ctxt.queryPos.Value mrng then
                refStubDesc := meth.desc
                refStubDefLoc := meth.loc
                refStubTy := meth.ty
            meth.ty,None
        | (RecordTy(name,_,_,_,_,methods,_),OpMethInd, String(str,_)) ->
            if ctxt.trackErrors then
                addError
                    !currentFileName
                    (name + " does not have a method called " + str)
                    rng
            UnknownTy,None
        | (OpenRecordTy(name,_,_,_,_,_,_),OpMethInd, String(str,_)) ->
            if ctxt.trackErrors then
                addError
                    !currentFileName
                    (name + " does not have a method called " + str)
                    rng
            UnknownTy,None
        | (OpenRecordTy(name,_,_,_,_,methods,_),OpInd, String(str,_)) ->
            if methods.ContainsKey str && ctxt.isLeftExpr then
                addError
                    !currentFileName
                    (name + " already contains a method called " + str + ". Cannot add a field of the same name.")
                    rng
                UnknownTy,None
            elif ctxt.isLeftExpr then
                NewFieldTy,None//RecordTy("*NewField*","",None,MetamethodSet.empty,Map.empty,Map.empty,("",(0,0)))
            else
                if ctxt.trackErrors then
                    addError
                        !currentFileName
                        (name + " does not have a field called " + str)
                        rng
                UnknownTy,None
        | _ ->
            let metaset = getMetamethodSet ctxt.tenv tyA
            let opTy = getBinOp metaset binop
            let tyB = Type.Coerce tenv (fst (typeCheckExpr ctxt opB))
            match (opTy) with
            | (None) ->
                if ctxt.trackErrors then
                    addError
                        !currentFileName
                        (tyA.ToString() + " does not define a " + binop.ToString() + " operator")
                        rng
                UnknownTy,None
            | Some (desc,expectedRhsTy, retTy) ->
                match tyB with
                | UnknownTy ->
                    UnknownTy, None
                | _ ->
                    ignore (checkType ctxt opB tyB expectedRhsTy)
                    retTy, None
    | ParenthesizedExpr(expr,rng) ->
        Type.Coerce tenv (fst (typeCheckExpr ctxt.IsNotLeftExpr expr)), None
    | NameExpr(name, rng) ->
        if ctxt.venv.ContainsKey name then
            let field = ctxt.venv.Item name
            if ctxt.queryPos.IsSome && inRange ctxt.queryPos.Value rng then
                refStubDesc := field.desc
                refStubDefLoc := field.loc
                refStubTy := field.ty

            field.ty, Some(field)
        elif ctxt.addGlobals && ctxt.isLeftExpr then
            NewFieldTy, None
        else
            if ctxt.trackErrors then
                addError
                    (!currentFileName)
                    "variable not in context"
                    rng
            UnknownTy, None     
    | CallExpr(func,actuals,rng) ->
        let actualTypes = List.map (fun x -> fst (typeCheckExpr ctxt.IsNotLeftExpr x)) actuals

        //returns the input for function types and the call metamethod for record types
        let funcTy = Type.Coerce tenv (fst (typeCheckExpr ctxt.IsNotLeftExpr func))

        // If this is an Overload type, we need to find some overload which
        // matches the actuals. If multiple overloads match, we choose an
        // arbitrary one. Anything that goes wrong would then be the fault
        // of the API designer.
        let funcTy = 
            match funcTy with
            | OverloadTy(overloads) ->
                let overloadMatches (ty : Type) =
                    match ty with
                    | FunctionTy(desc,formals,rets,isMethod,loc) ->
                        if actuals.Length > formals.Length then
                            false
                        else
                            let actuals =
                                if actuals.Length > formals.Length then
                                    actuals
                                else
                                    padList actuals (Nil rng) formals.Length

                            let actualMatchesFormal (actual : TypedExpr) (formalTy : Type) =
                                let actualTy,_ = typeCheckExpr ctxt actual
                                fst (Type.IsSubtypeOf tenv actualTy formalTy)

                            List.forall2 actualMatchesFormal actuals (List.map (fun (_,_,z) -> z) formals)
                    | _ ->
                        false

                match List.tryFind overloadMatches overloads with
                | Some(overload) ->
                    overload
                | None ->
                    if ctxt.trackErrors then
                        addError
                            !currentFileName
                            ("argument types " + actualTypes.ToString() + " matches none of the overloads " + overloads.ToString())
                            rng
                             
                    UnknownTy
            | _ ->
                funcTy

        match funcTy with
        | CallableTy(_,formals,rets,isMethod,loc) ->
            let formals,actuals,actualTypes = 
                if isMethod then
                    formals.Tail, actuals.Tail, actualTypes.Tail
                else
                    formals,actuals,actualTypes

            let revFormals = ref (List.rev formals)
            let numOptionals = ref 0
            let thrd (_,_,x) = x

            let isNillable (ty : Type) =
                match ty with
                | NillableTy(_) 
                | NilTy ->
                    true
                | _ ->
                    false

            while (not (!revFormals).IsEmpty) && (isNillable (thrd (!revFormals).Head)) do
                revFormals := (!revFormals).Tail
                numOptionals := !numOptionals + 1

            let (funcStart,funcFin) = getExprRange func
            let (_,callFin) = rng
            let minActuals = formals.Length - !numOptionals
            
            if (actuals.Length < minActuals) || (actuals.Length > formals.Length) then
                if minActuals = formals.Length then
                    if ctxt.trackErrors then
                        addError
                            !currentFileName
                            ("received " + actuals.Length.ToString() + " arguments. Expected " + formals.Length.ToString() + ".")
                            (funcStart,callFin)
                else
                    if ctxt.trackErrors then
                        addError
                            !currentFileName
                            ("received " + actuals.Length.ToString() + " arguments. Expected between " + minActuals.ToString() + " and " + formals.Length.ToString() + ".")
                            (funcStart,callFin)
            else
                let actuals =
                    padList actuals (Nil rng) formals.Length

                let actualTypes =
                    padList actualTypes NilTy formals.Length

                let triples = List.zip3 actuals actualTypes formals
                    
                let checkTriple ((actual,actualTy,(_,_,formalTy)) : TypedExpr*Type*(string*string*Type)) =
                    ignore (checkType ctxt actual actualTy formalTy)

                List.iter checkTriple triples

            if rets.Length > 0 then
                match snd rets.[0] with
                | ErrorTy(msg) ->
                    if ctxt.trackErrors then
                        addError
                            !currentFileName
                            msg
                            (funcStart,callFin)
                    UnknownTy, None
                | _ ->
                    TupleTy(List.map snd rets), None
            else
                TupleTy(List.replicate 20 UnknownTy), None

        | UnknownTy ->
            TupleTy(List.replicate 20 UnknownTy), None
        | _ ->
            let (funcStart,funcFin) = getExprRange func
            let (_,callFin) = rng
            if ctxt.trackErrors then
                addError
                    !currentFileName
                    ("instances of type " + funcTy.ToString() + " are uncallable")
                    (funcStart,callFin)  
            UnknownTy, None
    | Ascription(expr,ty,rng) ->
        let exprTy,field = typeCheckExpr ctxt expr
        ignore (checkType ctxt expr exprTy ty)
        ty, field
    | ErrorExpr(_,_) ->
        UnknownTy, None

let (|MethodDefInCtxt|) (ctxt : Context) (methName : string) (stat : TypedStatement) =
    let venv,tenv = ctxt.venv, ctxt.tenv
    let rec findDef (stat : TypedStatement) (ctxt : Context) : Option<TypedStatement*Context*Range>=        
        match stat with
        | Sequence(s0,s1,rng) ->
            match findDef s0 ctxt with
            | Some x ->
                Some x
            | None ->
                let ctxt' = updateCtxt ctxt s0
                findDef s1 ctxt'
        | Assign(
            _,
            [BinOpExpr(OpInd,NameExpr(x,_),String(name,nameRng),_)],
            [Function(desc,selfName,formals,varargs,rets,body,(startLoc,_))],
            _
          ) when name = methName ->
            let foldFormal (mp : ValueEnvironment) (name,desc,ty) =
                let field = {
                    desc = desc
                    ty = Type.Unfold tenv ty 
                    loc = (!currentFileName,nameRng)
                    isConst = false
                }
                 mp.Add(name,field)
            let argVenv : ValueEnvironment = List.fold foldFormal Map.empty formals 
            let ctxt = 
                {
                ctxt with
                    venv = cover ctxt.venv argVenv
                }
            Some (body, ctxt, nameRng)
        | _ ->
            None
   
    findDef stat ctxt
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.