Source

love studio / LoveStudio / LuaAnalyzer / Type.fs

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
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
///
/// Defines a family of optional types which are used for classifying 
/// lua expressions and propogating intellisense data.
///
module LuaAnalyzer.Type

open System.Diagnostics.Contracts

open Annotations
open Syntax // BinOp
open Utils

/// Stores the location of a function definition
/// the string is the project-relative filename containing the definition
/// the int is the absolute offset of the definition in the file
type DefinitionLocation = string*(int*int)

let NoLocation : DefinitionLocation = ("",(0,0))

/// A structure describing all known types, their properties, and relations, 
/// available to a piece of code.
type TypeEnvironment = {

    /// The set of all instance type names, i.e. those types which can be 
    /// referenced from annotations
    instanceTypes : Set<string>

    /// Maps all type names (both for external and internal types) to their
    /// corresponding type structures.
    typeMap : Map<string,Type>

    /// Maps each type to the range its declaration appears in
    typeDeclarationRanges : Map<string,Range>

    /// Maps each user-defined type to the file it was defined in
    typeFiles : Map<string, string>

    /// maps constructors to their corresponding type structures
    consMap : Map<string,Type>

    /// A nominal subtyping graph, includes both internal and external types
    /// An entry (a,b) means "a is a subtype of each element in b"
    edges : Map<string,List<string>>
}

/// Describes an operation which can be performed by an object.
and Method = 
    {
        /// A description of the method's behavior
        desc : string
        /// They type of the method.
        /// Must be a function type with at least one formal parameter,
        /// the leading parameter being a non-typed self reference.
        // Typing the self argument would make it difficult to reuse methods
        // via inheritence. Instead, the typing of the self argument should
        // be done by a type collector's decorate callback.
        ty : Type
        /// Whether or not the method is abstract. 
        isAbstract : bool
        /// The location (filename, char index) at which this identifier was 
        /// delcared.
        loc : DefinitionLocation
    }

/// Many identifiers occurring in programs refer to runtime values. These
/// identifiers are associated the statically computed satellite data 
/// contained in Field.
and Field =
    {
        /// A description of the identifier's purpose
        desc : string
        /// A statically computed type of the values that the identifier
        /// denotes. Since this is not a sound type system, runtime values
        /// associated with this identifier may sometimes not actually belong
        /// to this type; the goal is to design the type system to minimize
        /// the frequency of theses scenarios without limiting the programmer.
        ty : Type
        /// The location (filename, char index) at which this identifier was 
        /// delcared.
        loc : DefinitionLocation
        /// Whether or not this identifier can be reassigned to expressions
        /// determined to have type *ty*.
        isConst : bool
    }

