/
optional.mojo
359 lines (275 loc) · 11.8 KB
/
optional.mojo
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
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2024, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""Defines Optional, a type modeling a value which may or may not be present.
Optional values can be thought of as a type-safe nullable pattern.
Your value can take on a value or `None`, and you need to check
and explicitly extract the value to get it out.
```mojo
from collections import Optional
var a = Optional(1)
var b = Optional[Int](None)
if a:
print(a.value()[]) # prints 1
if b: # bool(b) is False, so no print
print(b.value()[])
var c = a.or_else(2)
var d = b.or_else(2)
print(c) # prints 1
print(d) # prints 2
```
"""
from utils import Variant
# TODO(27780): NoneType can't currently conform to traits
@value
struct _NoneType(CollectionElement):
pass
# ===----------------------------------------------------------------------===#
# Optional
# ===----------------------------------------------------------------------===#
@value
struct Optional[T: CollectionElement](CollectionElement, Boolable):
"""A type modeling a value which may or may not be present.
Optional values can be thought of as a type-safe nullable pattern.
Your value can take on a value or `None`, and you need to check
and explicitly extract the value to get it out.
Currently T is required to be a `CollectionElement` so we can implement
copy/move for Optional and allow it to be used in collections itself.
```mojo
from collections import Optional
var a = Optional(1)
var b = Optional[Int](None)
if a:
print(a.value()[]) # prints 1
if b: # bool(b) is False, so no print
print(b.value()[])
var c = a.or_else(2)
var d = b.or_else(2)
print(c) # prints 1
print(d) # prints 2
```
Parameters:
T: The type of value stored in the Optional.
"""
# Fields
# _NoneType comes first so its index is 0.
# This means that Optionals that are 0-initialized will be None.
alias _type = Variant[_NoneType, T]
var _value: Self._type
# ===-------------------------------------------------------------------===#
# Life cycle methods
# ===-------------------------------------------------------------------===#
fn __init__(inout self):
"""Construct an empty Optional."""
self._value = Self._type(_NoneType())
fn __init__(inout self, owned value: T):
"""Construct an Optional containing a value.
Args:
value: The value to store in the optional.
"""
self._value = Self._type(value^)
fn __init__(inout self, value: NoneType):
"""Construct an empty Optional.
Args:
value: Must be exactly `None`.
"""
self = Self()
# ===-------------------------------------------------------------------===#
# Operator dunders
# ===-------------------------------------------------------------------===#
fn __is__(self, other: NoneType) -> Bool:
"""Return `True` if the Optional has no value.
It allows you to use the following syntax: `if my_optional is None:`
Args:
other: The value to compare to (None).
Returns:
True if the Optional has no value and False otherwise.
"""
return not self.__bool__()
fn __isnot__(self, other: NoneType) -> Bool:
"""Return `True` if the Optional has a value.
It allows you to use the following syntax: `if my_optional is not None:`.
Args:
other: The value to compare to (None).
Returns:
True if the Optional has a value and False otherwise.
"""
return self.__bool__()
# ===-------------------------------------------------------------------===#
# Trait implementations
# ===-------------------------------------------------------------------===#
fn __bool__(self) -> Bool:
"""Return true if the Optional has a value.
Returns:
True if the optional has a value and False otherwise.
"""
return not self._value.isa[_NoneType]()
fn __invert__(self) -> Bool:
"""Return False if the optional has a value.
Returns:
False if the optional has a value and True otherwise.
"""
return not self
# ===-------------------------------------------------------------------===#
# Methods
# ===-------------------------------------------------------------------===#
@always_inline
fn value(
self: Reference[Self, _, _]
) -> Reference[T, self.is_mutable, self.lifetime]:
"""Retrieve a reference to the value of the Optional.
This check to see if the optional contains a value.
If you call this without first verifying the optional with __bool__()
eg. by `if my_option:` or without otherwise knowing that it contains a
value (for instance with `or_else`), the program will abort
Returns:
A reference to the contained data of the option as a Reference[T].
"""
if not self[].__bool__():
abort(".value() on empty Optional")
return self[].unsafe_value()
@always_inline
fn unsafe_value(
self: Reference[Self, _, _]
) -> Reference[T, self.is_mutable, self.lifetime]:
"""Unsafely retrieve a reference to the value of the Optional.
This doesn't check to see if the optional contains a value.
If you call this without first verifying the optional with __bool__()
eg. by `if my_option:` or without otherwise knowing that it contains a
value (for instance with `or_else`), you'll get garbage unsafe data out.
Returns:
A reference to the contained data of the option as a Reference[T].
"""
debug_assert(self[].__bool__(), ".value() on empty Optional")
return self[]._value[T]
@always_inline
fn _value_copy(self) -> T:
"""Unsafely retrieve the value out of the Optional.
Note: only used for Optionals when used in a parameter context
due to compiler bugs. In general, prefer using the public `Optional.value()`
function that returns a `Reference[T]`.
"""
debug_assert(self.__bool__(), ".value() on empty Optional")
return self._value[T]
fn take(inout self) -> T:
"""Move the value out of the Optional.
The caller takes ownership over the new value, which is moved
out of the Optional, and the Optional is left in an empty state.
This check to see if the optional contains a value.
If you call this without first verifying the optional with __bool__()
eg. by `if my_option:` or without otherwise knowing that it contains a
value (for instance with `or_else`), you'll get garbage unsafe data out.
Returns:
The contained data of the option as an owned T value.
"""
if not self.__bool__():
abort(".take() on empty Optional")
return self.unsafe_take()
fn unsafe_take(inout self) -> T:
"""Unsafely move the value out of the Optional.
The caller takes ownership over the new value, which is moved
out of the Optional, and the Optional is left in an empty state.
This check to see if the optional contains a value.
If you call this without first verifying the optional with __bool__()
eg. by `if my_option:` or without otherwise knowing that it contains a
value (for instance with `or_else`), the program will abort!
Returns:
The contained data of the option as an owned T value.
"""
debug_assert(self.__bool__(), ".unsafe_take() on empty Optional")
return self._value.unsafe_replace[_NoneType, T](_NoneType())
fn or_else(self, default: T) -> T:
"""Return the underlying value contained in the Optional or a default value if the Optional's underlying value is not present.
Args:
default: The new value to use if no value was present.
Returns:
The underlying value contained in the Optional or a default value.
"""
if self.__bool__():
return self._value[T]
return default
# ===----------------------------------------------------------------------===#
# OptionalReg
# ===----------------------------------------------------------------------===#
@register_passable("trivial")
struct OptionalReg[T: AnyRegType](Boolable):
"""A register-passable optional type.
This struct optionally contains a value. It only works with trivial register
passable types at the moment.
Parameters:
T: The type of value stored in the Optional.
"""
# Fields
alias _mlir_type = __mlir_type[`!kgen.variant<`, T, `, i1>`]
var _value: Self._mlir_type
# ===-------------------------------------------------------------------===#
# Life cycle methods
# ===-------------------------------------------------------------------===#
fn __init__(inout self):
"""Create an optional with a value of None."""
self = Self(None)
fn __init__(inout self, value: T):
"""Create an optional with a value.
Args:
value: The value.
"""
self._value = __mlir_op.`kgen.variant.create`[
_type = Self._mlir_type, index = Int(0).value
](value)
fn __init__(inout self, value: NoneType):
"""Create an optional without a value from a None literal.
Args:
value: The None value.
"""
self._value = __mlir_op.`kgen.variant.create`[
_type = Self._mlir_type, index = Int(1).value
](__mlir_attr.false)
# ===-------------------------------------------------------------------===#
# Operator dunders
# ===-------------------------------------------------------------------===#
fn __is__(self, other: NoneType) -> Bool:
"""Return `True` if the Optional has no value.
It allows you to use the following syntax: `if my_optional is None:`
Args:
other: The value to compare to (None).
Returns:
True if the Optional has no value and False otherwise.
"""
return not self.__bool__()
fn __isnot__(self, other: NoneType) -> Bool:
"""Return `True` if the Optional has a value.
It allows you to use the following syntax: `if my_optional is not None:`
Args:
other: The value to compare to (None).
Returns:
True if the Optional has a value and False otherwise.
"""
return self.__bool__()
# ===-------------------------------------------------------------------===#
# Trait implementations
# ===-------------------------------------------------------------------===#
fn __bool__(self) -> Bool:
"""Return true if the optional has a value.
Returns:
True if the optional has a value and False otherwise.
"""
return __mlir_op.`kgen.variant.is`[index = Int(0).value](self._value)
# ===-------------------------------------------------------------------===#
# Methods
# ===-------------------------------------------------------------------===#
@always_inline
fn value(self) -> T:
"""Get the optional value.
Returns:
The contained value.
"""
return __mlir_op.`kgen.variant.take`[index = Int(0).value](self._value)