/
tokenizer.cs
5088 lines (4412 loc) · 184 KB
/
tokenizer.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 (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.DesiredStateConfiguration.Internal;
namespace System.Management.Automation.Language
{
/// <summary>
/// Defines the name modes for a dynamic keyword. A name expression may be required, optional or not permitted.
/// </summary>
public enum DynamicKeywordNameMode
{
/// <summary>
/// This keyword does not take a name value.
/// </summary>
NoName = 0,
/// <summary>
/// Name must be present and simple non-empty bare word.
/// </summary>
SimpleNameRequired = 1,
/// <summary>
/// Name must be present but can also be an expression.
/// </summary>
NameRequired = 2,
/// <summary>
/// Name may be optionally present, but if it is present, it must be a non-empty bare word.
/// </summary>
SimpleOptionalName = 3,
/// <summary>
/// Name may be optionally present, expression or bare word.
/// </summary>
OptionalName = 4,
};
/// <summary>
/// Defines the body mode for a dynamic keyword. It can be a scriptblock, hashtable or command which means no body.
/// </summary>
public enum DynamicKeywordBodyMode
{
/// <summary>
/// The keyword act like a command.
/// </summary>
Command = 0,
/// <summary>
/// The keyword has a scriptblock body.
/// </summary>
ScriptBlock = 1,
/// <summary>
/// The keyword has hashtable body.
/// </summary>
Hashtable = 2,
}
/// <summary>
/// Defines the schema/behaviour for a dynamic keyword.
/// a constrained.
/// </summary>
public class DynamicKeyword
{
#region static properties/functions
/// <summary>
/// Defines a dictionary of dynamic keywords, stored in thread-local storage.
/// </summary>
private static Dictionary<string, DynamicKeyword> DynamicKeywords
{
get
{
return t_dynamicKeywords ??
(t_dynamicKeywords = new Dictionary<string, DynamicKeyword>(StringComparer.OrdinalIgnoreCase));
}
}
[ThreadStatic]
private static Dictionary<string, DynamicKeyword> t_dynamicKeywords;
/// <summary>
/// Stack of DynamicKeywords Cache.
/// </summary>
private static Stack<Dictionary<string, DynamicKeyword>> DynamicKeywordsStack
{
get
{
return t_dynamicKeywordsStack ??
(t_dynamicKeywordsStack = new Stack<Dictionary<string, DynamicKeyword>>());
}
}
[ThreadStatic]
private static Stack<Dictionary<string, DynamicKeyword>> t_dynamicKeywordsStack;
/// <summary>
/// Reset the keyword table to a new empty collection.
/// </summary>
public static void Reset()
{
t_dynamicKeywords = new Dictionary<string, DynamicKeyword>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Push current dynamicKeywords cache into stack.
/// </summary>
public static void Push()
{
DynamicKeywordsStack.Push(t_dynamicKeywords);
Reset();
}
/// <summary>
/// Pop up previous dynamicKeywords cache.
/// </summary>
public static void Pop()
{
t_dynamicKeywords = DynamicKeywordsStack.Pop();
}
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static DynamicKeyword GetKeyword(string name)
{
DynamicKeyword keywordToReturn;
DynamicKeyword.DynamicKeywords.TryGetValue(name, out keywordToReturn);
return keywordToReturn;
}
/// <summary>
/// Returns a copied list of all of the existing dynamic keyword definitions.
/// </summary>
/// <returns></returns>
public static List<DynamicKeyword> GetKeyword()
{
return new List<DynamicKeyword>(DynamicKeyword.DynamicKeywords.Values);
}
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static bool ContainsKeyword(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name));
throw e;
}
return DynamicKeyword.DynamicKeywords.ContainsKey(name);
}
/// <summary>
/// </summary>
/// <param name="keywordToAdd"></param>
public static void AddKeyword(DynamicKeyword keywordToAdd)
{
if (keywordToAdd == null)
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(keywordToAdd));
throw e;
}
// Allow overwriting of the existing entries
string name = keywordToAdd.Keyword;
if (string.IsNullOrEmpty(name))
{
throw PSTraceSource.NewArgumentNullException("keywordToAdd.Keyword");
}
DynamicKeyword.DynamicKeywords.Remove(name);
DynamicKeyword.DynamicKeywords.Add(name, keywordToAdd);
}
/// <summary>
/// Remove a single entry from the dynamic keyword collection
/// and clean up any associated data.
/// </summary>
/// <param name="name"></param>
public static void RemoveKeyword(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name));
throw e;
}
DynamicKeyword.DynamicKeywords.Remove(name);
}
/// <summary>
/// Check if it is a hidden keyword.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
internal static bool IsHiddenKeyword(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name));
throw e;
}
return s_hiddenDynamicKeywords.Contains(name);
}
/// <summary>
/// A set of dynamic keywords that are not supposed to be used in script directly.
/// They are for internal use only.
/// </summary>
private static readonly HashSet<string> s_hiddenDynamicKeywords =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "MSFT_Credential" };
#endregion
/// <summary>
/// Duplicates the DynamicKeyword.
/// </summary>
/// <returns>A copy of the DynamicKeyword.</returns>
public DynamicKeyword Copy()
{
DynamicKeyword keyword = new DynamicKeyword()
{
ImplementingModule = this.ImplementingModule,
ImplementingModuleVersion = this.ImplementingModuleVersion,
Keyword = this.Keyword,
ResourceName = this.ResourceName,
BodyMode = this.BodyMode,
DirectCall = this.DirectCall,
NameMode = this.NameMode,
MetaStatement = this.MetaStatement,
IsReservedKeyword = this.IsReservedKeyword,
HasReservedProperties = this.HasReservedProperties,
PreParse = this.PreParse,
PostParse = this.PostParse,
SemanticCheck = this.SemanticCheck
};
foreach (KeyValuePair<string, DynamicKeywordProperty> entry in this.Properties)
{
keyword.Properties.Add(entry.Key, entry.Value);
}
foreach (KeyValuePair<string, DynamicKeywordParameter> entry in this.Parameters)
{
keyword.Parameters.Add(entry.Key, entry.Value);
}
return keyword;
}
/// <summary>
/// The name of the module that implements the function corresponding to this keyword.
/// </summary>
public string ImplementingModule { get; set; }
/// <summary>
/// The version of the module that implements the function corresponding to this keyword.
/// </summary>
public Version ImplementingModuleVersion { get; set; }
/// <summary>
/// The keyword string
/// If an alias qualifier exist, use alias.
/// </summary>
public string Keyword { get; set; }
/// <summary>
/// The keyword resource name string.
/// </summary>
public string ResourceName { get; set; }
/// <summary>
/// Set to true if we should be looking for a scriptblock instead of a hashtable.
/// </summary>
public DynamicKeywordBodyMode BodyMode { get; set; }
/// <summary>
/// If true, then don't use the marshalled call. Just
/// rewrite the node as a simple direct function call.
/// If NameMode is other than NoName, then the name of the instance
/// will be passed as the parameter -InstanceName.
/// </summary>
public bool DirectCall { get; set; }
/// <summary>
/// This allows you to specify if the keyword takes a name argument and if so, what form that takes.
/// </summary>
public DynamicKeywordNameMode NameMode { get; set; }
/// <summary>
/// Indicate that the nothing should be added to the AST for this
/// dynamic keyword.
/// </summary>
public bool MetaStatement { get; set; }
/// <summary>
/// Indicate that the keyword is reserved for future use by powershell.
/// </summary>
public bool IsReservedKeyword { get; set; }
/// <summary>
/// Contains the list of properties that are reserved for future use.
/// </summary>
public bool HasReservedProperties { get; set; }
/// <summary>
/// A list of the properties allowed for this constuctor.
/// </summary>
public Dictionary<string, DynamicKeywordProperty> Properties
{
get
{
return _properties ??
(_properties = new Dictionary<string, DynamicKeywordProperty>(StringComparer.OrdinalIgnoreCase));
}
}
private Dictionary<string, DynamicKeywordProperty> _properties;
/// <summary>
/// A list of the parameters allowed for this constuctor.
/// </summary>
public Dictionary<string, DynamicKeywordParameter> Parameters
{
get
{
return _parameters ??
(_parameters = new Dictionary<string, DynamicKeywordParameter>(StringComparer.OrdinalIgnoreCase));
}
}
private Dictionary<string, DynamicKeywordParameter> _parameters;
/// <summary>
/// A custom function that gets executed at parsing time before parsing dynamickeyword block
/// The delegate has one parameter: DynamicKeyword.
/// </summary>
public Func<DynamicKeyword, ParseError[]> PreParse { get; set; }
/// <summary>
/// A custom function that gets executed at parsing time after parsing dynamickeyword block.
/// </summary>
public Func<DynamicKeywordStatementAst, ParseError[]> PostParse { get; set; }
/// <summary>
/// A custom function that checks semantic for the given <see cref="DynamicKeywordStatementAst"/>
/// </summary>
public Func<DynamicKeywordStatementAst, ParseError[]> SemanticCheck { get; set; }
}
internal static class DynamicKeywordExtension
{
internal static bool IsMetaDSCResource(this DynamicKeyword keyword)
{
string implementingModule = keyword.ImplementingModule;
if (implementingModule != null)
{
return implementingModule.Equals(DscClassCache.DefaultModuleInfoForMetaConfigResource.Item1, StringComparison.OrdinalIgnoreCase);
}
return false;
}
internal static bool IsCompatibleWithConfigurationType(this DynamicKeyword keyword, ConfigurationType ConfigurationType)
{
return ((ConfigurationType == ConfigurationType.Meta && keyword.IsMetaDSCResource()) ||
(ConfigurationType != ConfigurationType.Meta && !keyword.IsMetaDSCResource()));
}
private static Dictionary<string, List<string>> s_excludeKeywords = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase)
{
{@"Node", new List<string> {@"Node"}},
};
/// <summary>
/// Get allowed keyword list for a given keyword.
/// </summary>
/// <param name="keyword"></param>
/// <param name="allowedKeywords"></param>
/// <returns>NULL if no keyword allowed for a given <see cref="DynamicKeyword"/></returns>
internal static IEnumerable<DynamicKeyword> GetAllowedKeywords(this DynamicKeyword keyword, IEnumerable<DynamicKeyword> allowedKeywords)
{
string keywordName = keyword.Keyword;
if (string.Compare(keywordName, @"Node", StringComparison.OrdinalIgnoreCase) == 0)
{
List<string> excludeKeywords;
if (s_excludeKeywords.TryGetValue(keywordName, out excludeKeywords))
{
return allowedKeywords.Where(k => !excludeKeywords.Contains(k.Keyword));
}
else
return allowedKeywords;
}
return null;
}
}
/// <summary>
/// Metadata about a member property for a dynamic keyword.
/// </summary>
public class DynamicKeywordProperty
{
/// <summary>
/// The name of the property.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The required type of the property.
/// </summary>
public string TypeConstraint { get; set; }
/// <summary>
/// Any attributes that the property has.
/// </summary>
public List<string> Attributes
{
get { return _attributes ?? (_attributes = new List<string>()); }
}
private List<string> _attributes;
/// <summary>
/// List of strings that may be used as values for this property.
/// </summary>
public List<string> Values
{
get { return _values ?? (_values = new List<string>()); }
}
private List<string> _values;
/// <summary>
/// Mapping the descriptive values to the actual values.
/// </summary>
public Dictionary<string, string> ValueMap
{
get { return _valueMap ?? (_valueMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)); }
}
private Dictionary<string, string> _valueMap;
/// <summary>
/// Indicates that this property is mandatory and must be present.
/// </summary>
public bool Mandatory { get; set; }
/// <summary>
/// Indicates that this property is a key.
/// </summary>
public bool IsKey { get; set; }
/// <summary>
/// Indicates a range constraint on the property value.
/// </summary>
public Tuple<int, int> Range { get; set; }
}
/// <summary>
/// Metadata about a parameter for a dynamic keyword. Adds one
/// new property to the base classL Switch for switch parameters
/// (THere is no such thing as a switch property...)
/// </summary>
public class DynamicKeywordParameter : DynamicKeywordProperty
{
/// <summary>
/// Type if this is a switch parameter and takes no argument.
/// </summary>
public bool Switch { get; set; }
}
internal enum TokenizerMode
{
Command,
Expression,
TypeName,
Signature, // i.e. class or method declaration
}
/// <summary>
/// Indicates which suffix character(s) are present in the numeric literal being parsed by TryGetNumberValue.
/// </summary>
[Flags]
internal enum NumberSuffixFlags
{
/// <summary>
/// Indicates no suffix, a raw numeric literal. May be parsed as Int32, Int64, or Double.
/// </summary>
None = 0x0,
/// <summary>
/// Indicates 'u' suffix for unsigned integers. May be parsed as UInt32 or UInt64, depending on the value.
/// </summary>
Unsigned = 0x1,
/// <summary>
/// Indicates 'y' suffix for signed byte (sbyte) values.
/// </summary>
SignedByte = 0x2,
/// <summary>
/// Indicates 'uy' suffix for unsigned byte values.
/// This is a compound value, representing both SignedByte and Unsigned flags being set.
/// </summary>
UnsignedByte = 0x3,
/// <summary>
/// Indicates 's' suffix for short (Int16) integers.
/// </summary>
Short = 0x4,
/// <summary>
/// Indicates 'us' suffix for ushort (UInt16) integers.
/// This is a compound flag value, representing both Unsigned and Short flags being set.
/// </summary>
UnsignedShort = 0x5,
/// <summary>
/// Indicates 'l' suffix for long (Int64) integers.
/// </summary>
Long = 0x8,
/// <summary>
/// Indicates 'ul' suffix for ulong (UInt64) integers.
/// This is a compound flag value, representing both Unsigned and Long flags being set.
/// </summary>
UnsignedLong = 0x9,
/// <summary>
/// Indicates 'd' suffix for decimal (128-bit) real numbers.
/// </summary>
Decimal = 0x10,
/// <summary>
/// Indicates 'N' suffix for BigInteger (arbitrarily large integer) numerals.
/// </summary>
BigInteger = 0x20
}
/// <summary>
/// Indicates the format of a numeric literal.
/// </summary>
internal enum NumberFormat
{
/// <summary>
/// Indicates standard decimal literal, no necessary prefix.
/// </summary>
Decimal = 0x0,
/// <summary>
/// Indicates hexadecimal literal, with '0x' prefix.
/// </summary>
Hex = 0x1,
/// <summary>
/// Indicates binary literal, with '0b' prefix.
/// </summary>
Binary = 0x2
}
//
// Class used to do a partial snapshot of the state of the tokenizer.
// This is used for nested scans on the same string.
//
internal class TokenizerState
{
internal int NestedTokensAdjustment;
internal string Script;
internal int TokenStart;
internal int CurrentIndex;
internal Token FirstToken;
internal Token LastToken;
internal BitArray SkippedCharOffsets;
internal List<Token> TokenList;
}
[DebuggerDisplay("Mode = {Mode}; Script = {_script}")]
internal class Tokenizer
{
private static readonly Dictionary<string, TokenKind> s_keywordTable
= new Dictionary<string, TokenKind>(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, TokenKind> s_operatorTable
= new Dictionary<string, TokenKind>(StringComparer.OrdinalIgnoreCase);
private static readonly char s_invalidChar = char.MaxValue;
private static readonly int s_maxNumberOfUnicodeHexDigits = 6;
private readonly Parser _parser;
private PositionHelper _positionHelper;
private int _nestedTokensAdjustment;
// This BitArray is used to help ensure we get the correct extent in a corner case that looks something like:
// $(""abc"")
// In the above, we scan the characters between the parens once and create a token that is scanned later. This
// first pass scan replaces doubled quotes with single quotes so that a subsequent scan will see: "abc" instead
// of: ""abc"". (This isn't really necessary, but is done for backwards compatibility.) If we didn't track
// the skipped quotes, we'd generate incorrect extent of the string token on subsequent rescans.
private BitArray _skippedCharOffsets;
private string _script;
private int _tokenStart;
private int _currentIndex;
private InternalScriptExtent _beginSignatureExtent;
#region Tables for initialization
private static readonly string[] s_keywordText = new string[] {
/*1*/ "elseif", "if", "else", "switch", /*1*/
/*2*/ "foreach", "from", "in", "for", /*2*/
/*3*/ "while", "until", "do", "try", /*3*/
/*4*/ "catch", "finally", "trap", "data", /*4*/
/*5*/ "return", "continue", "break", "exit", /*5*/
/*6*/ "throw", "begin", "process", "end", /*6*/
/*7*/ "dynamicparam", "function", "filter", "param", /*7*/
/*8*/ "class", "define", "var", "using", /*8*/
/*9*/ "workflow", "parallel", "sequence", "inlinescript", /*9*/
/*A*/ "configuration", "public", "private", "static", /*A*/
/*B*/ "interface", "enum", "namespace", "module", /*B*/
/*C*/ "type", "assembly", "command", "hidden", /*C*/
/*D*/ "base", "default", /*D*/
};
private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] {
/*1*/ TokenKind.ElseIf, TokenKind.If, TokenKind.Else, TokenKind.Switch, /*1*/
/*2*/ TokenKind.Foreach, TokenKind.From, TokenKind.In, TokenKind.For, /*2*/
/*3*/ TokenKind.While, TokenKind.Until, TokenKind.Do, TokenKind.Try, /*3*/
/*4*/ TokenKind.Catch, TokenKind.Finally, TokenKind.Trap, TokenKind.Data, /*4*/
/*5*/ TokenKind.Return, TokenKind.Continue, TokenKind.Break, TokenKind.Exit, /*5*/
/*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/
/*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/
/*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/
/*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/
/*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/
/*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/
/*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/
/*D*/ TokenKind.Base, TokenKind.Default, /*D*/
};
internal static readonly string[] _operatorText = new string[] {
/*1*/ "bnot", "not", "eq", "ieq", /*1*/
/*2*/ "ceq", "ne", "ine", "cne", /*2*/
/*3*/ "ge", "ige", "cge", "gt", /*3*/
/*4*/ "igt", "cgt", "lt", "ilt", /*4*/
/*5*/ "clt", "le", "ile", "cle", /*5*/
/*6*/ "like", "ilike", "clike", "notlike", /*6*/
/*7*/ "inotlike", "cnotlike", "match", "imatch", /*7*/
/*8*/ "cmatch", "notmatch", "inotmatch", "cnotmatch", /*8*/
/*9*/ "replace", "ireplace", "creplace", "contains", /*9*/
/*10*/ "icontains", "ccontains", "notcontains", "inotcontains", /*10*/
/*11*/ "cnotcontains", "in", "iin", "cin", /*11*/
/*12*/ "notin", "inotin", "cnotin", "split", /*12*/
/*13*/ "isplit", "csplit", "isnot", "is", /*13*/
/*14*/ "as", "f", "and", "band", /*14*/
/*15*/ "or", "bor", "xor", "bxor", /*15*/
/*16*/ "join", "shl", "shr", /*16*/
};
private static readonly TokenKind[] s_operatorTokenKind = new TokenKind[] {
/*1*/ TokenKind.Bnot, TokenKind.Not, TokenKind.Ieq, TokenKind.Ieq, /*1*/
/*2*/ TokenKind.Ceq, TokenKind.Ine, TokenKind.Ine, TokenKind.Cne, /*2*/
/*3*/ TokenKind.Ige, TokenKind.Ige, TokenKind.Cge, TokenKind.Igt, /*3*/
/*4*/ TokenKind.Igt, TokenKind.Cgt, TokenKind.Ilt, TokenKind.Ilt, /*4*/
/*5*/ TokenKind.Clt, TokenKind.Ile, TokenKind.Ile, TokenKind.Cle, /*5*/
/*6*/ TokenKind.Ilike, TokenKind.Ilike, TokenKind.Clike, TokenKind.Inotlike, /*6*/
/*7*/ TokenKind.Inotlike, TokenKind.Cnotlike, TokenKind.Imatch, TokenKind.Imatch, /*7*/
/*8*/ TokenKind.Cmatch, TokenKind.Inotmatch, TokenKind.Inotmatch, TokenKind.Cnotmatch, /*8*/
/*9*/ TokenKind.Ireplace, TokenKind.Ireplace, TokenKind.Creplace, TokenKind.Icontains, /*9*/
/*10*/ TokenKind.Icontains, TokenKind.Ccontains, TokenKind.Inotcontains, TokenKind.Inotcontains, /*10*/
/*11*/ TokenKind.Cnotcontains, TokenKind.Iin, TokenKind.Iin, TokenKind.Cin, /*11*/
/*12*/ TokenKind.Inotin, TokenKind.Inotin, TokenKind.Cnotin, TokenKind.Isplit, /*12*/
/*13*/ TokenKind.Isplit, TokenKind.Csplit, TokenKind.IsNot, TokenKind.Is, /*13*/
/*14*/ TokenKind.As, TokenKind.Format, TokenKind.And, TokenKind.Band, /*14*/
/*15*/ TokenKind.Or, TokenKind.Bor, TokenKind.Xor, TokenKind.Bxor, /*15*/
/*16*/ TokenKind.Join, TokenKind.Shl, TokenKind.Shr, /*16*/
};
#endregion Tables for initialization
static Tokenizer()
{
Diagnostics.Assert(s_keywordText.Length == s_keywordTokenKind.Length, "Keyword table sizes must match");
Diagnostics.Assert(_operatorText.Length == s_operatorTokenKind.Length, "Operator table sizes must match");
for (int i = 0; i < s_keywordText.Length; ++i)
{
s_keywordTable.Add(s_keywordText[i], s_keywordTokenKind[i]);
}
for (int i = 0; i < _operatorText.Length; ++i)
{
s_operatorTable.Add(_operatorText[i], s_operatorTokenKind[i]);
}
// The real signature (in mshsip.cpp) has spaces, but we ignore whitespace when looking
// for signatures because we only care about things that look like a signature.
// The hash we compute is intentionally dumb, we want collisions to catch similar strings,
// so we just sum up the characters.
const string beginSig = "sig#beginsignatureblock";
beginSig.Aggregate(0, (current, t) => current + t);
// Spot check to help make sure the arrays are in sync
Diagnostics.Assert(s_keywordTable["using"] == TokenKind.Using, "Keyword table out of sync w/ enum");
Diagnostics.Assert(s_operatorTable["join"] == TokenKind.Join, "Operator table out of sync w/ enum");
}
internal Tokenizer(Parser parser)
{
_parser = parser;
}
internal TokenizerMode Mode { get; set; }
internal bool AllowSignedNumbers { get; set; }
// TODO: use auto-properties when making 'ternary operator' an official feature.
private bool _forceEndNumberOnTernaryOpChars;
internal bool ForceEndNumberOnTernaryOpChars
{
get { return _forceEndNumberOnTernaryOpChars; }
set { _forceEndNumberOnTernaryOpChars = value; }
}
internal bool WantSimpleName { get; set; }
internal bool InWorkflowContext { get; set; }
internal List<Token> TokenList { get; set; }
internal Token FirstToken { get; private set; }
internal Token LastToken { get; private set; }
private List<Token> RequiresTokens { get; set; }
private bool InCommandMode() { return Mode == TokenizerMode.Command; }
private bool InExpressionMode() { return Mode == TokenizerMode.Expression; }
private bool InTypeNameMode() { return Mode == TokenizerMode.TypeName; }
private bool InSignatureMode() { return Mode == TokenizerMode.Signature; }
internal void Initialize(string fileName, string input, List<Token> tokenList)
{
_positionHelper = new PositionHelper(fileName, input);
_script = input;
this.TokenList = tokenList;
this.FirstToken = null;
this.LastToken = null;
this.RequiresTokens = null;
_beginSignatureExtent = null;
List<int> lineStartMap = new List<int>(100) { 0 };
for (int i = 0; i < input.Length; ++i)
{
char c = input[i];
if (c == '\r')
{
if ((i + 1) < input.Length && input[i + 1] == '\n')
{
i += 1;
}
lineStartMap.Add(i + 1);
}
if (c == '\n')
{
lineStartMap.Add(i + 1);
}
}
_currentIndex = 0;
Mode = TokenizerMode.Command;
_positionHelper.LineStartMap = lineStartMap.ToArray();
}
internal TokenizerState StartNestedScan(UnscannedSubExprToken nestedText)
{
TokenizerState ts = new TokenizerState
{
CurrentIndex = _currentIndex,
NestedTokensAdjustment = _nestedTokensAdjustment,
Script = _script,
TokenStart = _tokenStart,
FirstToken = FirstToken,
LastToken = LastToken,
SkippedCharOffsets = _skippedCharOffsets,
TokenList = TokenList,
};
_currentIndex = 0;
_nestedTokensAdjustment = ((InternalScriptExtent)nestedText.Extent).StartOffset;
_script = nestedText.Value;
_tokenStart = 0;
_skippedCharOffsets = nestedText.SkippedCharOffsets;
TokenList = (TokenList != null) ? new List<Token>() : null;
return ts;
}
internal void FinishNestedScan(TokenizerState ts)
{
_currentIndex = ts.CurrentIndex;
_nestedTokensAdjustment = ts.NestedTokensAdjustment;
_script = ts.Script;
_tokenStart = ts.TokenStart;
FirstToken = ts.FirstToken;
LastToken = ts.LastToken;
_skippedCharOffsets = ts.SkippedCharOffsets;
TokenList = ts.TokenList;
}
#region Utilities
private char GetChar()
{
Diagnostics.Assert(0 <= _currentIndex, "GetChar reading before start of input.");
Diagnostics.Assert(_currentIndex <= _script.Length + 1, "GetChar reading after end of input.");
// Increment _currentIndex, even if it goes over the Length so callers can call UngetChar to unget EOF.
int current = _currentIndex++;
if (current >= _script.Length)
{
return '\0';
}
return _script[current];
}
private void UngetChar()
{
Diagnostics.Assert(_currentIndex > 0, "UngetChar ungetting before start of input.");
_currentIndex -= 1;
}
private char PeekChar()
{
Diagnostics.Assert(0 <= _currentIndex && _currentIndex <= _script.Length, "PeekChar out of range.");
if (_currentIndex == _script.Length)
{
return '\0';
}
return _script[_currentIndex];
}
private void SkipChar()
{
Diagnostics.Assert((_currentIndex + 1) <= _script.Length, "SkipChar can't skip past EOF");
_currentIndex += 1;
}
private bool AtEof()
{
return _currentIndex > _script.Length;
}
internal static bool IsKeyword(string str)
{
if (s_keywordTable.ContainsKey(str))
{
return true;
}
if (DynamicKeyword.ContainsKeyword(str) && !DynamicKeyword.IsHiddenKeyword(str))
{
return true;
}
return false;
}
internal void SkipNewlines(bool skipSemis)
{
// We normally don't create any tokens in a Skip method, but the
// V2 tokenizer api returns newline, semi-colon, and line
// continuation tokens so we create them as they are encountered.
again:
char c = GetChar();
switch (c)
{
case ' ':
case '\t':
case '\f':
case '\v':
case SpecialChars.NoBreakSpace:
case SpecialChars.NextLine:
SkipWhiteSpace();
goto again;
case '\r':
case '\n':
ScanNewline(c);
goto again;
case ';':
if (skipSemis)
{
ScanSemicolon();
goto again;
}
break;
case '#':
_tokenStart = _currentIndex - 1;
ScanLineComment();
goto again;
case '<':
if (PeekChar() == '#')
{
_tokenStart = _currentIndex - 1;
SkipChar();
ScanBlockComment();
goto again;
}
break;
case '`':
char c1 = GetChar();
if (c1 == '\n' || c1 == '\r')
{
ScanLineContinuation(c1);
goto again;
}
if (char.IsWhiteSpace(c1))
{
SkipWhiteSpace();
goto again;
}
UngetChar();
break;
default:
if (c.IsWhitespace())
{
SkipWhiteSpace();
goto again;
}
break;
}
UngetChar();
}
private void SkipWhiteSpace()
{
while (true)
{
char c = PeekChar();
if (!c.IsWhitespace())
{
break;
}
SkipChar();
}
}
private void ScanNewline(char c)
{
_tokenStart = _currentIndex - 1;
NormalizeCRLF(c);
// Memory optimization: only create the token if it will be stored
if (TokenList != null)
{
NewToken(TokenKind.NewLine);
}
}
private void ScanSemicolon()
{
_tokenStart = _currentIndex - 1;
// Memory optimization: only create the token if it will be stored
if (TokenList != null)
{
NewToken(TokenKind.Semi);
}