/// A family of optional types for classifying lua expressions and associating
/// them with descriptions about the types of values they denote.
and Type =
    /// NumberTy classifies expressions which denote double precision floating
    /// point numbers, which are used for both integers and approximating 
    /// real numbers in Lua.
    | NumberTy
    /// StringTy classifies expressions which denote arrays of characters.
    | StringTy
    /// NilTy classifies expressions which denote the value nil
    | NilTy
    /// BoolTy classifies expressions which may denote either true or false.
    | BoolTy
    /// Record(name,description,isStructural,metamethods,fieldMap,methodMap)
    /// fieldList and methodList map names to description/type/loc triples
    /// srcExpr maps  
    ///
    /// 
    /// 
    /// Classifies expressions which denote records. A record contains labeled
    /// fields and methods which can be indexed, as well as a set of operator
    /// overloads (i.e. metamethods). 
    | RecordTy of string*string*bool*MetamethodSet*Map<string,Field>*Map<string,Method>*DefinitionLocation
    /// Like record, but allows new fields to be added. TODO: comment more
    | OpenRecordTy of string*string*bool*MetamethodSet*Map<string,Field>*Map<string,Method>*DefinitionLocation
    /// When an open record in an lexp gets indexed by a field it doesn't
    /// have, the resulting type is NewField. NewField is a treated as a 
    /// supertype of anything so that its variables can be assigned to anything.
    | NewFieldTy
    /// Function(desc,params,rets,method, deflocation) -
    /// desc - description of the function
    /// params - name/description/type triples for each formal parameter
    /// ret - description/type pairs for each return value
    /// method - whether or not this is a method (with implicit self)
    /// deflocation - location of function definition
    ///
    /// FunctionTy classifies expressions which denote functions or procedures
    /// which can be called.
    | FunctionTy of string*List<string*string*Type>*List<string*Type>*bool*DefinitionLocation
    /// TupleTy([ty1,ty2,...]) classifies expressions which denote an ordered 
    /// list of values, where ty1 classifies the first value, ty2 classifies the
    /// second, etc. The only such expressions in lua are call expressions, which
    /// may return multiple values, and vararg literals. TupleTy may be coerced 
    /// into the first type in its contained list.
    | TupleTy of List<Type>
    /// OverloadTy([ty1,ty2,...]) classifies record lookups on keys which
    /// which map to several values of different types. This is intended 
    /// to represent overloaded functions defined in C APIs, and should be
    /// used sparingly.
    | OverloadTy of List<Type>
    /// NillableTy(ty) behaves exactly the same as ty, but NilTy is a subtype
    /// of it, allowing NillableTy(ty) variables to be assigned to nil.
    /// These types appear in annotations as ?typename.
    | NillableTy of Type
    /// UserDefined(typename) is converted to userTypes[typename] before it is 
    /// used. Indirection is necessary in order to handle recursive types.
    | UserDefinedTy of string
    /// permanent type/temporary type
    /// can be assigned to any value belonging to the permanent type
    /// can be used as temporary type
    /// TODO: Closures could really screw up deduced types. Closures are rare,
    /// though. We could disable deduced types in blocks with closures.
    | DeducedTy of Type*Type
    /// ErrorTy(msg) -
    /// Whenever a function returns an item belonging to type ErrorTy,
    /// the type checker reports the error contained in msg. This can
    /// be used to notify the user of common problems, such as trying
    /// to instantiate an abstract class. 
    | ErrorTy of string
    /// Classifies all expressions which we are unable to classify by other
    /// means. Expressions of this type can occur in any context without
    /// generating errors.
    /// Appears in annotations as "unknown".
    | UnknownTy

    /// Provides an elaborate, multiline description of the type (or a short one-liner when sufficient) 
    /// for use in calltips.
    member this.ToStringElaborate() =
        match this with
        | FunctionTy(desc,pars,rets,meth,deflocation) ->
            let desc = if desc = "" then "" else "\n" + desc
            let ret = ref ("Function" + desc)

            let pars = 
                if meth then 
                    List.tail pars
                else
                    pars

            if pars.Length > 0 then
                ret := !ret + "\nParameters:"
                for pname,pdesc,pty in pars do
                    ret := !ret + "\n" + pname + " : " + pty.ToString() + " - " + pdesc
            
            if rets.Length > 0 then
                ret := !ret + "\nReturns:"
                for rdesc,rty in rets do
                    ret := !ret + "\n" + rty.ToString() + " - " + rdesc
            !ret
        | _ ->
            this.ToString()

    /// A brief, one line description of the type.
    override this.ToString() =
        match this with
        | NumberTy ->
            "number"
        | StringTy ->
            "string"
        | NilTy ->
            "nil"
        | BoolTy ->
            "boolean"
        | RecordTy(name,_,_,_,_,_,_) ->
            name
        | OpenRecordTy(name,_,_,_,_,_,_) ->
            name
        | NewFieldTy ->
            "newfield"
        | FunctionTy(desc,pars,rets,meth,deflocation) ->
            let foldPar acc (name,desc,ty) =
                acc + ty.ToString()
            let foldRet acc (desc,ty) =
                acc + ty.ToString()

            let parTys = List.map (fun (name,desc,ty) -> ty) pars
            let retTys = List.map (fun (desc,ty) -> ty) rets

            "(" + parTys.ToString() + " -> "  + retTys.ToString() + ")"
        | NillableTy(ty) ->
            "?" + ty.ToString()
        | UserDefinedTy(name) ->
            name
        | TupleTy(tyList) ->
            "tuple: " + tyList.ToString()
        | OverloadTy(tyList) ->
            "overload: " + tyList.ToString()
        | DeducedTy(perm,temp) ->
            "Deduced Type: (perm = " + perm.ToString() + ", temp = " + temp.ToString() + ")"
        | ErrorTy(_) ->
            "Error"
        | UnknownTy ->
            "unknown"

    /// Generate a deduced Type for when an field of type original 
    /// has been determined to have type deduced.
    static member MakeDeducedTy (original : Type) (deduced : Type) =
        match original with
        | DeducedTy(permOriginal,_) ->
            DeducedTy(permOriginal,deduced)
        | _ ->
            DeducedTy(original,deduced)
    
    static member Flatten (ty : Type) =
        match ty with
        | TupleTy(lst) ->
            lst
        | x ->
            [x]

    /// TODO: Add a list of strings, path
    static member UndoDeductions (ty : Type) =
        match ty with
        | RecordTy(a,b,c,d,fields,e,loc) ->
            RecordTy(a,b,c,d,Map.map (fun k f -> {f with ty=Type.UndoDeductions f.ty}) fields,e,loc)
        | NillableTy(ty) ->
            NillableTy(Type.UndoDeductions ty)
        | DeducedTy(perm,temp) ->
            Type.UndoDeductions perm
        | _ ->
            ty

    static member FromString (name : string) =
        let name,nillable,isConst =
            if name.[0] = '?' then
                name.Substring(1),true,false
            else
                name,false,false

        //TODO: is tyName recorded as an external type name?
        //if not, record an error... maybe should be done during final typechecking
        let ty =
            match name with
            | "nil" ->
                NilTy
            | "number" ->
                NumberTy
            | "boolean" ->
                BoolTy
            | "unknown" ->
                UnknownTy
            | _ ->
                UserDefinedTy(name)

        if nillable then
            NillableTy(ty)
        else
            ty

    static member Unfold (env : TypeEnvironment) (ty : Type) =
        let tyMap = env.typeMap
        match ty with
        | UserDefinedTy(name) ->
            match tyMap.TryFind name with
            | Some(userTy) ->
                userTy
            | None ->
                UnknownTy
        | _ ->
            ty
    
    static member Untuple (ty : Type) =
        match ty with
        | TupleTy(head::_) ->
            head
        | _ ->
            ty

    /// Allows the a tuple or nillable instance to be treated as its first element
    /// when, for example, it gets operated on, called, or parenthesized.
    static member Coerce (env : TypeEnvironment) (ty : Type) =
        match Type.Unfold env ty with
        | TupleTy(head::_) ->
            Type.Coerce env head
        | NillableTy(ty) ->
            Type.Coerce env ty
        | DeducedTy(_,temp) ->
            Type.Coerce env temp
        | _ ->
            Type.Unfold env ty

