L4.check

  1from collections.abc import Mapping
  2from functools import partial
  3
  4from .syntax import (
  5    Abstraction,
  6    And,
  7    Application,
  8    Arrow,
  9    Bool,
 10    Boolean,
 11    Box,
 12    BoxRead,
 13    BoxWrite,
 14    Branch,
 15    Identifier,
 16    If,
 17    Immediate,
 18    Int,
 19    Join,
 20    Let,
 21    Primitive,
 22    Product,
 23    Program,
 24    Project,
 25    Reference,
 26    Sole,
 27    Term,
 28    Trivial,
 29    Tuple,
 30    TupleGet,
 31    Type,
 32)
 33
 34
 35def equivalent(
 36    t1: Type,
 37    t2: Type,
 38) -> bool:
 39    recur = partial(equivalent)
 40
 41    match t1, t2:
 42        case Arrow(domain=d1, codomain=c1), Arrow(domain=d2, codomain=c2):
 43            return (
 44                recur(d1, d2)  # domain
 45                and recur(c1, c2)  # codomain
 46            )
 47
 48        case Int(), Int():
 49            return True
 50
 51        case Bool(), Bool():
 52            return True
 53
 54        case Trivial(), Trivial():
 55            return True
 56
 57        case Product(components=cs1), Product(components=cs2):
 58            return (
 59                len(cs1) == len(cs2) and all(recur(c1, c2) for c1, c2 in zip(cs1, cs2))  #
 60            )
 61
 62        case Box(content=c1), Box(content=c2):  # 2 boxes are the same if they share contents
 63            return recur(c1, c2)
 64
 65        case _:
 66            return False
 67
 68
 69def check_term(
 70    term: Term,
 71    expected: Type,
 72    gamma: Mapping[Identifier, Type],
 73) -> Type:
 74    infer = partial(infer_term, gamma=gamma)
 75
 76    actual = infer(term)
 77    if not equivalent(actual, expected):
 78        raise ValueError(f"type mismatch: expected {expected} but got {actual}")
 79
 80    return actual
 81
 82
 83def infer_term(
 84    term: Term,
 85    gamma: Mapping[Identifier, Type],
 86) -> Type:
 87    _infer = partial(infer_term, gamma=gamma)
 88    _check = partial(check_term, gamma=gamma)
 89
 90    match term:
 91        case Reference(name=name):
 92            match gamma.get(name):
 93                case None:
 94                    raise ValueError(f"unknown variable: {name}")
 95
 96                case type:
 97                    return type
 98
 99        case Abstraction(parameter=parameter, domain=domain, body=body):
