forked from microsoft/python-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFStringParser.cs
More file actions
452 lines (401 loc) · 18.5 KB
/
FStringParser.cs
File metadata and controls
452 lines (401 loc) · 18.5 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
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Python.Core;
using Microsoft.Python.Core.Text;
using Microsoft.Python.Parsing.Ast;
namespace Microsoft.Python.Parsing {
internal class FStringParser {
// Readonly parametrized
private readonly List<Node> _fStringChildren;
private readonly string _fString;
private readonly bool _isRaw;
private readonly ErrorSink _errors;
private readonly ParserOptions _options;
private readonly PythonLanguageVersion _langVersion;
private readonly bool _verbatim;
private readonly SourceLocation _start;
// Nonparametric initialization
private readonly StringBuilder _buffer = new StringBuilder();
private readonly Stack<char> _nestedParens = new Stack<char>();
// State fields
private int _position = 0;
private int _currentLineNumber;
private int _currentColNumber;
private bool _hasErrors = false;
// Static fields
private static readonly StringSpan DoubleOpen = new StringSpan("{{", 0, 2);
private static readonly StringSpan DoubleClose = new StringSpan("}}", 0, 2);
private static readonly StringSpan NotEqualStringSpan = new StringSpan("!=", 0, 2);
private static readonly StringSpan BackslashN = new StringSpan("\\N", 0, 2);
internal FStringParser(List<Node> fStringChildren, string fString, bool isRaw,
ParserOptions options, PythonLanguageVersion langVersion) {
_fString = fString;
_isRaw = isRaw;
_fStringChildren = fStringChildren;
_errors = options.ErrorSink ?? ErrorSink.Null;
_options = options;
_langVersion = langVersion;
_verbatim = options.Verbatim;
_start = options.InitialSourceLocation ?? SourceLocation.MinValue;
_currentLineNumber = _start.Line;
_currentColNumber = _start.Column;
}
public void Parse() {
var bufferStartLoc = CurrentLocation();
while (!EndOfFString()) {
if (IsNext(DoubleOpen)) {
_buffer.Append(NextChar());
_buffer.Append(NextChar());
} else if (IsNext(DoubleClose)) {
_buffer.Append(NextChar());
_buffer.Append(NextChar());
} else if (!_isRaw && IsNext(BackslashN)) {
_buffer.Append(NextChar());
_buffer.Append(NextChar());
if (CurrentChar() == '{') {
Read('{');
_buffer.Append('{');
while (!EndOfFString() && CurrentChar() != '}') {
_buffer.Append(NextChar());
}
if (Read('}')) {
_buffer.Append('}');
}
} else {
_buffer.Append(NextChar());
}
} else if (CurrentChar() == '{') {
AddBufferedSubstring(bufferStartLoc);
ParseInnerExpression();
bufferStartLoc = CurrentLocation();
} else if (CurrentChar() == '}') {
ReportSyntaxError(Resources.SingleClosedBraceFStringErrorMsg);
_buffer.Append(NextChar());
} else {
_buffer.Append(NextChar());
}
}
AddBufferedSubstring(bufferStartLoc);
}
private bool IsNext(StringSpan span)
=> _fString.Slice(_position, span.Length).Equals(span);
private void ParseInnerExpression() {
_fStringChildren.Add(ParseFStringExpression());
}
// Inspired on CPython's f-string parsing implementation
private Node ParseFStringExpression() {
Debug.Assert(_buffer.Length == 0, "Current buffer is not empty");
var startOfFormattedValue = CurrentLocation().Index;
Read('{');
var initialPosition = _position;
SourceLocation initialSourceLocation = CurrentLocation();
BufferInnerExpression();
Expression fStringExpression = null;
FormattedValue formattedValue;
if (EndOfFString()) {
if (_nestedParens.Count > 0) {
ReportSyntaxError(Resources.UnmatchedFStringErrorMsg.FormatInvariant(_nestedParens.Peek()));
_nestedParens.Clear();
} else {
ReportSyntaxError(Resources.ExpectingCharFStringErrorMsg.FormatInvariant('}'));
}
if (_buffer.Length != 0) {
fStringExpression = CreateExpression(_buffer.ToString(), initialSourceLocation);
_buffer.Clear();
} else {
fStringExpression = Error(initialPosition);
}
formattedValue = new FormattedValue(fStringExpression, null, null);
formattedValue.SetLoc(new IndexSpan(startOfFormattedValue, CurrentLocation().Index - startOfFormattedValue));
return formattedValue;
}
if (!_hasErrors) {
fStringExpression = CreateExpression(_buffer.ToString(), initialSourceLocation);
_buffer.Clear();
} else {
// Clear and recover
_buffer.Clear();
}
Debug.Assert(CurrentChar() == '}' || CurrentChar() == '!' || CurrentChar() == ':');
var conversion = MaybeReadConversionChar();
var formatSpecifier = MaybeReadFormatSpecifier();
Read('}');
if (fStringExpression == null) {
return Error(initialPosition);
}
formattedValue = new FormattedValue(fStringExpression, conversion, formatSpecifier);
formattedValue.SetLoc(new IndexSpan(startOfFormattedValue, CurrentLocation().Index - startOfFormattedValue));
Debug.Assert(_buffer.Length == 0, "Current buffer is not empty");
return formattedValue;
}
private SourceLocation CurrentLocation() {
return new SourceLocation(StartIndex() + _position, _currentLineNumber, _currentColNumber);
}
private Expression MaybeReadFormatSpecifier() {
Debug.Assert(_buffer.Length == 0);
Expression formatSpecifier = null;
if (!EndOfFString() && CurrentChar() == ':') {
Read(':');
var position = _position;
/* Ideally we would just call the FStringParser here. But we are relying on
* an already cut of string, so we need to find the end of the format
* specifier. */
BufferFormatSpecifier();
// If we got to the end, there will be an error when we try to read '}'
if (!EndOfFString()) {
var options = _options.Clone();
options.InitialSourceLocation = new SourceLocation(
StartIndex() + position,
_currentLineNumber,
_currentColNumber
);
var formatStr = _buffer.ToString();
_buffer.Clear();
var formatSpecifierChildren = new List<Node>();
new FStringParser(formatSpecifierChildren, formatStr, _isRaw, options, _langVersion).Parse();
formatSpecifier = new FormatSpecifier(formatSpecifierChildren.ToArray(), formatStr);
formatSpecifier.SetLoc(new IndexSpan(StartIndex() + position, formatStr.Length));
}
}
return formatSpecifier;
}
private char? MaybeReadConversionChar() {
char? conversion = null;
if (!EndOfFString() && CurrentChar() == '!') {
Read('!');
if (EndOfFString()) {
return null;
}
conversion = CurrentChar();
if (conversion == 's' || conversion == 'r' || conversion == 'a') {
NextChar();
return conversion;
} else if (conversion == '}' || conversion == ':') {
ReportSyntaxError(Resources.InvalidConversionCharacterFStringErrorMsg);
} else {
NextChar();
ReportSyntaxError(Resources.InvalidConversionCharacterExpectedFStringErrorMsg.FormatInvariant(conversion));
}
}
return null;
}
private void BufferInnerExpression() {
Debug.Assert(_nestedParens.Count == 0);
char? quoteChar = null;
int stringType = 0;
while (!EndOfFString()) {
var ch = CurrentChar();
if (!quoteChar.HasValue && _nestedParens.Count == 0 && (ch == '}' || ch == '!' || ch == ':')) {
// check that it's not a != comparison
if (ch != '!' || !IsNext(NotEqualStringSpan)) {
break;
}
}
if (HasBackslash(ch)) {
ReportSyntaxError(Resources.BackslashFStringExpressionErrorMsg);
_buffer.Append(NextChar());
continue;
}
if (quoteChar.HasValue) {
HandleInsideString(ref quoteChar, ref stringType);
} else {
HandleInnerExprOutsideString(ref quoteChar, ref stringType);
}
}
}
private void BufferFormatSpecifier() {
Debug.Assert(_nestedParens.Count == 0);
char? quoteChar = null;
int stringType = 0;
while (!EndOfFString()) {
var ch = CurrentChar();
if (!quoteChar.HasValue && _nestedParens.Count == 0 && (ch == '}')) {
// check that it's not a != comparison
if (ch != '!' || !IsNext(NotEqualStringSpan)) {
break;
}
}
if (quoteChar.HasValue) {
/* We're inside a string. See if we're at the end. */
HandleInsideString(ref quoteChar, ref stringType);
} else {
HandleFormatSpecOutsideString(ref quoteChar, ref stringType);
}
}
}
private void HandleFormatSpecOutsideString(ref char? quoteChar, ref int stringType) {
Debug.Assert(!quoteChar.HasValue);
var ch = CurrentChar();
if (ch == '\'' || ch == '"') {
/* Is this a triple quoted string? */
quoteChar = ch;
if (IsNext(new StringSpan($"{ch}{ch}{ch}", 0, 3))) {
stringType = 3;
_buffer.Append(NextChar());
_buffer.Append(NextChar());
_buffer.Append(NextChar());
return;
} else {
/* Start of a normal string. */
stringType = 1;
}
/* Start looking for the end of the string. */
} else if ((ch == ')' || ch == '}' || ch == ']') && _nestedParens.Count > 0) {
char opening = _nestedParens.Pop();
if (!IsOpeningOf(opening, ch)) {
ReportSyntaxError(Resources.ClosingParensNotMatchFStringErrorMsg.FormatInvariant(ch, opening));
}
} else if ((ch == ')' || ch == '}' || ch == ']') && _nestedParens.Count == 0) {
ReportSyntaxError(Resources.UnmatchedFStringErrorMsg.FormatInvariant(ch));
} else if (ch == '(' || ch == '{' || ch == '[') {
_nestedParens.Push(ch);
}
_buffer.Append(NextChar());
}
private void HandleInnerExprOutsideString(ref char? quoteChar, ref int stringType) {
Debug.Assert(!quoteChar.HasValue);
var ch = CurrentChar();
if (ch == '\'' || ch == '"') {
/* Is this a triple quoted string? */
quoteChar = ch;
if (IsNext(new StringSpan($"{ch}{ch}{ch}", 0, 3))) {
stringType = 3;
_buffer.Append(NextChar());
_buffer.Append(NextChar());
_buffer.Append(NextChar());
return;
} else {
/* Start of a normal string. */
stringType = 1;
}
/* Start looking for the end of the string. */
} else if (ch == '#') {
ReportSyntaxError(Resources.NumberSignFStringExpressionErrorMsg);
} else if ((ch == ')' || ch == '}' || ch == ']') && _nestedParens.Count > 0) {
char opening = _nestedParens.Pop();
if (!IsOpeningOf(opening, ch)) {
ReportSyntaxError(Resources.ClosingParensNotMatchFStringErrorMsg.FormatInvariant(ch, opening));
}
} else if ((ch == ')' || ch == '}' || ch == ']') && _nestedParens.Count == 0) {
ReportSyntaxError(Resources.UnmatchedFStringErrorMsg.FormatInvariant(ch));
} else if (ch == '(' || ch == '{' || ch == '[') {
_nestedParens.Push(ch);
}
_buffer.Append(NextChar());
}
private bool IsOpeningOf(char opening, char ch) {
switch (opening) {
case '(' when ch == ')':
case '{' when ch == '}':
case '[' when ch == ']':
return true;
default:
return false;
}
}
private void HandleInsideString(ref char? quoteChar, ref int stringType) {
Debug.Assert(quoteChar.HasValue);
var ch = CurrentChar();
/* We're inside a string. See if we're at the end. */
if (ch == quoteChar.Value) {
/* Does this match the string_type (single or triple
quoted)? */
if (stringType == 3) {
if (IsNext(new StringSpan($"{ch}{ch}{ch}", 0, 3))) {
/* We're at the end of a triple quoted string. */
_buffer.Append(NextChar());
_buffer.Append(NextChar());
_buffer.Append(NextChar());
stringType = 0;
quoteChar = null;
return;
}
} else {
/* We're at the end of a normal string. */
quoteChar = null;
stringType = 0;
}
}
_buffer.Append(NextChar());
}
private Expression CreateExpression(string subExprStr, SourceLocation initialSourceLocation) {
if (subExprStr.IsNullOrEmpty()) {
ReportSyntaxError(Resources.EmptyExpressionFStringErrorMsg);
return new ErrorExpression(subExprStr, null);
}
var parser = Parser.CreateParser(new StringReader(subExprStr), _langVersion, new ParserOptions() {
ErrorSink = _errors,
InitialSourceLocation = initialSourceLocation,
ParseFStringExpression = true
});
var expr = parser.ParseFStrSubExpr();
if (expr is null) {
// Should not happen but just in case
ReportSyntaxError(Resources.InvalidExpressionFStringErrorMsg);
return Error(_position - subExprStr.Length);
}
return expr;
}
private bool Read(char nextChar) {
if (EndOfFString()) {
ReportSyntaxError(Resources.ExpectingCharFStringErrorMsg.FormatInvariant(nextChar));
return false;
}
char ch = CurrentChar();
NextChar();
if (ch != nextChar) {
ReportSyntaxError(Resources.ExpectingCharButFoundFStringErrorMsg.FormatInvariant(nextChar, ch));
return false;
}
return true;
}
private void AddBufferedSubstring(SourceLocation bufferStartLoc) {
if (_buffer.Length == 0) {
return;
}
var s = _buffer.ToString();
_buffer.Clear();
string contents = "";
try {
contents = LiteralParser.ParseString(s.ToCharArray(),
0, s.Length, _isRaw, isUni: true, normalizeLineEndings: true, allowTrailingBackslash: true);
} catch (DecoderFallbackException e) {
var span = new SourceSpan(bufferStartLoc, CurrentLocation());
_errors.Add(e.Message, span, ErrorCodes.SyntaxError, Severity.Error);
} finally {
var expr = new ConstantExpression(contents);
expr.SetLoc(new IndexSpan(bufferStartLoc.Index, s.Length));
_fStringChildren.Add(expr);
}
}
private char NextChar() {
var prev = CurrentChar();
_position++;
_currentColNumber++;
if (IsLineEnding(prev)) {
_currentColNumber = 1;
_currentLineNumber++;
}
return prev;
}
private int StartIndex() => _start.Index;
private bool IsLineEnding(char prev) => prev == '\n' || (prev == '\\' && IsNext(new StringSpan("n", 0, 1)));
private bool HasBackslash(char ch) => ch == '\\';
private char CurrentChar() => _fString[_position];
private bool EndOfFString() => _position >= _fString.Length;
private void ReportSyntaxError(string message) {
_hasErrors = true;
var span = new SourceSpan(new SourceLocation(_start.Index + _position, _currentLineNumber, _currentColNumber),
new SourceLocation(StartIndex() + _position + 1, _currentLineNumber, _currentColNumber + 1));
_errors.Add(message, span, ErrorCodes.SyntaxError, Severity.Error);
}
private ErrorExpression Error(int startPos, string verbatimImage = null, Expression preceding = null) {
verbatimImage = verbatimImage ?? (_fString.Substring(startPos, _position - startPos));
var expr = new ErrorExpression(verbatimImage, preceding);
expr.SetLoc(StartIndex() + startPos, StartIndex() + _position);
return expr;
}
}
}