/// (description, rhsType, retTy) for binary operator
and BinOpTy = string*Type*Type

/// description, return type of unary operator
and UnOpTy = string*Type

and MetamethodSet = {
    /// Binary '+' operator type, if defined
    Add : Option<BinOpTy>
    /// Binary '-' operator type, if defined
    Sub : Option<BinOpTy>
    /// Binary '*' operator type, if defined
    Mul : Option<BinOpTy>
    /// Binary '/' operator type, if defined
    Div : Option<BinOpTy>
    /// Binary '%' operator type, if defined
    Mod : Option<BinOpTy>
    /// Binary '^' operator type, if defined
    Pow : Option<BinOpTy>
    /// Unary '-' operator type, if defined
    Unm : Option<UnOpTy>
    /// Binary '..' operator type, if defined
    Concat : Option<BinOpTy>
    /// Unary '#' operator type, if defined
    Len : Option<UnOpTy>
    /// Binary '==' operator type, if defined
    Eq : Option<BinOpTy>
    /// Binary '~=' operator type, if defined
    Ne : Option<BinOpTy>
    /// Binary '<' operator type, if defined
    Lt : Option<BinOpTy>
    /// Binary '<=' opeartor type, if defined
    Le : Option<BinOpTy>
    /// Binary '>' operator type, if defined
    Gt : Option<BinOpTy>
    /// Binary '>=' operator type, if defined
    Ge : Option<BinOpTy>
    
    /// Binary 'and' operator type, if defined; for certain built-in types only
    And : Option<BinOpTy>
    /// Binary 'or' operator type, if defined; for certain built-in types only
    Or : Option<BinOpTy>
    /// Unary 'not' operator type, if defined; for certain built-in types only
    Not : Option<UnOpTy>

    /// Binary '[]' operator type, if defined
    /// note that string cannot be used as the rhs type, as string indices are 
    /// considered structural.
    Index : Option<BinOpTy>

    // newindex is not handled by the type system
    // whenever an assign happens, we check that the
    // lhs and rhs have equal types. So newindex is really
    // handled using the index metamethod by our type system.

    /// call operator
    Call : Option< string*List<string*string*Type>*List<string*Type>*bool*DefinitionLocation > 
}