100            return Arrow(
101                domain=domain,
102                codomain=_infer(body, gamma={**gamma, parameter: domain}),
103            )
104
105        case Application(target=target, argument=argument):
106            match _infer(target):
107                case Arrow(domain=domain, codomain=codomain):
108                    _check(argument, domain)
109                    return codomain
110
111                case target_type:
112                    raise ValueError(f"expected {target} to be {Arrow} not {target_type}")
113
114        case Immediate():
115            return Int()  # passes value to the type version
116
117        case Boolean():
118            return Bool()  # made it pass the value to the type
119
120        case Primitive(operator=operator, left=left, right=right):  # Should only add Ints
121            match operator:
122                case "+" | "-" | "*":
123                    _check(left, Int())
124                    _check(right, Int())
125                    return Int()
126
127        case Branch(
128            operator=operator, left=left, right=right, motive=motive, consequent=consequent, otherwise=otherwise
129        ):  # branch now only covers the comparison of Int types
130            match operator:
131                case "<" | "==":
132                    _check(left, Int())
133                    _check(right, Int())
134                    _check(consequent, motive)
135                    _check(otherwise, motive)
136                    return motive
137
138        case If(test=test, consequent=consequent, otherwise=otherwise):
139            _check(test, Bool())
140            consequent_type = _infer(consequent)
141            otherwise_type = _infer(otherwise)
142            if not equivalent(consequent_type, otherwise_type):
143                raise ValueError(f"branches have different types: {consequent_type} and {otherwise_type}")
144            return consequent_type
145
146        case And(left=left, right=right):  # used to be branch but for clarity now used to represent the and operator
147            # should only accept bools and return a bool
148            _check(left, Bool())
149            _check(right, Bool())
150            return Bool()
151
152        case Sole():
153            return Trivial()
154
155        case Tuple(components=components):
156            return Product(components=[_infer(component) for component in components])
157
158        case TupleGet(target=target, index=index):
159            match _infer(target):
160                case Product(components=components):
161                    if index not in range(len(components)):
162                        raise ValueError(f"invalid index: {index} in {components}")
163                    return components[index]
164
165                case target_type:
166                    raise ValueError(f"expected {target} to be {Product} not {target_type}")
167
168        case Join(components=components):
169            return Product(components=[_infer(component) for component in components])
170
171        case Project(target=target, index=index):
172            match _infer(target):
173                case Product(components=components):
174                    if index not in range(len(components)):
175                        raise ValueError(f"invalid index: {index} in {components}")
176
177                    return components[index]
178
179                case target_type:
180                    raise ValueError(f"expected {target} to be {Product} not {target_type}")
181
182        case BoxWrite(target=target, value=value):
183            # target has to be in box(content = T) and value has to be of type T
184            match _infer(target):
185                case Box(content=content_type):
186                    _check(value, content_type)
187                    return Trivial()  # writing is a side effect dont need to return meaningful stuff
188                case target_type:  # wrong T
189                    raise ValueError(f"expected {target} to be {Box} not {target_type}")
190
191        case BoxRead(target=target):  # return T
192            match _infer(target):  # target myst be a box with content=T
193                case Box(content=content_type):
194                    return content_type
195                case target_type:
196                    raise ValueError(f"expected {target} to be {Box} not {target_type}")
197
198        case Let(bindings=bindings, body=body):
199            # Evaluate each binding in sequence with progressively extended context
200            extended_gamma = dict(gamma)
201            for identifier, value_term in bindings:
202                # Infer type of the binding value using current gamma
203                value_type = infer_term(value_term, extended_gamma)
204                # Add binding to gamma for next bindings and body
205                extended_gamma[identifier] = value_type
206            # Evaluate body with all bindings in scope
207            return infer_term(body, extended_gamma)
208
209        case _:
210            raise ValueError(f"cannot infer type for term: {term}")
211
212
213def check_program(
214    program: Program,
215) -> None:
216    match program:
217        case Program(parameters=parameters, body=body):  # pragma: no branch
218            check_term(body, Int(), dict.fromkeys(parameters, Int()))
def equivalent(t1: Type, t2: Type) -> bool:
36def equivalent(
37    t1: Type,
38    t2: Type,
39) -> bool:
40    recur = partial(equivalent)
41
42    match t1, t2:
43        case Arrow(domain=d1, codomain=c1), Arrow(domain=d2, codomain=c2):
44            return (
45                recur(d1, d2)  # domain
46                and recur(c1, c2)  # codomain
47            )
48
49        case Int(), Int():
50            return True
51
52        case Bool(), Bool():
53            return True
54
55        case Trivial(), Trivial():
56            return True
57
58        case Product(components=cs1), Product(components=cs2):
59            return (
60                len(cs1) == len(cs2) and all(recur(c1, c2) for c1, c2 in zip(cs1, cs2))  #
61            )
62
63        case Box(content=c1), Box(content=c2):  # 2 boxes are the same if they share contents
64            return recur(c1, c2)
65
66        case _:
67            return False
def check_term(term: Term, expected: Type, gamma: Mapping[Identifier, Type]) -> Type:
70def check_term(
71    term: Term,
72    expected: Type,
73    gamma: Mapping[Identifier, Type],
74) -> Type:
75    infer = partial(infer_term, gamma=gamma)
76
77    actual = infer(term)
78    if not equivalent(actual, expected):
79        raise ValueError(f"type mismatch: expected {expected} but got {actual}")
80
81    return actual
def infer_term(term: Term, gamma: Mapping[Identifier, Type]) -> Type:
 84def infer_term(
 85    term: Term,
 86    gamma: Mapping[Identifier, Type],
 87) -> Type:
 88    _infer = partial(infer_term, gamma=gamma)
 89    _check = partial(check_term, gamma=gamma)
 90
 91    match term:
 92        case Reference(name=name):
 93            match gamma.get(name):
 94                case None:
 95                    raise ValueError(f"unknown variable: {name}")
 96
 97                case type:
 98                    return type
 99
