forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonRange.cs
More file actions
425 lines (346 loc) · 13.2 KB
/
PythonRange.cs
File metadata and controls
425 lines (346 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// Copyright (c) Pawel Jasinski.
//
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace IronPython.Runtime {
[PythonType("range")]
[DontMapIEnumerableToContains]
public sealed class PythonRange : IEnumerable<int>, ICodeFormattable, IReversible {
internal readonly BigInteger _start;
internal readonly BigInteger _stop;
internal readonly BigInteger _step;
internal readonly BigInteger _length;
public PythonRange([AllowNull] object stop) : this(0, stop, 1) { }
public PythonRange([AllowNull] object start, [AllowNull] object stop) : this(start, stop, 1) { }
public PythonRange([AllowNull] object start, [AllowNull] object stop, [AllowNull] object step) {
this.start = AsIndex(start, out _start);
this.stop = AsIndex(stop, out _stop);
this.step = AsIndex(step, out _step);
if (_step == 0) {
throw PythonOps.ValueError("step must not be zero");
}
_length = GetLengthHelper(_start, _stop, _step);
static BigInteger GetLengthHelper(BigInteger start, BigInteger stop, BigInteger step) {
BigInteger length = 0;
if (step > 0) {
if (start < stop) {
length = (stop - start + step - 1) / step;
}
} else {
if (start > stop) {
length = (stop - start + step + 1) / step;
}
}
return length;
}
}
private static object AsIndex(object? obj, out BigInteger big) {
var index = PythonOps.Index(obj);
if (index is int i) {
big = i;
} else if (index is BigInteger bi) {
big = bi;
} else {
throw new InvalidOperationException();
}
return index;
}
public object? start { get; private set; }
public object? stop { get; private set; }
public object? step { get; private set; }
public PythonTuple __reduce__() {
return PythonTuple.MakeTuple(
DynamicHelpers.GetPythonType(this),
PythonTuple.MakeTuple(start, stop, step)
);
}
public int __len__() {
return (int)_length;
}
public object this[int index] => this[(BigInteger)index];
public object this[BigInteger index] {
get {
if (index < 0) index += _length;
if (index >= _length || index < 0)
throw PythonOps.IndexError("range object index out of range");
return index * _step + _start;
}
}
public object this[[AllowNull] object index] {
get {
if (PythonOps.TryToIndex(index, out BigInteger bi)) {
return this[bi];
}
throw PythonOps.TypeError("range indices must be integers or slices, not {0}", PythonOps.GetPythonTypeName(index));
}
}
public object this[[NotNone] Slice slice] {
get {
slice.indices(_length, out BigInteger ostart, out BigInteger ostop, out BigInteger ostep);
return new PythonRange(Compute(ostart), Compute(ostop), _step * ostep);
BigInteger Compute(BigInteger index) {
return index * _step + _start;
}
}
}
public bool __eq__([NotNone] PythonRange other) {
if (_length != other._length) {
return false;
}
if (_length == 0) {
return true;
}
if (_start != other._start) {
return false;
}
if (_length == 1) {
return true;
}
if (Last() != other.Last()) {
return false;
}
return _step == other._step;
}
[return: MaybeNotImplemented]
public object __eq__(object? other) => other is PythonRange range ? __eq__(range) : NotImplementedType.Value;
public int __hash__() {
if (_length == 0) {
return 0;
}
var hash = _start.GetHashCode();
hash ^= _length.GetHashCode();
if (_length > 1) {
hash ^= _step.GetHashCode();
}
return hash;
}
public bool __contains__(CodeContext context, object? item) {
if (TryConvertToInt(item, out BigInteger intItem)) {
return IndexOf(intItem) != -1;
}
return IndexOf(context, item) != -1;
}
private static bool TryConvertToInt(object? value, out BigInteger converted) {
if (value is int i) {
converted = i;
return true;
}
if (value is BigInteger bi) {
converted = bi;
return true;
}
if (value is long l) {
converted = l;
return true;
}
converted = 0;
return false;
}
private int CountOf(BigInteger value) {
if (_length == 0) {
return 0;
}
if (_start < _stop) {
if (value < _start || value >= _stop) {
return 0;
}
} else if (_start > _stop) {
if (value > _start || value <= _stop) {
return 0;
}
}
return (value - _start) % _step == 0 ? 1 : 0;
}
private int CountOf(CodeContext context, object? obj) {
var pythonContext = context.LanguageContext;
var count = 0;
foreach (var i in (IEnumerable)this) {
if ((bool)pythonContext.Operation(PythonOperationKind.Equal, obj, i)) {
count++;
}
}
return count;
}
private BigInteger IndexOf(BigInteger value) {
if (CountOf(value) == 0) {
return -1;
}
return (value - _start) / _step;
}
private int IndexOf(CodeContext context, object? obj) {
var idx = 0;
var pythonContext = context.LanguageContext;
foreach (var i in (IEnumerable)this) {
if ((bool)pythonContext.Operation(PythonOperationKind.Equal, obj, i)) {
return idx;
}
idx++;
}
return -1;
}
public object count(CodeContext context, object? value) {
if (TryConvertToInt(value, out BigInteger i)) {
return CountOf(i);
}
return CountOf(context, value);
}
public BigInteger index(CodeContext context, object? value) {
BigInteger idx;
if (TryConvertToInt(value, out BigInteger intValue)) {
idx = IndexOf(intValue);
if (idx == -1) {
throw PythonOps.ValueError("{0} is not in range", intValue);
}
} else {
idx = IndexOf(context, value);
if (idx == -1) {
throw PythonOps.ValueError("sequence.index(x): x not in sequence");
}
}
return idx;
}
private BigInteger Last() {
return _start + (_length - 1) * _step;
}
public IEnumerator __iter__() {
if (IsInt(_start) && IsInt(_stop) && IsInt(_step) && IsInt(_length)) {
return new PythonRangeIterator(this);
} else {
return new PythonLongRangeIterator(this);
}
static bool IsInt(BigInteger val) => int.MinValue <= val && val <= int.MaxValue;
}
public IEnumerator __reversed__()
=> new PythonRange(Last(), _start - _step, -_step).__iter__();
IEnumerator IEnumerable.GetEnumerator() => __iter__();
IEnumerator<int> IEnumerable<int>.GetEnumerator() => new PythonRangeIterator(this);
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
return _step == 1 ?
string.Format("range({0}, {1})", start, stop) :
string.Format("range({0}, {1}, {2})", start, stop, step);
}
#endregion
}
[PythonType("range_iterator")]
public sealed class PythonRangeIterator : IEnumerable, IEnumerator<int> {
private readonly PythonRange _range;
private int _value;
private int _position;
internal PythonRangeIterator(PythonRange range) {
Debug.Assert(range._start.AsInt32(out _) && range._stop.AsInt32(out _) && range._step.AsInt32(out _) && range._length <= int.MaxValue);
_range = range;
_value = unchecked((int)range._start - (int)range._step); // this could overflow but we'll overflow back to the correct value on MoveNext
}
[PythonHidden]
public object Current => ScriptingRuntimeHelpers.Int32ToObject(_value);
[PythonHidden]
public bool MoveNext() {
if (_position >= (int)_range._length) {
return false;
}
_position++;
_value = unchecked(_value + (int)_range._step);
return true;
}
[PythonHidden]
public void Reset() {
_value = unchecked((int)_range._start - (int)_range._step); // this could overflow but we'll overflow back to the correct value on MoveNext
_position = 0;
}
public PythonTuple __reduce__(CodeContext/*!*/ context) {
context.TryLookupBuiltin("iter", out object? iter);
return PythonTuple.MakeTuple(
iter,
PythonTuple.MakeTuple(_range),
_position
);
}
public void __setstate__(int position) {
if (position < 0) position = 0;
else if (position > (int)_range._length) position = (int)_range._length;
_position = position;
_value = unchecked((int)_range._start + (_position - 1) * (int)_range._step); // this could overflow but we'll overflow back to the correct value on MoveNext
}
#region IEnumerator<int> Members
int IEnumerator<int>.Current => _value;
#endregion
#region IDisposable Members
[PythonHidden]
public void Dispose() { }
#endregion
#region IEnumerable Members
[PythonHidden]
public IEnumerator GetEnumerator() => this;
#endregion
public int __length_hint__() {
return (int)(_range._length - _position);
}
}
[PythonType("longrange_iterator")]
public sealed class PythonLongRangeIterator : IEnumerable, IEnumerator<BigInteger> {
private readonly PythonRange _range;
private BigInteger _value;
private BigInteger _position;
internal PythonLongRangeIterator(PythonRange range) {
_range = range;
_value = range._start - range._step;
}
[PythonHidden]
public object Current => _value;
[PythonHidden]
public bool MoveNext() {
if (_position >= _range._length) {
return false;
}
_position++;
_value = _value + _range._step;
return true;
}
[PythonHidden]
public void Reset() {
_value = _range._start - _range._step;
_position = 0;
}
public PythonTuple __reduce__(CodeContext context) {
context.TryLookupBuiltin("iter", out object? iter);
return PythonTuple.MakeTuple(
iter,
PythonTuple.MakeTuple(_range),
_position
);
}
public void __setstate__(BigInteger position) {
if (position < 0) position = 0;
else if (position > _range._length) position = _range._length;
_position = position;
_value = _range._start + (_position - 1) * _range._step;
}
#region IEnumerator<BigInteger> Members
BigInteger IEnumerator<BigInteger>.Current => _value;
#endregion
#region IDisposable Members
[PythonHidden]
public void Dispose() { }
#endregion
#region IEnumerable Members
[PythonHidden]
public IEnumerator GetEnumerator() => this;
#endregion
public BigInteger __length_hint__() => _range._length - _position;
}
}