type MetamethodSet with
    /// Default metamethod set, defining metamethods only for the == and ~=
    /// operators, which can be applied to operands of any type.
    static member empty
        with get () =
            {
                Add = None
                Sub = None
                Mul = None
                Div = None
                Mod = None
                Pow = None
                Unm = None
                Concat = None
                Len = None
                Eq = Some("equal",UnknownTy,BoolTy)
                Ne = Some("not equal",UnknownTy,BoolTy)
                Lt = None
                Le = None
                Gt = None
                Ge = None
                And = None
                Or = None
                Not = None
                Index = None
                Call = None
            }


    /// Returns a metamethod set which is the result of covering a with b.
    ///
    /// i.e. a metamethod set which uses all of the metamethods
    /// of b which are defined. For those which does b does not define,
    /// it uses a's metamethods if they exist. If neither set defines
    /// an operator, the resulting set does not define that operator.
    static member cover (a : MetamethodSet) (b : MetamethodSet) =
        { MetamethodSet.empty with
            Add = if Option.isSome b.Add then b.Add else a.Add
            Sub = if Option.isSome b.Sub then b.Sub else a.Sub
            Mul = if Option.isSome b.Mul then b.Mul else a.Mul
            Div = if Option.isSome b.Div then b.Div else a.Div
            Mod = if Option.isSome b.Mod then b.Mod else a.Mod
            Pow = if Option.isSome b.Pow then b.Pow else a.Pow
            Unm = if Option.isSome b.Unm then b.Unm else a.Unm
            Concat = if Option.isSome b.Concat then b.Concat else a.Concat
            Len = if Option.isSome b.Len then b.Len else a.Len
            Eq = if Option.isSome b.Eq then b.Eq else a.Eq
            Ne = if Option.isSome b.Ne then b.Ne else a.Ne
            Lt = if Option.isSome b.Lt then b.Lt else a.Lt
            Le = if Option.isSome b.Le then b.Le else a.Le
            Gt = if Option.isSome b.Gt then b.Gt else a.Gt
            Ge = if Option.isSome b.Ge then b.Ge else a.Ge
            And = if Option.isSome b.And then b.And else a.And
            Or = if Option.isSome b.Or then b.Or else a.Or
            Not = if Option.isSome b.Not then b.Not else a.Not
            Index = if Option.isSome b.Index then b.Index else a.Index
            Call = if Option.isSome b.Call then b.Call else a.Call
        }
            
type TypeEnvironment with
    /// An empty type environment
    static member empty
        with get () =
            {
                instanceTypes = Set.empty
                typeMap = Map.empty
                typeDeclarationRanges = Map.empty
                typeFiles = Map.empty
                consMap = Map.empty
                edges = Map.empty
            }
    
    /// A list of all typenames appearing in the nominal subtyping
    /// graph, topologically sorted. what does it mean for a list to be 
    /// topologically sorted? See the wikipedia page on it: *insert url here*.
    /// Also, read CLRS; you'll learn a bunch of other cool algorithms in 
    /// addition to the topological sort.
    member this.TopSortedTypeNames
        with get() =
            let subtypeEdges = this.edges

            let visited = ref Set.empty
            let ret = ref []

            let rec topSortAux (root : string) =
                for adj in subtypeEdges.Item root do
                    if (!visited).Contains adj then
                        ()
                    else
                        topSortAux adj

                visited := (!visited).Add(root)
                ret := root :: !ret

            for kv in this.typeFiles do
                let typeName = kv.Key
                topSortAux typeName
        
            List.rev !ret        

