-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
91 lines (80 loc) · 2.28 KB
/
context.go
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
package generic
import (
"fmt"
)
type InferenceContext struct {
ExpectedType Type
IsAssignment bool
IsFunctionArg bool
IsReturnValue bool
}
func NewInferenceContext(options ...func(*InferenceContext)) *InferenceContext {
ctx := &InferenceContext{}
for _, opt := range options {
opt(ctx)
}
return ctx
}
func WithExpectedType(t Type) func(*InferenceContext) {
return func(ctx *InferenceContext) {
ctx.ExpectedType = t
}
}
func WithAssignment() func(*InferenceContext) {
return func(ctx *InferenceContext) {
ctx.IsAssignment = true
}
}
func WithFunctionArg() func(*InferenceContext) {
return func(ctx *InferenceContext) {
ctx.IsFunctionArg = true
}
}
func WithReturnValue() func(*InferenceContext) {
return func(ctx *InferenceContext) {
ctx.IsReturnValue = true
}
}
// InferType infers the type of an expression.
func checkInterfaceCompatibility(iface, expected *InterfaceType) error {
for name, method := range expected.Methods {
ifaceMethod, ok := iface.Methods[name]
if !ok {
return fmt.Errorf("missing method %s", name)
}
if !MethodsEqual(method, ifaceMethod) {
return fmt.Errorf("method %s has incompatible signature", name)
}
}
return nil
}
// checkFunctionCompatibility checks if two function types are compatible.
func checkFunctionCompatibility(func1, func2 *FunctionType) error {
if len(func1.ParamTypes) != len(func2.ParamTypes) {
return fmt.Errorf("expected %d parameters, got %d", len(func2.ParamTypes), len(func1.ParamTypes))
}
for i, param1 := range func1.ParamTypes {
if !TypesEqual(param1, func2.ParamTypes[i]) {
return fmt.Errorf("parameter type mismatch at position %d", i)
}
}
if !TypesEqual(func1.ReturnType, func2.ReturnType) {
return fmt.Errorf("return type mismatch")
}
if func1.IsVariadic != func2.IsVariadic {
return fmt.Errorf("variadic parameter mismatch")
}
return nil
}
// checkTupleCompatibility checks if two tuple types are compatible.
func checkTupleCompatibility(tuple1, tuple2 *TupleType) error {
if len(tuple1.Types) != len(tuple2.Types) {
return fmt.Errorf("tuple length mismatch. expected %d elements, got %d", len(tuple2.Types), len(tuple1.Types))
}
for i, type1 := range tuple1.Types {
if !TypesEqual(type1, tuple2.Types[i]) {
return fmt.Errorf("element type mismatch at position %d", i)
}
}
return nil
}