100        case Abstraction(parameter=parameter, domain=domain, body=body):
101            return Arrow(
102                domain=domain,
103                codomain=_infer(body, gamma={**gamma, parameter: domain}),
104            )
105
106        case Application(target=target, argument=argument):
107            match _infer(target):
108                case Arrow(domain=domain, codomain=codomain):
109                    _check(argument, domain)
110                    return codomain
111
112                case target_type:
113                    raise ValueError(f"expected {target} to be {Arrow} not {target_type}")
114
115        case Immediate():
116            return Int()  # passes value to the type version
117
118        case Boolean():
119            return Bool()  # made it pass the value to the type
120
121        case Primitive(operator=operator, left=left, right=right):  # Should only add Ints
122            match operator:
123                case "+" | "-" | "*":
124                    _check(left, Int())
125                    _check(right, Int())
126                    return Int()
127
128        case Branch(
129            operator=operator, left=left, right=right, motive=motive, consequent=consequent, otherwise=otherwise
130        ):  # branch now only covers the comparison of Int types
131            match operator:
132                case "<" | "==":
133                    _check(left, Int())
134                    _check(right, Int())
135                    _check(consequent, motive)
136                    _check(otherwise, motive)
137                    return motive
138
139        case If(test=test, consequent=consequent, otherwise=otherwise):
140            _check(test, Bool())
141            consequent_type = _infer(consequent)
142            otherwise_type = _infer(otherwise)
143            if not equivalent(consequent_type, otherwise_type):
144                raise ValueError(f"branches have different types: {consequent_type} and {otherwise_type}")
145            return consequent_type
146
147        case And(left=left, right=right):  # used to be branch but for clarity now used to represent the and operator
148            # should only accept bools and return a bool
149            _check(left, Bool())
150            _check(right, Bool())
151            return Bool()
152
153        case Sole():
154            return Trivial()
155
156        case Tuple(components=components):
157            return Product(components=[_infer(component) for component in components])
158
159        case TupleGet(target=target, index=index):
160            match _infer(target):
161                case Product(components=components):
162                    if index not in range(len(components)):
163                        raise ValueError(f"invalid index: {index} in {components}")
164                    return components[index]
165
166                case target_type:
167                    raise ValueError(f"expected {target} to be {Product} not {target_type}")
168
169        case Join(components=components):
170            return Product(components=[_infer(component) for component in components])
171
172        case Project(target=target, index=index):
173            match _infer(target):
174                case Product(components=components):
175                    if index not in range(len(components)):
176                        raise ValueError(f"invalid index: {index} in {components}")
177
178                    return components[index]
179
180                case target_type:
181                    raise ValueError(f"expected {target} to be {Product} not {target_type}")
182
183        case BoxWrite(target=target, value=value):
184            # target has to be in box(content = T) and value has to be of type T
185            match _infer(target):
186                case Box(content=content_type):
187                    _check(value, content_type)
188                    return Trivial()  # writing is a side effect dont need to return meaningful stuff
189                case target_type:  # wrong T
190                    raise ValueError(f"expected {target} to be {Box} not {target_type}")
191
192        case BoxRead(target=target):  # return T
193            match _infer(target):  # target myst be a box with content=T
194                case Box(content=content_type):
195                    return content_type
196                case target_type:
197                    raise ValueError(f"expected {target} to be {Box} not {target_type}")
198
199        case Let(bindings=bindings, body=body):
200            # Evaluate each binding in sequence with progressively extended context
201            extended_gamma = dict(gamma)
202            for identifier, value_term in bindings:
203                # Infer type of the binding value using current gamma
204                value_type = infer_term(value_term, extended_gamma)
205                # Add binding to gamma for next bindings and body
206                extended_gamma[identifier] = value_type
207            # Evaluate body with all bindings in scope
208            return infer_term(body, extended_gamma)
209
210        case _:
211            raise ValueError(f"cannot infer type for term: {term}")
def check_program(program: L4.syntax.Program) -> None:
214def check_program(
215    program: Program,
216) -> None:
217    match program:
218        case Program(parameters=parameters, body=body):  # pragma: no branch
219            check_term(body, Int(), dict.fromkeys(parameters, Int()))