/// Matches any type (either function, or record with call metamethod), which
/// classifies callable values. Yields pattern variables which describe the
/// call interface:
/// CallableTy(desc,formals,rets,isMethod,defLocation) 
///
/// desc - description of the "function"
/// params - name/description/type pairs for each formal parameter
/// ret - description/type pairs for each return value
/// method - whether or not this is a method (with implicit self)
/// deflocation - location of function definition
let (|CallableTy|_|) (ty : Type) =
    match ty with
    | FunctionTy(desc,formals,rets,isMethod,defLocation) ->
        Some (desc,formals,rets,isMethod,defLocation)
    | RecordTy(_,_,_,metamethods,_,_,_)
    | OpenRecordTy(_,_,_,metamethods,_,_,_) ->
        match metamethods.Call with
        | Some(desc,formals,rets,isMethod,defLocation) ->
            Some (desc,formals,rets,isMethod,defLocation)
        | None ->
            None
    | _ ->
        None

let (|ClassTy|_|) (ty : Type) =
    match ty with
    | RecordTy(name,description,srcExpr,metamethods,fieldMap,methodMap,rng) ->
        Some (metamethods,fieldMap,methodMap)
    | UnknownTy ->
        Some (MetamethodSet.empty,Map.empty,Map.empty)
    | _ ->
        None

let (|ArrayTy|_|) (ty : Type) =
    match ty with
    | RecordTy(_,_,_,metamethods,_,_,_) ->
        match metamethods.Index with
        | Some(_,rhsTy,retTy) when rhsTy = NumberTy ->
            Some (retTy)
        | _ ->
            None
    | _ ->
        None

let getUnOp (metaset : MetamethodSet) (unop : UnOp) =
    match unop with
    | OpNegate ->
        metaset.Unm
    | OpNot ->
        metaset.Not
    | OpLen ->
        metaset.Len

/// Given a metamethod set, returns the metamethod (if any) defined for
/// the specified binary operator.
let getBinOp (metaset : MetamethodSet) (binop : BinOp) =
    match binop with
    | OpAdd ->
        metaset.Add
    | OpSub ->
        metaset.Sub
    | OpMul ->
        metaset.Mul
    | OpDiv ->
        metaset.Div
    | OpMod ->
        metaset.Mod
    | OpPow ->
        metaset.Pow
    | OpConcat ->
        metaset.Concat
    | OpEq ->
        metaset.Eq
    | OpNe ->
        metaset.Ne
    | OpLt ->
        metaset.Lt
    | OpLe ->
        metaset.Le
    | OpGt ->
        metaset.Gt
    | OpGe ->
        metaset.Ge
    | OpAnd ->
        metaset.And
    | OpOr ->
        metaset.Or
    | OpInd ->
        metaset.Index
    | OpMethInd ->
        metaset.Index

