/
ExpressionLexer.cs
1357 lines (1183 loc) · 53.4 KB
/
ExpressionLexer.cs
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//---------------------------------------------------------------------
// <copyright file="ExpressionLexer.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.UriParser
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.OData;
using Microsoft.OData.Edm;
using ODataErrorStrings = Microsoft.OData.Strings;
#endregion Namespaces
/// <summary>Use this class to parse an expression in the OData URI format.</summary>
/// <remarks>
/// Literals (non-normative "handy" reference - see spec for correct expression):
/// Null null
/// Boolean true | false
/// Int32 (digit+)
/// Int64 (digit+)[L|l]
/// Decimal (digit+ ['.' digit+])[M|m]
/// Float (digit+ ['.' digit+][e|E [+|-] digit+)[f|F]
/// Double (digit+ ['.' digit+][e|E [+|-] digit+)[d|D]
/// String "'" .* "'"
/// DateTime datetime"'"dddd-dd-dd[T|' ']dd:mm[ss[.fffffff]]"'"
/// DateTimeOffset dddd-dd-dd[T|' ']dd:mm[ss[.fffffff]]-dd:mm
/// Duration time"'"dd:mm[ss[.fffffff]]"'"
/// Binary (binary|X)'digit*'
/// GUID 8HEXDIG "-" 4HEXDIG "-" 4HEXDIG "-" 4HEXDIG "-" 12HEXDIG
///
/// Note: ABNF v4.0 actually has forbidden numeric string's trailing L,M,F,D though we allow them to be optional
/// http://docs.oasis-open.org/odata/odata/v4.0/cs01/abnf/odata-abnf-construction-rules.txt
/// decimalValue = [SIGN] 1*DIGIT ["." 1*DIGIT]
/// doubleValue = decimalValue [ "e" [SIGN] 1*DIGIT ] / nanInfinity ; with restricted number range
/// singleValue = doubleValue ; with restricted number range
/// nanInfinity = 'NaN' / '-INF' / 'INF'
///
/// </remarks>
[DebuggerDisplay("ExpressionLexer ({text} @ {textPos} [{token}])")]
internal class ExpressionLexer
{
#region Protected and Private fields
/// <summary>Text being parsed.</summary>
protected readonly string Text;
/// <summary>Length of text being parsed.</summary>
protected readonly int TextLen;
/// <summary>Position on text being parsed.</summary>
protected int textPos;
/// <summary>Character being processed.</summary>
protected char? ch;
/// <summary>Token being processed.</summary>
protected ExpressionToken token;
/// <summary>
/// For an identifier, EMD supports chars that match the regex [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Lm}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]
/// IsLetterOrDigit covers Ll, Lu, Lt, Lo, Lm, Nd, this set covers the rest
/// </summary>
private static readonly HashSet<UnicodeCategory> AdditionalUnicodeCategoriesForIdentifier = new HashSet<UnicodeCategory>(new UnicodeCategoryEqualityComparer())
{
UnicodeCategory.LetterNumber,
UnicodeCategory.NonSpacingMark,
UnicodeCategory.SpacingCombiningMark,
UnicodeCategory.ConnectorPunctuation, // covers "_"
UnicodeCategory.Format
};
/// <summary> flag to indicate whether to delimit on a semicolon. </summary>
private readonly bool useSemicolonDelimiter;
/// <summary>Whether the lexer is being used to parse function parameters. If true, will allow/recognize parameter aliases and typed nulls.</summary>
private readonly bool parsingFunctionParameters;
/// <summary>Lexer ignores whitespace</summary>
private bool ignoreWhitespace;
/// <summary>Indicates whether a double-quoted string is being parsed.</summary>
private bool parsingDoubleQuotedString;
#endregion Protected and Private fields
#region Constructors
/// <summary>Initializes a new <see cref="ExpressionLexer"/>.</summary>
/// <param name="expression">Expression to parse.</param>
/// <param name="moveToFirstToken">If true, this constructor will call NextToken() to move to the first token.</param>
/// <param name="useSemicolonDelimiter">If true, the lexer will tokenize based on semicolons as well.</param>
internal ExpressionLexer(string expression, bool moveToFirstToken, bool useSemicolonDelimiter)
: this(expression, moveToFirstToken, useSemicolonDelimiter, false /*parsingFunctionParameters*/)
{
}
/// <summary>Initializes a new <see cref="ExpressionLexer"/>.</summary>
/// <param name="expression">Expression to parse.</param>
/// <param name="moveToFirstToken">If true, this constructor will call NextToken() to move to the first token.</param>
/// <param name="useSemicolonDelimiter">If true, the lexer will tokenize based on semicolons as well.</param>
/// <param name="parsingFunctionParameters">Whether the lexer is being used to parse function parameters. If true, will allow/recognize parameter aliases and typed nulls.</param>
internal ExpressionLexer(string expression, bool moveToFirstToken, bool useSemicolonDelimiter, bool parsingFunctionParameters)
{
Debug.Assert(expression != null, "expression != null");
this.ignoreWhitespace = true;
this.Text = expression;
this.TextLen = this.Text.Length;
this.useSemicolonDelimiter = useSemicolonDelimiter;
this.parsingFunctionParameters = parsingFunctionParameters;
this.parsingDoubleQuotedString = false;
this.SetTextPos(0);
if (moveToFirstToken)
{
this.NextToken();
}
}
#endregion Constructors
#region Internal properties
/// <summary>Token being processed.</summary>
internal ExpressionToken CurrentToken
{
get
{
return this.token;
}
set
{
this.token = value;
}
}
/// <summary>Text being parsed.</summary>
internal string ExpressionText
{
get
{
return this.Text;
}
}
/// <summary>Position on text being parsed.</summary>
internal int Position
{
get
{
return this.token.Position;
}
}
#endregion Internal properties
#region Private properties
/// <summary>
/// Gets if the current char is whitespace.
/// </summary>
protected bool IsValidWhiteSpace
{
get
{
return this.ch != null && Char.IsWhiteSpace(this.ch.Value);
}
}
/// <summary>
/// Gets if the current char is digit.
/// </summary>
private bool IsValidDigit
{
get
{
return this.ch != null && Char.IsDigit(this.ch.Value);
}
}
/// <summary>
/// Is the current char a valid starting char for an identifier.
/// Valid starting chars for identifier include all that are supported by EDM ([\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Lm}\p{Nl}]) and '_'.
/// </summary>
private bool IsValidStartingCharForIdentifier
{
get
{
return this.ch != null && (
Char.IsLetter(this.ch.Value) || // IsLetter covers: Ll, Lu, Lt, Lo, Lm
this.ch == '_' ||
this.ch == '$' ||
PlatformHelper.GetUnicodeCategory(this.ch.Value) == UnicodeCategory.LetterNumber);
}
}
/// <summary>
/// Is the current char a valid non-starting char for an identifier.
/// Valid non-starting chars for identifier include all that are supported
/// by EDM [\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Lm}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}].
/// This list includes '_', which is ConnectorPunctuation (Pc)
/// </summary>
private bool IsValidNonStartingCharForIdentifier
{
get
{
return this.ch != null && (
Char.IsLetterOrDigit(this.ch.Value) || // covers: Ll, Lu, Lt, Lo, Lm, Nd
AdditionalUnicodeCategoriesForIdentifier.Contains(PlatformHelper.GetUnicodeCategory(this.ch.Value))); // covers the rest
}
}
#endregion
#region Internal methods
/// <summary>
/// Determines if the next token can be processed without error without advancing the token.
/// </summary>
/// <param name="resultToken">The next ExpressionToken. This value is undefined if error is defined.</param>
/// <param name="error">Exception generated from trying to process the next token.</param>
/// <returns>True if the next token can be processed, false otherwise.</returns>
internal bool TryPeekNextToken(out ExpressionToken resultToken, out Exception error)
{
int savedTextPos = this.textPos;
char? savedChar = this.ch;
ExpressionToken savedToken = this.token;
resultToken = this.NextTokenImplementation(out error);
this.textPos = savedTextPos;
this.ch = savedChar;
this.token = savedToken;
return error == null;
}
/// <summary>Reads the next token, skipping whitespace as necessary, advancing the Lexer.</summary>
/// <returns>The next token.</returns>
/// <remarks>Throws on error.</remarks>
internal ExpressionToken NextToken()
{
Exception error = null;
ExpressionToken nextToken = this.NextTokenImplementation(out error);
if (error != null)
{
throw error;
}
return nextToken;
}
/// <summary>
/// Starting from an identifier, reads a sequence of dots and
/// identifiers, and returns the text for it, with whitespace
/// stripped.
/// </summary>
/// <param name="acceptStar">do we allow a star in this identifier</param>
/// <returns>The dotted identifier starting at the current identifier.</returns>
internal string ReadDottedIdentifier(bool acceptStar)
{
this.ValidateToken(ExpressionTokenKind.Identifier);
StringBuilder builder = null;
string result = this.CurrentToken.Text;
this.NextToken();
while (this.CurrentToken.Kind == ExpressionTokenKind.Dot)
{
this.NextToken();
if (this.CurrentToken.Kind != ExpressionTokenKind.Identifier &&
this.CurrentToken.Kind != ExpressionTokenKind.QuotedLiteral)
{
if (this.CurrentToken.Kind == ExpressionTokenKind.Star)
{
// if we accept a star and this is the last token in the identifier, then we're ok... otherwise we throw.
if (!acceptStar || (this.PeekNextToken().Kind != ExpressionTokenKind.End && this.PeekNextToken().Kind != ExpressionTokenKind.Comma))
{
throw ParseError(ODataErrorStrings.ExpressionLexer_SyntaxError(this.textPos, this.Text));
}
}
else
{
throw ParseError(ODataErrorStrings.ExpressionLexer_SyntaxError(this.textPos, this.Text));
}
}
if (builder == null)
{
builder = new StringBuilder(result, result.Length + 1 + this.CurrentToken.Text.Length);
}
builder.Append('.');
builder.Append(this.CurrentToken.Text);
this.NextToken();
}
if (builder != null)
{
result = builder.ToString();
}
return result;
}
/// <summary>Returns the next token without advancing the lexer.</summary>
/// <returns>The next token.</returns>
internal ExpressionToken PeekNextToken()
{
ExpressionToken outToken;
Exception error;
this.TryPeekNextToken(out outToken, out error);
if (error != null)
{
throw error;
}
return outToken;
}
/// <summary>
/// Check whether the current identifier is a function. If so, expand the token text to the function signature
/// </summary>
/// <returns>True if the current identifier is a function call</returns>
internal bool ExpandIdentifierAsFunction()
{
// FUNCTION := (<ID> {<DOT>}) ... <ID> <OpenParen>
// if we fail to match then we leave the token as it
ExpressionTokenKind id = this.token.Kind;
if (id != ExpressionTokenKind.Identifier)
{
return false;
}
int savedTextPos = this.textPos;
char? savedChar = this.ch;
ExpressionToken savedToken = this.token;
bool savedIgnoreWs = this.ignoreWhitespace;
this.ignoreWhitespace = false;
// Expansion left anchor
int tokenStartPos = this.token.Position;
while (this.MoveNextWhenMatch(ExpressionTokenKind.Dot) && this.MoveNextWhenMatch(ExpressionTokenKind.Identifier))
{
}
bool matched = false;
if (this.CurrentToken.Kind == ExpressionTokenKind.Identifier)
{
ExpressionTokenKind nextKind = this.PeekNextToken().Kind;
// Special case for 'in' operator: It is legal to have a custom function with the same name as an operator.
// If the current identifier is 'in', PeekNextToken() will return ParenthesesExpression instead of OpenParen.
// Nevertheless, we should still treat it as a function.
matched =
nextKind == ExpressionTokenKind.OpenParen ||
(nextKind == ExpressionTokenKind.ParenthesesExpression && this.CurrentToken.Text == ExpressionConstants.KeywordIn);
}
if (matched)
{
this.token.Text = this.Text.Substring(tokenStartPos, this.textPos - tokenStartPos);
this.token.Position = tokenStartPos;
}
else
{
this.textPos = savedTextPos;
this.ch = savedChar;
this.token = savedToken;
}
this.ignoreWhitespace = savedIgnoreWs;
return matched;
}
/// <summary>Validates the current token is of the specified kind.</summary>
/// <param name="t">Expected token kind.</param>
internal void ValidateToken(ExpressionTokenKind t)
{
if (this.token.Kind != t)
{
throw ParseError(ODataErrorStrings.ExpressionLexer_SyntaxError(this.textPos, this.Text));
}
}
/// <summary>
/// Advances the lexer until a semicolon, an unbalanced close parens occurs, or the text ends.
/// Any string literals (text in single quotes) will be skipped when checking for delimiters.
/// The CurrentToken of the lexer after this method call will be whatever comes after the advanced text.
/// </summary>
/// <returns>All of the text that was read.</returns>
internal string AdvanceThroughExpandOption()
{
int startingPosition = this.textPos;
string textToReturn;
while (true)
{
if (this.ch == '\'')
{
this.AdvanceToNextOccurenceOf('\'');
}
if (this.ch == '(')
{
this.NextChar();
this.AdvanceThroughBalancedParentheticalExpression();
continue;
}
if (this.ch == ';' || this.ch == ')')
{
textToReturn = this.Text.Substring(startingPosition, this.textPos - startingPosition);
break;
}
if (this.ch == null)
{
textToReturn = this.Text.Substring(startingPosition);
break;
}
this.NextChar();
}
// Move the lexer to be on the delimiter (or past, if the delimiter isn't something special)
this.NextToken();
return textToReturn;
}
/// <summary>
/// Advances through a balanced expression that we do not want to parse, beginning with a '(' and ending with a ')'.
/// </summary>
/// <remarks>
/// 1. This method will identify and advance through inner pairs of parenthesis.
/// 2. The lexer is expected to have a CurrentToken which is the open parenthesis at the start, meaning that we are positioned
/// on the first character of the expression inside that.
/// 3. When we are done we will be right after the closing ')', but we will have have set CurrentToken to anything.
/// For this reason, you probably want to call NextToken() after this method, since CurrentToken wil be garbage.
/// </remarks>
/// <returns>The parenthesis expression, including the outer parenthesis.</returns>
internal string AdvanceThroughBalancedParentheticalExpression()
{
int startPosition = this.Position;
this.AdvanceThroughBalancedExpression('(', ')');
string expressionText = this.Text.Substring(startPosition, this.textPos - startPosition);
//// TODO: Consider introducing a token type and setting up the current token instead of returning string.
//// We've done weird stuff, and the state of hte lexer is weird now. All will be well once NextToken() is called,
//// but until then CurrentToken is stale and misleading.
return expressionText;
}
/// <summary>
/// Get the current position in this lexer that can be used restore the lexer to this position later.
/// </summary>
/// <returns>
/// Returns a snapshot position used to call RestorePosition.
/// </returns>
internal ExpressionLexerPosition SnapshotPosition()
{
return new ExpressionLexerPosition(this, this.textPos, this.token);
}
/// <summary>
/// Sets the current position to the specified position.
/// </summary>
/// <param name="position">The position to restore, returned from SnapshotPosition.</param>
/// <remarks>
/// The specified position must have been retrieved by GetPosition on this instance.
/// </remarks>
internal void RestorePosition(ExpressionLexerPosition position)
{
Debug.Assert(position.Lexer == this, "Position was not taken from this ExpressionLexer instance.");
if (position.TextPos.HasValue)
{
SetTextPos(position.TextPos.Value);
}
if (position.Token.HasValue)
{
this.token = position.Token.Value;
}
}
#endregion Internal methods
#region Private methods
/// <summary>Creates an exception for a parse error.</summary>
/// <param name="message">Message text.</param>
/// <returns>A new Exception.</returns>
protected static Exception ParseError(string message)
{
return new ODataException(message);
}
/// <summary>Advanced to the next character.</summary>
protected void NextChar()
{
if (this.textPos < this.TextLen)
{
this.textPos++;
if (this.textPos < this.TextLen)
{
this.ch = this.Text[this.textPos];
return;
}
}
this.ch = null;
}
/// <summary>
/// Parses white spaces
/// </summary>
protected void ParseWhitespace()
{
while (this.IsValidWhiteSpace)
{
this.NextChar();
}
}
/// <summary>
/// Advance the pointer to the next occurence of the given value, swallowing all characters in between.
/// </summary>
/// <param name="endingValue">the ending delimiter.</param>
protected void AdvanceToNextOccurenceOf(char endingValue)
{
this.NextChar();
while (this.ch.HasValue && (this.ch != endingValue))
{
this.NextChar();
}
}
/// <summary>Reads the next token, skipping whitespace as necessary.</summary>
/// <param name="error">Error that occurred while trying to process the next token.</param>
/// <returns>The next token, which may be 'bad' if an error occurs.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This parser method is all about the switch statement and would be harder to maintain if it were broken up.")]
protected virtual ExpressionToken NextTokenImplementation(out Exception error)
{
error = null;
if (this.ignoreWhitespace)
{
this.ParseWhitespace();
}
ExpressionTokenKind t;
int tokenPos = this.textPos;
switch (this.ch)
{
case '(':
if (this.CurrentToken.Text == ExpressionConstants.KeywordIn)
{
this.NextChar();
this.AdvanceThroughBalancedExpression('(', ')');
t = ExpressionTokenKind.ParenthesesExpression;
}
else
{
this.NextChar();
t = ExpressionTokenKind.OpenParen;
}
break;
case ')':
this.NextChar();
t = ExpressionTokenKind.CloseParen;
break;
case ',':
this.NextChar();
t = ExpressionTokenKind.Comma;
break;
case '-':
bool hasNext = this.textPos + 1 < this.TextLen;
if (hasNext && Char.IsDigit(this.Text[this.textPos + 1]))
{
// don't separate '-' and its following digits : -2147483648 is valid int.MinValue, but 2147483648 is long.
t = this.ParseFromDigit();
if (ExpressionLexerUtils.IsNumeric(t))
{
break;
}
// If it looked like a numeric but wasn't (because it was a binary 0x... value for example),
// we'll rewind and fall through to a simple '-' token.
this.SetTextPos(tokenPos);
}
else if (hasNext && this.Text[tokenPos + 1] == ExpressionConstants.InfinityLiteral[0])
{
this.NextChar();
this.ParseIdentifier();
string currentIdentifier = this.Text.Substring(tokenPos + 1, this.textPos - tokenPos - 1);
if (ExpressionLexerUtils.IsInfinityLiteralDouble(currentIdentifier))
{
t = ExpressionTokenKind.DoubleLiteral;
break;
}
else if (ExpressionLexerUtils.IsInfinityLiteralSingle(currentIdentifier))
{
t = ExpressionTokenKind.SingleLiteral;
break;
}
// If it looked like '-INF' but wasn't we'll rewind and fall through to a simple '-' token.
this.SetTextPos(tokenPos);
}
this.NextChar();
t = ExpressionTokenKind.Minus;
break;
case '=':
this.NextChar();
t = ExpressionTokenKind.Equal;
break;
case '/':
this.NextChar();
t = ExpressionTokenKind.Slash;
break;
case '?':
this.NextChar();
t = ExpressionTokenKind.Question;
break;
case '.':
this.NextChar();
t = ExpressionTokenKind.Dot;
break;
case '\'':
char quote = this.ch.Value;
do
{
this.AdvanceToNextOccurenceOf(quote);
if (this.textPos == this.TextLen)
{
error = ParseError(ODataErrorStrings.ExpressionLexer_UnterminatedStringLiteral(this.textPos, this.Text));
}
this.NextChar();
}
while (this.ch.HasValue && (this.ch.Value == quote));
t = ExpressionTokenKind.StringLiteral;
break;
case '*':
this.NextChar();
t = ExpressionTokenKind.Star;
break;
case ':':
this.NextChar();
t = ExpressionTokenKind.Colon;
break;
case '{':
this.NextChar();
this.AdvanceThroughBalancedExpression('{', '}');
t = ExpressionTokenKind.BracedExpression;
break;
case '[':
this.NextChar();
this.AdvanceThroughBalancedExpression('[', ']');
t = ExpressionTokenKind.BracketedExpression;
break;
default:
if (this.IsValidWhiteSpace)
{
Debug.Assert(!this.ignoreWhitespace, "should not hit ws while ignoring it");
this.ParseWhitespace();
t = ExpressionTokenKind.Unknown;
break;
}
if (this.IsValidStartingCharForIdentifier)
{
this.ParseIdentifier();
// Guids will have '-' in them
// guidValue = 8HEXDIG "-" 4HEXDIG "-" 4HEXDIG "-" 4HEXDIG "-" 12HEXDIG
if (this.ch == '-'
&& this.TryParseGuid(tokenPos))
{
t = ExpressionTokenKind.GuidLiteral;
break;
}
t = ExpressionTokenKind.Identifier;
break;
}
if (this.IsValidDigit)
{
t = this.ParseFromDigit();
break;
}
if (this.textPos == this.TextLen)
{
t = ExpressionTokenKind.End;
break;
}
if (this.useSemicolonDelimiter && this.ch == ';')
{
this.NextChar();
t = ExpressionTokenKind.SemiColon;
break;
}
if (this.ch == '@')
{
this.NextChar();
if (this.textPos == this.TextLen)
{
error = ParseError(ODataErrorStrings.ExpressionLexer_SyntaxError(this.textPos, this.Text));
t = ExpressionTokenKind.Unknown;
break;
}
if (!this.IsValidStartingCharForIdentifier)
{
error = ParseError(ODataErrorStrings.ExpressionLexer_InvalidCharacter(this.ch, this.textPos, this.Text));
t = ExpressionTokenKind.Unknown;
break;
}
int start = this.textPos;
// Include dots for the case of annotation.
this.ParseIdentifier(true /*includingDots*/);
// Extract the identifier from expression.
string leftToken = ExpressionText.Substring(start, this.textPos - start);
t = this.parsingFunctionParameters && !leftToken.Contains(".")
? ExpressionTokenKind.ParameterAlias
: ExpressionTokenKind.Identifier;
break;
}
error = ParseError(ODataErrorStrings.ExpressionLexer_InvalidCharacter(this.ch, this.textPos, this.Text));
t = ExpressionTokenKind.Unknown;
break;
}
this.token.Kind = t;
this.token.Text = this.Text.Substring(tokenPos, this.textPos - tokenPos);
this.token.Position = tokenPos;
this.HandleTypePrefixedLiterals();
return this.token;
}
/// <summary>
/// Expand the token selection if the next token matches the input token
/// </summary>
/// <param name="id">the list of token id to match</param>
/// <returns>true if matched</returns>
private bool MoveNextWhenMatch(ExpressionTokenKind id)
{
ExpressionToken next = this.PeekNextToken();
if (id == next.Kind)
{
this.NextToken();
return true;
}
return false;
}
/// <summary>Handles lexeres that are formed by identifiers.</summary>
/// <remarks>This method modified the token field as necessary.</remarks>
private void HandleTypePrefixedLiterals()
{
if (this.token.Kind != ExpressionTokenKind.Identifier)
{
return;
}
// Get literal of quoted values
if (this.ch == '\'')
{
// Get custom literal if exists.
IEdmTypeReference edmTypeOfCustomLiteral = CustomUriLiteralPrefixes.GetEdmTypeByCustomLiteralPrefix(this.token.Text);
if (edmTypeOfCustomLiteral != null)
{
this.token.SetCustomEdmTypeLiteral(edmTypeOfCustomLiteral);
}
else
{
// Get built in type literal prefix for quoted values
this.token.Kind = this.GetBuiltInTypesLiteralPrefixWithQuotedValue(this.token.Text);
}
this.HandleQuotedValues();
}
else
{
// Handle keywords.
// Get built in type literal prefix.
ExpressionTokenKind? regularTokenKind = GetBuiltInTypesLiteralPrefix(this.token.Text);
if (regularTokenKind.HasValue)
{
this.token.Kind = regularTokenKind.Value;
}
}
}
private void HandleQuotedValues()
{
int startPosition = this.token.Position;
do
{
do
{
this.NextChar();
}
while (this.ch.HasValue && this.ch != '\'');
if (this.ch == null)
{
throw ParseError(ODataErrorStrings.ExpressionLexer_UnterminatedLiteral(this.textPos, this.Text));
}
this.NextChar();
}
while (this.ch.HasValue && this.ch == '\'');
// Update token.Text to include the literal + the quoted value
this.token.Text = this.Text.Substring(startPosition, this.textPos - startPosition);
}
/// <summary>
/// Get type-prefixed literals such as double, boolean...
/// </summary>
/// <param name="tokenText">Token texk</param>
/// <returns>ExpressionTokenKind by the token text</returns>
private static ExpressionTokenKind? GetBuiltInTypesLiteralPrefix(string tokenText)
{
if (ExpressionLexerUtils.IsInfinityOrNaNDouble(tokenText))
{
return ExpressionTokenKind.DoubleLiteral;
}
else if (ExpressionLexerUtils.IsInfinityOrNanSingle(tokenText))
{
return ExpressionTokenKind.SingleLiteral;
}
else if (tokenText == ExpressionConstants.KeywordTrue || tokenText == ExpressionConstants.KeywordFalse)
{
return ExpressionTokenKind.BooleanLiteral;
}
else if (tokenText == ExpressionConstants.KeywordNull)
{
return ExpressionTokenKind.NullLiteral;
}
return null;
}
/// <summary>
/// Get type-prefixed literals with quoted values duration, binary and spatial types.
/// </summary>
/// <param name="tokenText">Token text</param>
/// <returns>ExpressionTokenKind</returns>
/// <example>geometry'POINT (79 84)'. 'geometry' is the tokenText </example>
private ExpressionTokenKind GetBuiltInTypesLiteralPrefixWithQuotedValue(string tokenText)
{
if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixDuration, StringComparison.OrdinalIgnoreCase))
{
return ExpressionTokenKind.DurationLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixBinary, StringComparison.OrdinalIgnoreCase))
{
return ExpressionTokenKind.BinaryLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixGeography, StringComparison.OrdinalIgnoreCase))
{
return ExpressionTokenKind.GeographyLiteral;
}
else if (String.Equals(tokenText, ExpressionConstants.LiteralPrefixGeometry, StringComparison.OrdinalIgnoreCase))
{
return ExpressionTokenKind.GeometryLiteral;
}
else if (string.Equals(tokenText, ExpressionConstants.KeywordNull, StringComparison.OrdinalIgnoreCase))
{
// typed null literals are not supported.
throw ParseError(ODataErrorStrings.ExpressionLexer_SyntaxError(this.textPos, this.Text));
}
else
{
// treat as quoted literal
return ExpressionTokenKind.QuotedLiteral;
}
}
/// <summary>Parses a token that starts with a digit.</summary>
/// <returns>The kind of token recognized.</returns>
private ExpressionTokenKind ParseFromDigit()
{
Debug.Assert(this.IsValidDigit || (this.ch == '-'), "this.IsValidDigit || (this.ch == '-')");
ExpressionTokenKind result;
int tokenPos = this.textPos;
char startChar = this.ch.Value;
this.NextChar();
if (startChar == '0' && (this.ch == 'x' || this.ch == 'X'))
{
result = ExpressionTokenKind.BinaryLiteral;
do
{
this.NextChar();
}
while (this.ch.HasValue && UriParserHelper.IsCharHexDigit(this.ch.Value));
}
else
{
result = ExpressionTokenKind.IntegerLiteral;
while (this.IsValidDigit)
{
this.NextChar();
}
// DateTimeOffset, Date and Guids will have '-' in them
if (this.ch == '-')
{
if (this.TryParseDate(tokenPos))
{
return ExpressionTokenKind.DateLiteral;
}
else if (this.TryParseDateTimeoffset(tokenPos))
{
return ExpressionTokenKind.DateTimeOffsetLiteral;
}
else if (this.TryParseGuid(tokenPos))
{
return ExpressionTokenKind.GuidLiteral;
}
}
// TimeOfDay will have ":" in them
if (this.ch == ':')
{
if (this.TryParseTimeOfDay(tokenPos))
{
return ExpressionTokenKind.TimeOfDayLiteral;
}
}
// Guids will have alpha-numeric characters along with '-', so if a letter is encountered
// try to see if this is Guid or not.
if (this.ch.HasValue && Char.IsLetter(this.ch.Value))
{
if (this.TryParseGuid(tokenPos))
{
return ExpressionTokenKind.GuidLiteral;
}
}
if (this.ch == '.')
{
result = ExpressionTokenKind.DoubleLiteral;
this.NextChar();
this.ValidateDigit();
do
{
this.NextChar();
}
while (this.IsValidDigit);
}
if (this.ch == 'E' || this.ch == 'e')
{
result = ExpressionTokenKind.DoubleLiteral;
this.NextChar();
if (this.ch == '+' || this.ch == '-')
{
this.NextChar();
}
this.ValidateDigit();
do
{
this.NextChar();