-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonValue.cs
More file actions
617 lines (509 loc) · 17.2 KB
/
Copy pathPythonValue.cs
File metadata and controls
617 lines (509 loc) · 17.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using DotPython.Compiler.Bytecode;
using DotPython.Language.Text;
namespace DotPython.Runtime.Managed.Execution;
internal abstract record PythonValue
{
internal abstract string ToDisplayString();
internal virtual string ToRepresentationString() => ToDisplayString();
}
internal sealed record PythonNoneValue : PythonValue
{
internal static PythonNoneValue Instance { get; } = new();
private PythonNoneValue() { }
internal override string ToDisplayString() => "None";
}
internal sealed record PythonTruthValue : PythonValue
{
internal static PythonTruthValue False { get; } = new(false);
internal static PythonTruthValue True { get; } = new(true);
private PythonTruthValue(bool value)
{
Value = value;
}
internal bool Value { get; }
internal static PythonTruthValue FromBoolean(bool value) => value ? True : False;
internal override string ToDisplayString() => Value ? "True" : "False";
}
internal sealed record PythonWholeNumberValue(BigInteger Value) : PythonValue
{
private const int LargestCachedValue = 256;
private const int SmallestCachedValue = -5;
private static readonly PythonWholeNumberValue[] CachedValues = CreateCachedValues();
internal static PythonWholeNumberValue Create(BigInteger value)
{
if (value >= SmallestCachedValue && value <= LargestCachedValue)
{
return CachedValues[(int)value - SmallestCachedValue];
}
return new PythonWholeNumberValue(value);
}
internal override string ToDisplayString() => Value.ToString(CultureInfo.InvariantCulture);
private static PythonWholeNumberValue[] CreateCachedValues()
{
var values = new PythonWholeNumberValue[LargestCachedValue - SmallestCachedValue + 1];
for (var value = SmallestCachedValue; value <= LargestCachedValue; value++)
{
values[value - SmallestCachedValue] = new PythonWholeNumberValue(value);
}
return values;
}
}
internal sealed record PythonFloatingPointValue(double Value) : PythonValue
{
internal override string ToDisplayString()
{
if (double.IsNaN(Value))
{
return "nan";
}
if (double.IsPositiveInfinity(Value))
{
return "inf";
}
if (double.IsNegativeInfinity(Value))
{
return "-inf";
}
var text = Value
.ToString("R", CultureInfo.InvariantCulture)
.Replace("E", "e", StringComparison.Ordinal);
return
text.Contains('.', StringComparison.Ordinal)
|| text.Contains('e', StringComparison.Ordinal)
? text
: $"{text}.0";
}
}
internal sealed record PythonComplexValue(Complex Value) : PythonValue
{
internal override string ToDisplayString()
{
var real = FormatComponent(Value.Real);
var imaginary = FormatComponent(Math.Abs(Value.Imaginary));
var sign = Value.Imaginary < 0 ? "-" : "+";
if (Value.Real == 0)
{
return $"{(Value.Imaginary < 0 ? "-" : string.Empty)}{imaginary}j";
}
return $"({real}{sign}{imaginary}j)";
}
private static string FormatComponent(double value)
{
var text = new PythonFloatingPointValue(value).ToDisplayString();
return text.EndsWith(".0", StringComparison.Ordinal) ? text[..^2] : text;
}
}
internal sealed record PythonTextValue(string Value) : PythonValue
{
internal override string ToDisplayString() => Value;
internal override string ToRepresentationString()
{
var delimiter =
Value.Contains('\'', StringComparison.Ordinal)
&& !Value.Contains('"', StringComparison.Ordinal)
? '"'
: '\'';
var builder = new StringBuilder().Append(delimiter);
foreach (var rune in Value.EnumerateRunes())
{
switch (rune.Value)
{
case '\\':
builder.Append("\\\\");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
case var value when value == delimiter:
builder.Append('\\').Append(value);
break;
case var value when IsPythonPrintable(rune):
builder.Append(rune.ToString());
break;
case <= byte.MaxValue:
builder.Append(CultureInfo.InvariantCulture, $"\\x{rune.Value:x2}");
break;
case <= char.MaxValue:
builder.Append(CultureInfo.InvariantCulture, $"\\u{rune.Value:x4}");
break;
default:
builder.Append(CultureInfo.InvariantCulture, $"\\U{rune.Value:x8}");
break;
}
}
return builder.Append(delimiter).ToString();
}
private static bool IsPythonPrintable(Rune rune)
{
if (rune.Value == ' ')
{
return true;
}
return Rune.GetUnicodeCategory(rune)
is not (
UnicodeCategory.Control
or UnicodeCategory.Format
or UnicodeCategory.Surrogate
or UnicodeCategory.PrivateUse
or UnicodeCategory.OtherNotAssigned
or UnicodeCategory.LineSeparator
or UnicodeCategory.ParagraphSeparator
or UnicodeCategory.SpaceSeparator
);
}
}
internal sealed record PythonByteSequenceValue(byte[] Value) : PythonValue
{
internal override string ToDisplayString()
{
var builder = new StringBuilder("b'");
foreach (var item in Value)
{
switch (item)
{
case (byte)'\\':
builder.Append("\\\\");
break;
case (byte)'\'':
builder.Append("\\'");
break;
case >= 32 and < 127:
builder.Append((char)item);
break;
default:
builder.Append(CultureInfo.InvariantCulture, $"\\x{item:x2}");
break;
}
}
return builder.Append('\'').ToString();
}
public bool Equals(PythonByteSequenceValue? other) =>
other is not null && Value.AsSpan().SequenceEqual(other.Value);
public override int GetHashCode()
{
var hash = new HashCode();
foreach (var item in Value)
{
hash.Add(item);
}
return hash.ToHashCode();
}
}
internal sealed record PythonBuiltinFunctionValue(
string Name,
Func<IReadOnlyList<PythonValue>, TextSpan, PythonValue> Invoke
) : PythonValue
{
internal override string ToDisplayString() => $"<built-in function {Name}>";
}
internal sealed record PythonBuiltinTypeValue(
string Name,
Func<IReadOnlyList<PythonValue>, TextSpan, PythonValue> Construct
) : PythonValue
{
internal override string ToDisplayString() => $"<class '{Name}'>";
}
internal interface PythonExternalObjectProtocol
{
PythonValue Call(IReadOnlyList<PythonValue> arguments, TextSpan span);
PythonValue CallWithKeywords(
IReadOnlyList<PythonValue> arguments,
IReadOnlyList<string> keywordNames,
IReadOnlyList<PythonValue> keywordValues,
TextSpan span
);
PythonValue GetAttribute(string name, TextSpan span);
PythonValue GetItem(PythonValue index, TextSpan span);
long GetHash(TextSpan span);
int GetLength(TextSpan span);
PythonTruthValue RichCompare(PythonValue other, PythonRichComparison comparison, TextSpan span);
string ToDisplayString();
string ToRepresentationString();
}
internal sealed record PythonExternalObjectValue(PythonExternalObjectProtocol Protocol)
: PythonValue
{
internal override string ToDisplayString() => Protocol.ToDisplayString();
internal override string ToRepresentationString() => Protocol.ToRepresentationString();
public bool Equals(PythonExternalObjectValue? other) => ReferenceEquals(this, other);
public override int GetHashCode() => RuntimeHelpers.GetHashCode(this);
}
internal sealed record PythonProtocolFunctionValue(
string Name,
Func<PythonValue?, IReadOnlyList<PythonValue>, PythonValue> Invoke
) : PythonValue
{
internal override string ToDisplayString() => $"<built-in function {Name}>";
}
internal sealed record PythonBoundMethodValue(
string Name,
PythonValue Target,
PythonProtocolFunctionValue Function
) : PythonValue
{
internal override string ToDisplayString() => $"<bound method {Name}>";
}
internal sealed record PythonDescriptorValue(
string Name,
Func<PythonValue, PythonValue> Get,
Action<PythonValue, PythonValue>? Set = null,
bool IsDataDescriptor = true
) : PythonValue
{
internal override string ToDisplayString() => $"<descriptor '{Name}'>";
}
internal sealed record PythonManagedTypeValue : PythonValue
{
internal PythonManagedTypeValue(
string name,
PythonManagedTypeValue? baseType = null,
Func<IReadOnlyList<PythonValue>, PythonValue>? construct = null
)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
Name = name;
BaseType = baseType;
Construct = construct;
}
internal Dictionary<string, PythonValue> Attributes { get; } = new(StringComparer.Ordinal);
internal PythonManagedTypeValue? BaseType { get; }
internal Func<IReadOnlyList<PythonValue>, PythonValue>? Construct { get; }
internal string Name { get; }
public bool Equals(PythonManagedTypeValue? other) => ReferenceEquals(this, other);
public override int GetHashCode() => RuntimeHelpers.GetHashCode(this);
internal override string ToDisplayString() => $"<class '{Name}'>";
}
internal sealed record PythonManagedObjectValue : PythonValue
{
internal PythonManagedObjectValue(PythonManagedTypeValue type, object? payload = null)
{
ArgumentNullException.ThrowIfNull(type);
Type = type;
Payload = payload;
}
internal Dictionary<string, PythonValue> Attributes { get; } = new(StringComparer.Ordinal);
internal object? Payload { get; }
internal PythonManagedTypeValue Type { get; }
public bool Equals(PythonManagedObjectValue? other) => ReferenceEquals(this, other);
public override int GetHashCode() => RuntimeHelpers.GetHashCode(this);
internal override string ToDisplayString() => $"<{Type.Name} object>";
}
internal sealed record PythonExceptionTypeValue(string Name) : PythonValue
{
internal override string ToDisplayString() => $"<class '{Name}'>";
}
internal sealed record PythonExceptionValue(string TypeName, string Message) : PythonValue
{
internal PythonExceptionValue? Cause { get; set; }
internal PythonExceptionValue? Context { get; set; }
internal bool SuppressContext { get; set; }
public bool Equals(PythonExceptionValue? other) => ReferenceEquals(this, other);
public override int GetHashCode() => RuntimeHelpers.GetHashCode(this);
internal override string ToDisplayString() => Message;
internal override string ToRepresentationString() =>
Message.Length == 0
? $"{TypeName}()"
: $"{TypeName}({new PythonTextValue(Message).ToRepresentationString()})";
}
internal sealed record PythonFunctionValue(
string Name,
PreparedPythonCode Code,
PythonGlobalNamespace Globals,
PythonCell[] Closure,
PythonValue[] Defaults
) : PythonValue
{
internal override string ToDisplayString() => $"<function {Name}>";
}
internal sealed record PythonBoundUserMethodValue(
string Name,
PythonManagedObjectValue Target,
PythonFunctionValue Function
) : PythonValue
{
internal override string ToDisplayString() => $"<bound method {Name}>";
}
internal sealed record PythonModuleValue(string Name, PythonGlobalNamespace Globals) : PythonValue
{
internal override string ToDisplayString() => $"<module '{Name}'>";
}
internal sealed record PythonRangeValue(BigInteger Start, BigInteger Stop, BigInteger Step)
: PythonValue
{
internal BigInteger Count =>
Step > 0
? (Stop > Start ? (Stop - Start + Step - 1) / Step : 0)
: (Start > Stop ? (Start - Stop - Step - 1) / (-Step) : 0);
internal override string ToDisplayString() =>
Step.IsOne ? $"range({Start}, {Stop})" : $"range({Start}, {Stop}, {Step})";
}
internal sealed record PythonEnumerateSourceValue(PythonIteratorValue Inner, BigInteger StartIndex)
: PythonValue
{
internal override string ToDisplayString() => "<enumerate>";
}
internal sealed record PythonZipSourceValue(PythonIteratorValue[] Inners) : PythonValue
{
internal override string ToDisplayString() => "<zip>";
}
internal sealed record PythonMapSourceValue(
Func<PythonValue[], PythonValue> Apply,
PythonIteratorValue[] Inners
) : PythonValue
{
internal override string ToDisplayString() => "<map>";
}
internal sealed record PythonFilterSourceValue(
Func<PythonValue, bool> Keep,
PythonIteratorValue Inner
) : PythonValue
{
internal override string ToDisplayString() => "<filter>";
}
internal sealed record PythonSetValue(List<PythonValue> Elements) : PythonValue
{
internal override string ToDisplayString()
{
if (Elements.Count == 0)
{
return "set()";
}
if (!PythonRepresentationGuard.TryEnter(this))
{
return "{...}";
}
try
{
return "{"
+ string.Join(", ", Elements.Select(element => element.ToRepresentationString()))
+ "}";
}
finally
{
PythonRepresentationGuard.Exit(this);
}
}
}
internal sealed record PythonSliceValue(PythonValue Start, PythonValue Stop, PythonValue Step)
: PythonValue
{
internal override string ToDisplayString() =>
$"slice({Start.ToRepresentationString()}, {Stop.ToRepresentationString()}, "
+ $"{Step.ToRepresentationString()})";
}
internal sealed record PythonDictionaryViewValue(string Kind, PythonListValue Snapshot)
: PythonValue
{
internal override string ToDisplayString() => $"{Kind}({Snapshot.ToDisplayString()})";
}
internal sealed record PythonListValue(List<PythonValue> Elements) : PythonValue
{
internal override string ToDisplayString()
{
if (!PythonRepresentationGuard.TryEnter(this))
{
return "[...]";
}
try
{
return $"[{string.Join(", ", Elements.Select(element => element.ToRepresentationString()))}]";
}
finally
{
PythonRepresentationGuard.Exit(this);
}
}
}
internal sealed record PythonTupleValue(PythonValue[] Elements) : PythonValue
{
internal override string ToDisplayString()
{
if (!PythonRepresentationGuard.TryEnter(this))
{
return "(...)";
}
try
{
return FormatTuple();
}
finally
{
PythonRepresentationGuard.Exit(this);
}
}
private string FormatTuple()
{
if (Elements.Length == 0)
{
return "()";
}
var contents = string.Join(
", ",
Elements.Select(element => element.ToRepresentationString())
);
return Elements.Length == 1 ? $"({contents},)" : $"({contents})";
}
}
internal sealed class PythonDictionaryItemValue
{
internal PythonDictionaryItemValue(PythonValue key, PythonValue value)
{
Key = key;
Value = value;
}
internal PythonValue Key { get; }
internal PythonValue Value { get; set; }
}
internal sealed record PythonDictionaryValue(List<PythonDictionaryItemValue> Items) : PythonValue
{
internal int SizeVersion { get; set; }
internal override string ToDisplayString()
{
if (!PythonRepresentationGuard.TryEnter(this))
{
return "{...}";
}
try
{
return $"{{{string.Join(", ", Items.Select(item => $"{item.Key.ToRepresentationString()}: {item.Value.ToRepresentationString()}"))}}}";
}
finally
{
PythonRepresentationGuard.Exit(this);
}
}
}
internal sealed record PythonIteratorValue(PythonValue Iterable, int ExpectedDictionarySizeVersion)
: PythonValue
{
internal int Index { get; set; }
internal override string ToDisplayString() => "<collection_iterator>";
}
internal static class PythonRepresentationGuard
{
[ThreadStatic]
private static HashSet<PythonValue>? _activeValues;
internal static bool TryEnter(PythonValue value)
{
_activeValues ??= new HashSet<PythonValue>(ReferenceEqualityComparer.Instance);
return _activeValues.Add(value);
}
internal static void Exit(PythonValue value)
{
_activeValues?.Remove(value);
if (_activeValues?.Count == 0)
{
_activeValues = null;
}
}
}