let rec getMetamethodSet (env : TypeEnvironment) (ty : Type) : MetamethodSet =
    match ty with
    | TupleTy(fst :: _) ->
        getMetamethodSet env fst
    | DeducedTy(_,temp) ->
        getMetamethodSet env temp
    | UserDefinedTy(x) ->
        match env.typeMap.TryFind x with
        | Some (y) ->
            getMetamethodSet env y
        | None ->
            //HACK: this shouldn't get hit the way we are currently calling the function
            //but it might be more robust to instead return a metamethod set corresponding to the
            //unknown type (every method takes unknown and returns unknown).
            failwith "bllll"
    | NillableTy(x) ->
        { 
        getMetamethodSet env x with 
            Or = Some ("set default value", x, x)
        }
    | NumberTy ->
        {
            MetamethodSet.empty with
                Add = Some ("Add two numbers",NumberTy,NumberTy)
                Sub = Some ("Subtract right-hand number from left-hand number",NumberTy,NumberTy)
                Mul = Some ("Multiply two numbers",NumberTy,NumberTy)
                Div = Some ("Divide left-hand number by right-hand number",NumberTy,NumberTy)
                Mod = Some ("Mod left-hand number by right-hand number",NumberTy,NumberTy)
                Pow = Some ("Raise left-hand number to right-hand number's power",NumberTy,NumberTy)
                Unm = Some ("Negate number",NumberTy)
                Eq = Some ("are these two numbers equal?",NillableTy(NumberTy),BoolTy)
                Ne = Some ("are these two numbers unequal?",NillableTy(NumberTy),BoolTy)
                Lt = Some ("is the left number less than the right number?",NumberTy,BoolTy)
                Le = Some ("is the left number less than or equal to the right number?",NumberTy,BoolTy)
                Gt = Some ("is the left number greater than the right number?",NumberTy,BoolTy)
                Ge = Some ("is the left number less than or equal to the right number?",NumberTy,BoolTy)
        }
    | StringTy ->
        {
            MetamethodSet.empty with
                Concat = Some ("concatenate two strings", StringTy, StringTy)
                Len = Some ("get the length of the string", NumberTy)
                Eq = Some ("are these two strings equal?",NillableTy(StringTy),BoolTy)
                Ne = Some ("are these two strings unequal?",NillableTy(StringTy),BoolTy)
                Lt = Some ("is the left string lexicographically less than the right string?",StringTy,BoolTy)
                Le = Some ("is the left number lexicographically less than or equal to the right number?",StringTy,BoolTy)
                Gt = Some ("is the left number lexicographically greater than the right number?",StringTy,BoolTy)
                Ge = Some ("is the left number lexicographically less than or equal to the right number?",StringTy,BoolTy)
        }
    | BoolTy ->
        {
            MetamethodSet.empty with
                And = Some ("boolean and", BoolTy, BoolTy)
                Or = Some ("boolean or", BoolTy, BoolTy)
                Not = Some ("boolean not", BoolTy)
        }        
    | RecordTy(_,_,_,metaset,_,_,_) ->
        metaset
    | UnknownTy ->
        {
            Add = Some("add",UnknownTy,UnknownTy)
            Sub = Some("sub",UnknownTy,UnknownTy)
            Mul = Some("mul",UnknownTy,UnknownTy)
            Div = Some("div",UnknownTy,UnknownTy)
            Mod = Some("mod",UnknownTy,UnknownTy)
            Pow = Some("pow",UnknownTy,UnknownTy)
            Unm = Some("negate",UnknownTy)
            Concat = Some("..",UnknownTy,UnknownTy)
            Len = Some("len", UnknownTy)
            Eq = Some("equal",UnknownTy,UnknownTy)
            Ne = Some("not equal",UnknownTy,UnknownTy)
            Lt = Some("less than",UnknownTy,UnknownTy)
            Le = Some("less than or equal",UnknownTy,UnknownTy)
            Gt = Some("greater than",UnknownTy,UnknownTy)
            Ge = Some("greater or equal",UnknownTy,UnknownTy)
            And = Some("and",UnknownTy,UnknownTy)
            Or = Some("or",UnknownTy,UnknownTy)
            Not = Some("not",UnknownTy)
            Index = Some("index",UnknownTy,UnknownTy)
            Call = None
        }        
    | _ ->
        MetamethodSet.empty

/// Used for when someone tries to override a method using an incorrect 
/// type signature.
///
/// error message, fileName, rng
exception StructuralSubtypingError of string*string*(int*int)

let refCheckStructuralSubtyping =    
    ref (fun _ _ _ -> ())

let isStructuralSubtypeOf (env : TypeEnvironment) (a : Type) (b : Type) =
    try
        !refCheckStructuralSubtyping env a b
        true,""
    with
    | StructuralSubtypingError(msg, fileName, rng)->
        false,"\n" + msg

type Field with

    static member OfType(ty : Type) =
        {
            desc = ""
            ty = ty
            loc = NoLocation
            isConst = false
        }

