This repository was archived by the owner on Mar 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 635
Expand file tree
/
Copy pathset.go
More file actions
443 lines (388 loc) · 13.2 KB
/
set.go
File metadata and controls
443 lines (388 loc) · 13.2 KB
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
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
package grumpy
import (
"fmt"
"reflect"
)
var (
// FrozenSetType is the object representing the Python 'set' type.
FrozenSetType = newBasisType("frozenset", reflect.TypeOf(FrozenSet{}), toFrozenSetUnsafe, ObjectType)
// SetType is the object representing the Python 'set' type.
SetType = newBasisType("set", reflect.TypeOf(Set{}), toSetUnsafe, ObjectType)
)
type setBase struct {
Object
dict *Dict
}
func (s *setBase) contains(f *Frame, key *Object) (bool, *BaseException) {
item, raised := s.dict.GetItem(f, key)
if raised != nil {
return false, raised
}
return item != nil, nil
}
func (s *setBase) isSubset(f *Frame, o *Object) (*Object, *BaseException) {
s2, raised := setFromSeq(f, o)
if raised != nil {
return nil, raised
}
return setCompare(f, compareOpLE, s, &s2.Object)
}
func (s *setBase) isSuperset(f *Frame, o *Object) (*Object, *BaseException) {
s2, raised := setFromSeq(f, o)
if raised != nil {
return nil, raised
}
return setCompare(f, compareOpGE, s, &s2.Object)
}
func (s *setBase) repr(f *Frame) (*Object, *BaseException) {
if f.reprEnter(&s.Object) {
return NewStr(fmt.Sprintf("%s(...)", s.typ.Name())).ToObject(), nil
}
repr, raised := Repr(f, s.dict.Keys(f).ToObject())
f.reprLeave(&s.Object)
if raised != nil {
return nil, raised
}
return NewStr(fmt.Sprintf("%s(%s)", s.typ.Name(), repr.Value())).ToObject(), nil
}
// Set represents Python 'set' objects.
type Set setBase
// NewSet returns an empty Set.
func NewSet() *Set {
return &Set{Object{typ: SetType}, NewDict()}
}
func toSetUnsafe(o *Object) *Set {
return (*Set)(o.toPointer())
}
// Add inserts key into s. If key already exists then does nothing.
func (s *Set) Add(f *Frame, key *Object) (bool, *BaseException) {
origin, raised := s.dict.putItem(f, key, None, true)
if raised != nil {
return false, raised
}
return origin == nil, nil
}
// Contains returns true if key exists in s.
func (s *Set) Contains(f *Frame, key *Object) (bool, *BaseException) {
return (*setBase)(s).contains(f, key)
}
// Remove erases key from s. If key is not in s then raises KeyError.
func (s *Set) Remove(f *Frame, key *Object) (bool, *BaseException) {
return s.dict.DelItem(f, key)
}
// ToObject upcasts s to an Object.
func (s *Set) ToObject() *Object {
return &s.Object
}
// Update inserts all elements in the iterable o into s.
func (s *Set) Update(f *Frame, o *Object) *BaseException {
raised := seqForEach(f, o, func(key *Object) *BaseException {
return s.dict.SetItem(f, key, None)
})
return raised
}
func setAdd(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "add", args, SetType, ObjectType); raised != nil {
return nil, raised
}
if _, raised := toSetUnsafe(args[0]).Add(f, args[1]); raised != nil {
return nil, raised
}
return None, nil
}
func setContains(f *Frame, seq, value *Object) (*Object, *BaseException) {
contains, raised := toSetUnsafe(seq).Contains(f, value)
if raised != nil {
return nil, raised
}
return GetBool(contains).ToObject(), nil
}
func setDiscard(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "discard", args, SetType, ObjectType); raised != nil {
return nil, raised
}
if _, raised := toSetUnsafe(args[0]).Remove(f, args[1]); raised != nil {
return nil, raised
}
return None, nil
}
func setEq(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpEq, (*setBase)(toSetUnsafe(v)), w)
}
func setGE(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpGE, (*setBase)(toSetUnsafe(v)), w)
}
func setGT(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpGT, (*setBase)(toSetUnsafe(v)), w)
}
func setInit(f *Frame, o *Object, args Args, _ KWArgs) (*Object, *BaseException) {
argc := len(args)
if argc > 1 {
return nil, f.RaiseType(TypeErrorType, fmt.Sprintf("set expected at most 1 arguments, got %d", argc))
}
s := toSetUnsafe(o)
if argc == 1 {
if raised := s.Update(f, args[0]); raised != nil {
return nil, raised
}
}
return None, nil
}
func setIsSubset(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "issubset", args, SetType, ObjectType); raised != nil {
return nil, raised
}
return (*setBase)(toSetUnsafe(args[0])).isSubset(f, args[1])
}
func setIsSuperset(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "issuperset", args, SetType, ObjectType); raised != nil {
return nil, raised
}
return (*setBase)(toSetUnsafe(args[0])).isSuperset(f, args[1])
}
func setIter(f *Frame, o *Object) (*Object, *BaseException) {
s := toSetUnsafe(o)
s.dict.mutex.Lock(f)
iter := &newDictKeyIterator(s.dict).Object
s.dict.mutex.Unlock(f)
return iter, nil
}
func setLE(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpLE, (*setBase)(toSetUnsafe(v)), w)
}
func setLen(f *Frame, o *Object) (*Object, *BaseException) {
return NewInt(toSetUnsafe(o).dict.Len()).ToObject(), nil
}
func setLT(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpLT, (*setBase)(toSetUnsafe(v)), w)
}
func setNE(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpNE, (*setBase)(toSetUnsafe(v)), w)
}
func setNew(f *Frame, t *Type, _ Args, _ KWArgs) (*Object, *BaseException) {
s := toSetUnsafe(newObject(t))
s.dict = NewDict()
return s.ToObject(), nil
}
func setRemove(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "remove", args, SetType, ObjectType); raised != nil {
return nil, raised
}
key := args[1]
if removed, raised := toSetUnsafe(args[0]).Remove(f, key); raised != nil {
return nil, raised
} else if !removed {
return nil, raiseKeyError(f, key)
}
return None, nil
}
func setRepr(f *Frame, o *Object) (*Object, *BaseException) {
return (*setBase)(toSetUnsafe(o)).repr(f)
}
func setUpdate(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "update", args, SetType, ObjectType); raised != nil {
return nil, raised
}
if raised := toSetUnsafe(args[0]).Update(f, args[1]); raised != nil {
return nil, raised
}
return None, nil
}
func initSetType(dict map[string]*Object) {
dict["add"] = newBuiltinFunction("add", setAdd).ToObject()
dict["discard"] = newBuiltinFunction("discard", setDiscard).ToObject()
dict["issubset"] = newBuiltinFunction("issubset", setIsSubset).ToObject()
dict["issuperset"] = newBuiltinFunction("issuperset", setIsSuperset).ToObject()
dict["remove"] = newBuiltinFunction("remove", setRemove).ToObject()
dict["update"] = newBuiltinFunction("update", setUpdate).ToObject()
SetType.slots.Contains = &binaryOpSlot{setContains}
SetType.slots.Eq = &binaryOpSlot{setEq}
SetType.slots.GE = &binaryOpSlot{setGE}
SetType.slots.GT = &binaryOpSlot{setGT}
SetType.slots.Hash = &unaryOpSlot{hashNotImplemented}
SetType.slots.Init = &initSlot{setInit}
SetType.slots.Iter = &unaryOpSlot{setIter}
SetType.slots.LE = &binaryOpSlot{setLE}
SetType.slots.Len = &unaryOpSlot{setLen}
SetType.slots.LT = &binaryOpSlot{setLT}
SetType.slots.NE = &binaryOpSlot{setNE}
SetType.slots.New = &newSlot{setNew}
SetType.slots.Repr = &unaryOpSlot{setRepr}
}
// FrozenSet represents Python 'set' objects.
type FrozenSet setBase
func toFrozenSetUnsafe(o *Object) *FrozenSet {
return (*FrozenSet)(o.toPointer())
}
// Contains returns true if key exists in s.
func (s *FrozenSet) Contains(f *Frame, key *Object) (bool, *BaseException) {
return (*setBase)(s).contains(f, key)
}
// ToObject upcasts s to an Object.
func (s *FrozenSet) ToObject() *Object {
return &s.Object
}
func frozenSetContains(f *Frame, seq, value *Object) (*Object, *BaseException) {
contains, raised := toFrozenSetUnsafe(seq).Contains(f, value)
if raised != nil {
return nil, raised
}
return GetBool(contains).ToObject(), nil
}
func frozenSetEq(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpEq, (*setBase)(toFrozenSetUnsafe(v)), w)
}
func frozenSetGE(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpGE, (*setBase)(toFrozenSetUnsafe(v)), w)
}
func frozenSetGT(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpGT, (*setBase)(toFrozenSetUnsafe(v)), w)
}
func frozenSetIsSubset(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "issubset", args, FrozenSetType, ObjectType); raised != nil {
return nil, raised
}
return (*setBase)(toFrozenSetUnsafe(args[0])).isSubset(f, args[1])
}
func frozenSetIsSuperset(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "issuperset", args, FrozenSetType, ObjectType); raised != nil {
return nil, raised
}
return (*setBase)(toFrozenSetUnsafe(args[0])).isSuperset(f, args[1])
}
func frozenSetIter(f *Frame, o *Object) (*Object, *BaseException) {
s := toFrozenSetUnsafe(o)
s.dict.mutex.Lock(f)
iter := &newDictKeyIterator(s.dict).Object
s.dict.mutex.Unlock(f)
return iter, nil
}
func frozenSetLE(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpLE, (*setBase)(toFrozenSetUnsafe(v)), w)
}
func frozenSetLen(f *Frame, o *Object) (*Object, *BaseException) {
return NewInt(toFrozenSetUnsafe(o).dict.Len()).ToObject(), nil
}
func frozenSetLT(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpLT, (*setBase)(toFrozenSetUnsafe(v)), w)
}
func frozenSetNE(f *Frame, v, w *Object) (*Object, *BaseException) {
return setCompare(f, compareOpNE, (*setBase)(toFrozenSetUnsafe(v)), w)
}
func frozenSetNew(f *Frame, t *Type, args Args, _ KWArgs) (*Object, *BaseException) {
argc := len(args)
if argc > 1 {
format := "frozenset expected at most 1 arguments, got %d"
return nil, f.RaiseType(TypeErrorType, fmt.Sprintf(format, argc))
}
s := toFrozenSetUnsafe(newObject(t))
s.dict = NewDict()
if argc == 1 {
raised := seqForEach(f, args[0], func(o *Object) *BaseException {
return s.dict.SetItem(f, o, None)
})
if raised != nil {
return nil, raised
}
}
return s.ToObject(), nil
}
func frozenSetRepr(f *Frame, o *Object) (*Object, *BaseException) {
return (*setBase)(toFrozenSetUnsafe(o)).repr(f)
}
func initFrozenSetType(dict map[string]*Object) {
dict["issubset"] = newBuiltinFunction("issubset", frozenSetIsSubset).ToObject()
dict["issuperset"] = newBuiltinFunction("issuperset", frozenSetIsSuperset).ToObject()
FrozenSetType.slots.Contains = &binaryOpSlot{frozenSetContains}
FrozenSetType.slots.Eq = &binaryOpSlot{frozenSetEq}
FrozenSetType.slots.GE = &binaryOpSlot{frozenSetGE}
FrozenSetType.slots.GT = &binaryOpSlot{frozenSetGT}
// TODO: Implement hash for frozenset.
FrozenSetType.slots.Hash = &unaryOpSlot{hashNotImplemented}
FrozenSetType.slots.Iter = &unaryOpSlot{frozenSetIter}
FrozenSetType.slots.LE = &binaryOpSlot{frozenSetLE}
FrozenSetType.slots.Len = &unaryOpSlot{frozenSetLen}
FrozenSetType.slots.LT = &binaryOpSlot{frozenSetLT}
FrozenSetType.slots.NE = &binaryOpSlot{frozenSetNE}
FrozenSetType.slots.New = &newSlot{frozenSetNew}
FrozenSetType.slots.Repr = &unaryOpSlot{frozenSetRepr}
}
func setCompare(f *Frame, op compareOp, v *setBase, w *Object) (*Object, *BaseException) {
var s2 *setBase
switch {
case w.isInstance(SetType):
s2 = (*setBase)(toSetUnsafe(w))
case w.isInstance(FrozenSetType):
s2 = (*setBase)(toFrozenSetUnsafe(w))
default:
return NotImplemented, nil
}
if op == compareOpGE || op == compareOpGT {
op = op.swapped()
v, s2 = s2, v
}
v.dict.mutex.Lock(f)
iter := newDictEntryIterator(v.dict)
g1 := newDictVersionGuard(v.dict)
len1 := v.dict.Len()
v.dict.mutex.Unlock(f)
s2.dict.mutex.Lock(f)
g2 := newDictVersionGuard(s2.dict)
len2 := s2.dict.Len()
s2.dict.mutex.Unlock(f)
result := (op != compareOpNE)
switch op {
case compareOpLT:
if len1 >= len2 {
return False.ToObject(), nil
}
case compareOpLE:
if len1 > len2 {
return False.ToObject(), nil
}
case compareOpEq, compareOpNE:
if len1 != len2 {
return GetBool(!result).ToObject(), nil
}
}
for entry := iter.next(); entry != nil; entry = iter.next() {
contains, raised := s2.contains(f, entry.key)
if raised != nil {
return nil, raised
}
if !contains {
result = !result
break
}
}
if !g1.check() || !g2.check() {
return nil, f.RaiseType(RuntimeErrorType, "set changed during iteration")
}
return GetBool(result).ToObject(), nil
}
func setFromSeq(f *Frame, seq *Object) (*setBase, *BaseException) {
switch {
case seq.isInstance(SetType):
return (*setBase)(toSetUnsafe(seq)), nil
case seq.isInstance(FrozenSetType):
return (*setBase)(toFrozenSetUnsafe(seq)), nil
}
o, raised := SetType.Call(f, Args{seq}, nil)
if raised != nil {
return nil, raised
}
return (*setBase)(toSetUnsafe(o)), nil
}