forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewStringFormatter.cs
More file actions
589 lines (497 loc) · 22.9 KB
/
NewStringFormatter.cs
File metadata and controls
589 lines (497 loc) · 22.9 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
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Modules;
using IronPython.Runtime.Operations;
namespace IronPython.Runtime {
/// <summary>
/// New string formatter for 'str'.format(...) calls and support for the Formatter
/// library via the _formatter_parser / _formatter_field_name_split
/// methods.
///
/// We parse this format:
///
/// replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}"
/// field_name = (identifier | integer) ("." attribute_name | "[" element_index "]")*
/// attribute_name = identifier
/// element_index = identifier
/// conversion = "r" | "s"
/// format_spec = any char, { must be balanced (for computed values), passed to __format__ method on object
/// </summary>
internal sealed class NewStringFormatter {
private static readonly char[]/*!*/ _brackets = new[] { '{', '}' };
private static readonly char[]/*!*/ _fieldNameEnd = new[] { '{', '}', '!', ':' };
#region Public APIs
/// <summary>
/// Runs the formatting operation on the given format and keyword arguments
/// </summary>
public static string/*!*/ FormatString(PythonContext/*!*/ context, string/*!*/ format, PythonTuple/*!*/ args, IDictionary<object, object>/*!*/ kwArgs) {
ContractUtils.RequiresNotNull(context, nameof(context));
ContractUtils.RequiresNotNull(format, nameof(format));
ContractUtils.RequiresNotNull(args, nameof(args));
ContractUtils.RequiresNotNull(kwArgs, nameof(kwArgs));
return Formatter.FormatString(context, format, args, kwArgs);
}
/// <summary>
/// Gets the formatting information for the given format. This is a list of tuples. The tuples
/// include:
///
/// text, field name, format spec, conversion
/// </summary>
public static IEnumerable<PythonTuple/*!*/>/*!*/ GetFormatInfo(string/*!*/ format) {
ContractUtils.RequiresNotNull(format, nameof(format));
return StringFormatParser.Parse(format);
}
/// <summary>
/// Parses a field name returning the argument name and an iterable
/// object which can be used to access the individual attribute
/// or element accesses. The iterator yields tuples of:
///
/// bool (true if attribute, false if element index), attribute/index value
/// </summary>
public static PythonTuple/*!*/ GetFieldNameInfo(string/*!*/ name) {
ContractUtils.RequiresNotNull(name, nameof(name));
FieldName fieldName = ParseFieldName(name, false);
if (String.IsNullOrEmpty(fieldName.ArgumentName)) {
throw PythonOps.ValueError("empty field name");
}
int val;
object argName = fieldName.ArgumentName;
if (Int32.TryParse(fieldName.ArgumentName, out val)) {
argName = ScriptingRuntimeHelpers.Int32ToObject(val);
}
return PythonTuple.MakeTuple(
argName,
AccessorsToPython(fieldName.Accessors)
);
}
#endregion
#region Parsing
/// <summary>
/// Base class used for parsing the format. Subclasss override Text/ReplacementField methods. Those
/// methods get called when they call Parse and then they can do the appropriate actions for the
/// format.
/// </summary>
private struct StringFormatParser {
private readonly string/*!*/ _str;
private int _index;
private StringFormatParser(string/*!*/ text) {
Assert.NotNull(text);
_str = text;
_index = 0;
}
/// <summary>
/// Gets an enumerable object for walking the parsed format.
///
/// TODO: object array? struct?
/// </summary>
public static IEnumerable<PythonTuple/*!*/>/*!*/ Parse(string/*!*/ text) {
return new StringFormatParser(text).Parse();
}
/// <summary>
/// Provides an enumerable of the parsed format. The elements of the tuple are:
/// the text preceding the format information
/// the field name
/// the format spec
/// the conversion
/// </summary>
private IEnumerable<PythonTuple/*!*/>/*!*/ Parse() {
int lastTextStart = 0;
while (_index != _str.Length) {
lastTextStart = _index;
_index = _str.IndexOfAny(_brackets, _index);
if (_index == -1) {
// no more formats, send the remaining text.
yield return PythonTuple.MakeTuple(
_str.Substring(lastTextStart, _str.Length - lastTextStart),
null,
null,
null);
break;
}
yield return ParseFormat(lastTextStart);
}
}
private PythonTuple/*!*/ ParseFormat(int lastTextStart) {
// check for {{ or }} and get the text string that we've skipped over
string text;
if (ParseDoubleBracket(lastTextStart, out text)) {
return PythonTuple.MakeTuple(text, null, null, null);
}
int bracketDepth = 1;
char? conversion = null;
string formatSpec = String.Empty;
// all entries have a field name, read it first
string fldName = ParseFieldName(ref bracketDepth);
// check for conversion
bool end = CheckEnd();
if (!end && _str[_index] == '!') {
conversion = ParseConversion();
}
// check for format spec
end = end || CheckEnd();
if (!end && _str[_index] == ':') {
formatSpec = ParseFormatSpec(ref bracketDepth);
}
// verify we hit the end of the format
end = end || CheckEnd();
if (!end) {
throw PythonOps.ValueError("expected ':' after format specifier");
}
// yield the replacement field information
return PythonTuple.MakeTuple(
text,
fldName,
formatSpec,
conversion.HasValue ?
conversion.ToString() :
null
);
}
/// <summary>
/// Handles {{ and }} within the string. Returns true if a double bracket
/// is found and yields the text
/// </summary>
private bool ParseDoubleBracket(int lastTextStart, out string/*!*/ text) {
if (_str[_index] == '}') {
// report the text w/ a single } at the end
_index++;
if (_index == _str.Length || _str[_index] != '}') {
throw PythonOps.ValueError("Single '}}' encountered in format string");
}
text = _str.Substring(lastTextStart, _index - lastTextStart);
_index++;
return true;
} else if (_index == _str.Length - 1) {
throw PythonOps.ValueError("Single '{{' encountered in format string");
} else if (_str[_index + 1] == '{') {
// report the text w/ a single { at the end
text = _str.Substring(lastTextStart, ++_index - lastTextStart);
_index++;
return true;
} else {
// yield the text
text = _str.Substring(lastTextStart, _index++ - lastTextStart);
return false;
}
}
/// <summary>
/// Parses the conversion character and returns it
/// </summary>
private char ParseConversion() {
_index++; // eat the !
if (CheckEnd()) {
throw PythonOps.ValueError("end of format while looking for conversion specifier");
}
return _str[_index++];
}
/// <summary>
/// Checks to see if we're at the end of the format. If there's no more characters left we report
/// the error, otherwise if we hit a } we return true to indicate parsing should stop.
/// </summary>
private bool CheckEnd() {
if (_index == _str.Length) {
throw PythonOps.ValueError("unmatched '{{' in format");
} else if (_str[_index] == '}') {
_index++;
return true;
}
return false;
}
/// <summary>
/// Parses the format spec string and returns it.
/// </summary>
private string/*!*/ ParseFormatSpec(ref int depth) {
_index++; // eat the :
return ParseFieldOrSpecWorker(_brackets, ref depth);
}
/// <summary>
/// Parses the field name and returns it.
/// </summary>
private string/*!*/ ParseFieldName(ref int depth) {
return ParseFieldOrSpecWorker(_fieldNameEnd, ref depth);
}
/// <summary>
/// Handles parsing the field name and the format spec and returns it. At the parse
/// level these are basically the same - field names just have more terminating characters.
///
/// The most complex part of parsing them is they both allow nested braces and require
/// the braces are matched. Strangely though the braces need to be matched across the
/// combined field and format spec - not within each format.
/// </summary>
private string/*!*/ ParseFieldOrSpecWorker(char[]/*!*/ ends, ref int depth) {
int end = _index - 1;
bool done = false;
do {
end = _str.IndexOfAny(ends, end + 1);
if (end == -1) {
throw PythonOps.ValueError("unmatched '{{' in format");
}
switch (_str[end]) {
case '{': depth++; break;
case '}': depth--; break;
default: done = true; break;
}
} while (!done && depth != 0);
string res = _str.Substring(_index, end - _index);
_index = end;
return res;
}
}
#endregion
#region String Formatter
/// <summary>
/// Provides the built-in string formatter which is exposed to Python via the str.format API.
/// </summary>
private class Formatter {
private readonly PythonContext/*!*/ _context;
private readonly PythonTuple/*!*/ _args;
private readonly IDictionary<object, object>/*!*/ _kwArgs;
private int _depth;
private int _autoNumberedIndex;
private Formatter(PythonContext/*!*/ context, PythonTuple/*!*/ args, IDictionary<object, object>/*!*/ kwArgs) {
Assert.NotNull(context, args, kwArgs);
_context = context;
_args = args;
_kwArgs = kwArgs;
}
public static string/*!*/ FormatString(PythonContext/*!*/ context, string/*!*/ format, PythonTuple/*!*/ args, IDictionary<object, object>/*!*/ kwArgs) {
Assert.NotNull(context, args, kwArgs, format);
return new Formatter(context, args, kwArgs).ReplaceText(format);
}
private string ReplaceText(string format) {
if (_depth == 2) {
throw PythonOps.ValueError("Max string recursion exceeded");
}
StringBuilder builder = new StringBuilder();
foreach (PythonTuple pt in StringFormatParser.Parse(format)) {
string text = (string)pt[0];
string fieldName = (string)pt[1];
string formatSpec = (string)pt[2];
string conversionStr = (string)pt[3];
char? conversion = conversionStr != null && conversionStr.Length > 0 ? conversionStr[0] : (char?)null;
builder.Append(text);
if (fieldName != null) {
// get the argument value
object argValue = GetArgumentValue(ParseFieldName(fieldName, true));
// apply the conversion
argValue = ApplyConversion(conversion, argValue);
// handle computed format specifiers
formatSpec = ReplaceComputedFormats(formatSpec);
// append the string
builder.Append(Builtin.format(_context.SharedContext, argValue, formatSpec));
}
}
return builder.ToString();
}
/// <summary>
/// Inspects a format spec to see if it contains nested format specs which
/// we need to compute. If so runs another string formatter on the format
/// spec to compute those values.
/// </summary>
private string/*!*/ ReplaceComputedFormats(string/*!*/ formatSpec) {
int computeStart = formatSpec.IndexOf('{');
if (computeStart != -1) {
_depth++;
formatSpec = ReplaceText(formatSpec);
_depth--;
}
return formatSpec;
}
/// <summary>
/// Given the field name gets the object from our arguments running
/// any of the member/index accessors.
/// </summary>
private object GetArgumentValue(FieldName fieldName) {
return DoAccessors(fieldName, GetUnaccessedObject(fieldName));
}
/// <summary>
/// Applies the known built-in conversions to the object if a conversion is
/// specified.
/// </summary>
private object ApplyConversion(char? conversion, object argValue) {
switch (conversion) {
case 'a':
argValue = PythonOps.Ascii(_context.SharedContext, argValue);
break;
case 'r':
argValue = PythonOps.Repr(_context.SharedContext, argValue);
break;
case 's':
argValue = PythonOps.ToString(_context.SharedContext, argValue);
break;
case null:
// no conversion specified
break;
default:
throw PythonOps.ValueError("Unknown conversion specifier {0}", conversion.Value);
}
return argValue;
}
/// <summary>
/// Gets the initial object represented by the field name - e.g. the 0 or
/// keyword name.
/// </summary>
private object GetUnaccessedObject(FieldName fieldName) {
int argIndex;
object argValue;
// get the object
if (fieldName.ArgumentName.Length == 0) {
// auto-numbering of format specifiers
if (_autoNumberedIndex == -1) {
throw PythonOps.ValueError("cannot switch from manual field specification to automatic field numbering");
}
argValue = _args[_autoNumberedIndex++];
} else if (Int32.TryParse(fieldName.ArgumentName, out argIndex)) {
if (_autoNumberedIndex > 0) {
throw PythonOps.ValueError("cannot switch from automatic field numbering to manual field specification");
}
_autoNumberedIndex = -1;
argValue = _args[argIndex];
} else {
argValue = _kwArgs[fieldName.ArgumentName];
}
return argValue;
}
/// <summary>
/// Given the object value runs the accessors in the field name (if any) against the object.
/// </summary>
private object DoAccessors(FieldName fieldName, object argValue) {
foreach (FieldAccessor accessor in fieldName.Accessors) {
// then do any accesses against the object
int intVal;
if (accessor.IsField) {
argValue = PythonOps.GetBoundAttr(
_context.SharedContext,
argValue,
accessor.AttributeName
);
} else if (Int32.TryParse(accessor.AttributeName, out intVal)) {
argValue = PythonOps.GetIndex(
_context.SharedContext,
argValue,
ScriptingRuntimeHelpers.Int32ToObject(intVal)
);
} else {
argValue = PythonOps.GetIndex(
_context.SharedContext,
argValue,
accessor.AttributeName
);
}
}
return argValue;
}
}
#endregion
#region Parser helper functions
/// <summary>
/// Parses the field name including attribute access or element indexing.
/// </summary>
private static FieldName ParseFieldName(string/*!*/ str, bool reportErrors) {
// (identifier | integer) ("." attribute_name | "[" element_index "]")*
int index = 0;
string arg = ParseIdentifier(str, false, ref index);
return new FieldName(arg, ParseFieldAccessors(str, index, reportErrors));
}
/// <summary>
/// Parses the field name including attribute access or element indexing.
/// </summary>
private static IEnumerable<FieldAccessor> ParseFieldAccessors(string/*!*/ str, int index, bool reportErrors) {
// (identifier | integer) ("." attribute_name | "[" element_index "]")*
while (index != str.Length && str[index] != '}') {
char accessType = str[index];
if (accessType == '.' || accessType == '[') {
index++;
bool isIndex = accessType == '[';
string identifier = ParseIdentifier(str, isIndex, ref index);
if (isIndex) {
if (index == str.Length || str[index] != ']') {
throw PythonOps.ValueError("Missing ']' in format string");
}
index++;
}
if (identifier.Length == 0) {
throw PythonOps.ValueError("Empty attribute in format string");
}
yield return new FieldAccessor(identifier, !isIndex);
} else {
if (reportErrors) {
throw PythonOps.ValueError("Only '.' and '[' are valid in format field specifier, got {0}", accessType);
} else {
break;
}
}
}
}
/// <summary>
/// Converts accessors from our internal structure into a PythonTuple matching how CPython
/// exposes these
/// </summary>
private static IEnumerable<PythonTuple> AccessorsToPython(IEnumerable<FieldAccessor> accessors) {
foreach (FieldAccessor accessor in accessors) {
int val;
object attrName = accessor.AttributeName;
if (Int32.TryParse(accessor.AttributeName, out val)) {
attrName = ScriptingRuntimeHelpers.Int32ToObject(val);
}
yield return PythonTuple.MakeTuple(
ScriptingRuntimeHelpers.BooleanToObject(accessor.IsField),
attrName
);
}
}
/// <summary>
/// Parses an identifier and returns it
/// </summary>
private static string/*!*/ ParseIdentifier(string/*!*/ str, bool isIndex, ref int index) {
int start = index;
while (index < str.Length && str[index] != '.' && (isIndex || str[index] != '[') && (!isIndex || str[index] != ']')) {
index++;
}
return str.Substring(start, index - start);
}
/// <summary>
/// Encodes all the information about the field name.
/// </summary>
private readonly struct FieldName {
public readonly string/*!*/ ArgumentName;
public readonly IEnumerable<FieldAccessor>/*!*/ Accessors;
public FieldName(string/*!*/ argumentName, IEnumerable<FieldAccessor>/*!*/ accessors) {
Assert.NotNull(argumentName, accessors);
ArgumentName = argumentName;
Accessors = accessors;
}
}
/// <summary>
/// Encodes a single field accessor (.b or [number] or [str])
/// </summary>
private readonly struct FieldAccessor {
public readonly string AttributeName;
public readonly bool IsField;
public FieldAccessor(string attributeName, bool isField) {
AttributeName = attributeName;
IsField = isField;
}
}
#endregion
}
}