type Type with
    static member InterpretFunctionAnnotation (annotation : Option<Annotation>) : Option< string*List<string*string*Type>*List<string*Type> > =
        let (desc,paramList,retList,varList) = 
            match annotation with
            | Some(desc,paramList,retList,varList) ->
                desc,paramList,retList,varList
            | None ->
                EmptyAnnotation

        if paramList.Length > 0 || retList.Length > 0 then
            let getParamInfo ((name,desc,tyName) : ParamAnnotation) =
                (name,desc,Type.FromString tyName)
            let typedFormals = List.map getParamInfo paramList
            let typedRets = List.map (fun (name,desc) -> desc,Type.FromString name) retList
            Some (desc,typedFormals,typedRets)
        else
            None

    static member InterpretVarAnnotation (annotation : Option<Annotation>) (length : int) : List<string>*List<Option<Type>>*List<bool> =
        let (desc,fieldList) =
            match annotation with
            | Some(desc,_,_,fieldList) ->
                desc,fieldList
            | None ->
                "",[] 

        let opTypeNames, descriptions, isConstList =
            if fieldList.Length = 0 then
                [None], [desc], [false]
            else
                List.unzip3 fieldList

        let mapTypeName (opTypeName : Option<string>) =
            if opTypeName.IsSome then
                Some( Type.FromString opTypeName.Value )
            else
                None

        let types = List.map mapTypeName opTypeNames
        let descriptions = sizeListTo descriptions length ""
        let isConstList = sizeListTo isConstList length false
        let types = sizeListTo types length None
        descriptions,types,isConstList

    static member IsEqual (env : TypeEnvironment) (a : Type) (b : Type) =
        (fst (Type.IsSubtypeOf env a b)) && (fst (Type.IsSubtypeOf env b a))

    static member IsSubtypeOf (env : TypeEnvironment) (a : Type) (b : Type) : bool*string =
        let edges = env.edges

        let visited = ref( new Set<string>([]) )

        let rec reachable (src : string) (target : string) =
            if src = target then
                true
            elif (!visited).Contains src then
                false
            else
                visited := (!visited).Add(src)
                let children = edges.Item src
                List.fold (fun state child -> state || (reachable child target)) false children

        match (Type.Unfold env a,Type.Unfold env b) with
        | (UnknownTy,_)
        | (_, UnknownTy) ->
            true, ""
        | (_, NewFieldTy) ->
            true, ""
        | (BoolTy, BoolTy)
        | (NumberTy, NumberTy)
        | (NilTy, NilTy) ->
            true, ""
        | (a, NillableTy(b)) 
        | (NillableTy(a),NillableTy(b)) when fst (Type.IsSubtypeOf env a b) ->
            true, ""
        | (NilTy, NillableTy(_)) ->
            true, ""
        | (DeducedTy(_,a), b) when fst (Type.IsSubtypeOf env a b) ->
            true, ""
        | (a, DeducedTy(b,_)) when fst (Type.IsSubtypeOf env a b) ->
            true, ""
        | (TupleTy(a :: _),b) 
        | (a, TupleTy(b :: _)) when fst (Type.IsSubtypeOf env a b) ->
            true, ""
        | ((RecordTy(nameA,_,isStrucA,_,_,_,_) as tyA), (RecordTy(nameB,_,isStrucB,_,_,_,_) as tyB)) ->
            if isStrucA && isStrucB then
                isStructuralSubtypeOf env tyA tyB
            elif isStrucA || isStrucB then
                false, ""
            else
                reachable nameA nameB, ""
        | (CallableTy(_,paramsA,retsA,_,_), FunctionTy(_,paramsB,retsB,_,_)) ->
            let maxLen = max paramsA.Length paramsB.Length
            let paramsA = sizeListTo paramsA maxLen ("","",NilTy)
            let paramsB = sizeListTo paramsB maxLen ("","",NilTy)

            let maxLen = max retsA.Length retsB.Length
            let retsA = sizeListTo retsA maxLen ("",NilTy)
            let retsB = sizeListTo retsB maxLen ("",NilTy)

            let isParamNotContra ((s0A,s1A,tA),(s0B, s1B, tB),i) =
                let res,subExplanation = Type.IsSubtypeOf env tB tA
                
                if res then
                    None
                else
                    Some("\ntype of " + (orderStr i) + " argument (" + tA.ToString() + ") is not a supertype of type of " + tB.ToString() + subExplanation)

            let notContraExplanation = List.tryPick isParamNotContra (List.zip3 paramsA paramsB [1..paramsA.Length])
            
            let isRetNotCov ((s0A,tyA),(s0B,tyB),i) =
                let res, subExplanation = Type.IsSubtypeOf env tyA tyB 
                            
                if res then
                    None
                else
                    Some("\ntype of " + (orderStr i) + " return value (" + tyA.ToString() + ") is not a subtype of " + tyB.ToString() + subExplanation)

                
            let notCovExplanation = List.tryPick isRetNotCov (List.zip3 retsA retsB [1..retsA.Length])
            
            if notContraExplanation.IsSome then
                false, notContraExplanation.Value
            elif notCovExplanation.IsSome then
                false, notCovExplanation.Value
            else
                true, ""
            //paramsContra && retsCov
        | _ ->
            false, ""



/// TODO: handle metamethods
/// This should be done once the type environment construction is complete
/// since fields, methods, and subtyping info is collected in separate phases
/// and we do not want to complicate things by weaving in structural subtype checking
let checkStructuralSubtyping (env : TypeEnvironment) (a : Type) (b : Type) =
    //TODO: this is backwards... a's and b's need to be switched

    match (a,b) with
    | (UnknownTy, RecordTy(_,_,_,_,_,_,_)) 
    | (RecordTy(_,_,_,_,_,_,_), UnknownTy) 
    | (UnknownTy,UnknownTy) ->
        ()
    | (RecordTy(nameA,_,_,metamethodsA,fieldsA,methodsA,(fileA,rngA)), RecordTy(nameB,_,_,metamethodsB,fieldsB,methodsB,(fileB,rngB))) ->
        let compatMethod methNameB (methB : Method) =
            if not (methodsA.ContainsKey methNameB) then
                //TODO: we need the record type to carry defLocation here
                raise( StructuralSubtypingError("class does not contain " + methNameB + " method from supertype",fileA,rngA) )
            else
                let methA = methodsA.Item methNameB
                let (methFileA,methRngA) = methA.loc
                if not (Type.IsEqual env methA.ty methB.ty) then
                    raise( StructuralSubtypingError(methNameB + " does not match between " + nameA + " and " + nameB, methFileA, methRngA) )
        
        Map.iter compatMethod methodsB

        let compatField fieldNameB fieldB =
            if not (fieldsA.ContainsKey fieldNameB) then
                 raise( StructuralSubtypingError("record does not contain " + fieldNameB + " field ", fileA,rngA) )
            else
                let fieldA = fieldsA.Item fieldNameB
                let (fieldFileA,fieldRngA) = fieldA.loc
                if fieldA.isConst && fieldB.isConst then
                    let isSub,expl = Type.IsSubtypeOf env fieldA.ty fieldB.ty
                    if not isSub then
                        raise( StructuralSubtypingError("type of " + fieldNameB + ", " + fieldA.ty.ToString() + ", is not a subtype of " + fieldB.ty.ToString() + expl, fieldFileA, fieldRngA) )
                elif (not fieldA.isConst) && (not fieldB.isConst) then
                    if not (Type.IsEqual env fieldA.ty fieldB.ty) then
                         raise( StructuralSubtypingError(fieldNameB + " does not match between " + nameA + " and " + nameB, fieldFileA, fieldRngA) )
                elif (not fieldA.isConst) && fieldB.isConst then
                    raise( StructuralSubtypingError(fieldNameB + " is const in parent and not child.", fieldFileA, fieldRngA) )
                else
                    raise( StructuralSubtypingError(fieldNameB + " is const in child and not parent.", fieldFileA, fieldRngA) )
                    
        Map.iter compatField fieldsB
    | (_,_) ->
        failwith "only record types should be given nominal subtyping relations"

refCheckStructuralSubtyping := checkStructuralSubtyping

type TypeEnvironment with
    member this.CheckStructuralSubtyping () =
        // Given the name of a type, along with a list of all
        // outgoing edges for that type, check that each edge
        // satisfies structural subtyping
        let checkType srcName outEdges =
            let checkEdge dstName =
                let srcType = this.typeMap.Item srcName
                let dstType = this.typeMap.Item dstName
                checkStructuralSubtyping this srcType dstType

            List.iter checkEdge outEdges
        Map.iter checkType this.edges
            
/// TODO: structural subtyping is checked automatically; we should remove this
///
/// covers ctxt1 with ctxt2, but raises an error if any of the 
/// items in ctxt1 are not equal to the corresponding item in w2
/// useful for method inheritence, because method subtyping is invariant
/// w.r.t. object subtyping
//let overrid (env : TypeEnvironment) (ctxt1 : Map<string,Type>) (ctxt2 : Map<string,Type>) =
//    let isInvariant (name,ty) =
//        if not (Type.IsDefEqual env (ctxt1.Item name) ty) then
//            
//            raise( OverriddenMethodTypeError("" )