Repository navigation
Expand file tree
/
Copy pathUtils.cs
More file actions
1473 lines (1261 loc) · 48.8 KB
/
Copy pathUtils.cs
File metadata and controls
1473 lines (1261 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
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 2017 YANG Huan (sy.yanghuan@gmail.com).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using CSharpLua.LuaAst;
namespace CSharpLua {
public sealed class CmdArgumentException : Exception {
public CmdArgumentException(string message) : base(message) {
}
}
public sealed class CompilationErrorException : Exception {
public SyntaxNode SyntaxNode { get; }
public CompilationErrorException(string message) : base(message) {
}
public CompilationErrorException(SyntaxNode node, string message)
: base($"{node.GetLocationString()}: {message}, please refactor your code.") {
SyntaxNode = node;
}
public CompilationErrorException With(SyntaxNode node) {
if (SyntaxNode == null) {
return new CompilationErrorException(node, Message);
}
return this;
}
}
public sealed class BugErrorException : Exception {
private const string kIssueAddress = "Compiler has a bug, thanks to commit issue at https://github.com/yanghuan/CSharp.lua/issue";
public BugErrorException(SyntaxNode node, Exception e)
: base($"{node.GetLocationString()}: {kIssueAddress}", e) {
}
public BugErrorException(string message) : base($"{message}: {kIssueAddress}") {
}
}
public sealed class ConcurrentList<T> : ConcurrentBag<T> {
}
public sealed class ConcurrentHashSet<T> : IEnumerable<T> {
private readonly ConcurrentDictionary<T, bool> dict_;
public ConcurrentHashSet() {
dict_ = new();
}
public ConcurrentHashSet(IEqualityComparer<T> comparer) {
dict_ = new(comparer);
}
public bool Add(T v) {
return dict_.TryAdd(v, true);
}
public bool Contains(T v) {
return dict_.ContainsKey(v);
}
public IEnumerator<T> GetEnumerator() {
return dict_.Keys.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void UnionWith(IEnumerable<T> collection) {
foreach (var v in collection) {
Add(v);
}
}
}
public enum PropertyMethodKind {
Field = 0,
Both = 1,
GetOnly = 2,
SetOnly = 3,
}
public static class Utility {
public static T First<T>(this IList<T> list) {
return list[0];
}
public static T Last<T>(this IList<T> list) {
return list[list.Count - 1];
}
public static bool IsNullOrEmpty<T>(this IList<T> list) {
return list == null || list.Count == 0;
}
public static T GetOrDefault<T>(this IList<T> list, int index, T v = default) {
return index >= 0 && index < list.Count ? list[index] : v;
}
public static void RemoveRange<T>(this List<T> list, int index) {
list.RemoveRange(index, list.Count - index);
}
public static void RemoveAtLast<T>(this List<T> list) {
list.RemoveAt(list.Count - 1);
}
public static T GetOrDefault<K, T>(this IDictionary<K, T> dict, K key, T t = default) {
if (dict.TryGetValue(key, out T v)) {
return v;
}
return t;
}
public static bool TryAdd<K, V>(this Dictionary<K, HashSet<V>> dict, K key, V value) {
var set = dict.GetOrDefault(key);
if (set == null) {
set = new HashSet<V>();
dict.Add(key, set);
}
return set.Add(value);
}
public static T GetOrAdd<K, T>(this IDictionary<K, T> dict, K key, Func<K, T> valueFunc) {
if (!dict.TryGetValue(key, out var v)) {
v = valueFunc(key);
dict.Add(key, v);
}
return v;
}
public static bool Contains<K, V>(this Dictionary<K, HashSet<V>> dict, K key, V value) {
var set = dict.GetOrDefault(key);
return set != null && set.Contains(value);
}
public static void AddAt<T>(this IList<T> list, int index, T v) {
if (index < list.Count) {
list[index] = v;
} else {
int count = index - list.Count;
for (int i = 0; i < count; ++i) {
list.Add(default);
}
list.Add(v);
}
}
public static int IndexOf<T>(this IEnumerable<T> source, T value) {
var comparer = EqualityComparer<T>.Default;
return source.IndexOf(i => comparer.Equals(i, value));
}
public static int IndexOf<T>(this IEnumerable<T> source, Predicate<T> match) {
int index = 0;
foreach (var item in source) {
if (match(item)) {
return index;
}
++index;
}
return -1;
}
public static int FindIndex(this string s, int startIndex, Predicate<char> match) {
for (int i = startIndex; i < s.Length; ++i) {
if (match(s[i])) {
return i;
}
}
return -1;
}
public static T[] ArrayOf<T>(this T t) {
return new[] { t };
}
public static T[] ArrayOf<T>(this T t, T a) {
return new[] { t, a };
}
public static T[] ArrayOf<T>(this T t, params T[] args) {
T[] array = new T[args.Length + 1];
array[0] = t;
Array.Copy(args, 0, array, 1, args.Length);
return array;
}
public static Dictionary<string, string[]> GetCommandLines(string[] args) {
Dictionary<string, string[]> cmds = new Dictionary<string, string[]>();
string key = "";
List<string> values = new List<string>();
foreach (string arg in args) {
string i = arg.Trim();
if (i.StartsWith("-")) {
if (!string.IsNullOrEmpty(key)) {
cmds.Add(key, values.ToArray());
key = "";
values.Clear();
}
key = i;
} else {
values.Add(i);
}
}
if (!string.IsNullOrEmpty(key)) {
cmds.Add(key, values.ToArray());
}
return cmds;
}
public static string GetArgument(this Dictionary<string, string[]> args, string name, bool isOption = false) {
string[] values = args.GetOrDefault(name);
if (values == null || values.Length == 0) {
if (isOption) {
return null;
}
throw new CmdArgumentException(name + " is not found");
}
return values[0];
}
public static string GetCurrentDirectory(string path) {
const string CurrentDirectorySign1 = "~/";
const string CurrentDirectorySign2 = "~\\";
if (path.StartsWith(CurrentDirectorySign1)) {
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path[CurrentDirectorySign1.Length..]);
}
if (path.StartsWith(CurrentDirectorySign2)) {
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path[CurrentDirectorySign2.Length..]);
}
return Path.Combine(Environment.CurrentDirectory, path);
}
public static string[] Split(string s, bool isPath = true) {
HashSet<string> list = new HashSet<string>();
if (!string.IsNullOrEmpty(s)) {
string[] array = s.Split(';', ',');
foreach (string i in array) {
list.Add(isPath ? GetCurrentDirectory(i) : i);
}
}
return list.ToArray();
}
public static string ReplaceNewline(this string s) {
return s.Replace("\r\n", "\n").Replace('\r', '\n');
}
public static string LastName(this string s) {
int pos = s.LastIndexOf('.');
if (pos != -1) {
return s[(pos + 1)..];
}
return s;
}
public static string TrimEnd(this string s, string v) {
if (s.EndsWith(v)) {
return s.Remove(s.Length - v.Length);
}
return s;
}
public static LuaStringLiteralExpressionSyntax ToStringLiteral(this string s) {
return new(s);
}
public static bool IsPrivate(this ISymbol symbol) {
return symbol.DeclaredAccessibility == Accessibility.Private;
}
public static bool IsPublic(this ISymbol symbol) {
return symbol.DeclaredAccessibility == Accessibility.Public;
}
public static bool IsPrivate(this SyntaxTokenList modifiers) {
foreach (var modifier in modifiers) {
switch (modifier.Kind()) {
case SyntaxKind.PrivateKeyword: {
return true;
}
case SyntaxKind.PublicKeyword:
case SyntaxKind.InternalKeyword:
case SyntaxKind.ProtectedKeyword: {
return false;
}
}
}
return true;
}
public static bool IsStatic(this SyntaxTokenList modifiers) {
return modifiers.Any(SyntaxKind.StaticKeyword);
}
public static bool IsAbstract(this SyntaxTokenList modifiers) {
return modifiers.Any(SyntaxKind.AbstractKeyword);
}
public static bool IsExtern(this SyntaxTokenList modifiers) {
return modifiers.Any(SyntaxKind.ExternKeyword);
}
public static bool IsReadOnly(this SyntaxTokenList modifiers) {
return modifiers.Any(SyntaxKind.ReadOnlyKeyword);
}
public static bool IsConst(this SyntaxTokenList modifiers) {
return modifiers.Any(SyntaxKind.ConstKeyword);
}
public static bool IsParams(this SyntaxTokenList modifiers) {
return modifiers.Any(SyntaxKind.ParamsKeyword);
}
public static bool IsPartial(this SyntaxTokenList modifiers) {
return modifiers.Any(SyntaxKind.PartialKeyword);
}
public static bool IsOutOrRef(this SyntaxTokenList modifiers) {
return modifiers.Any(i => i.IsKind(SyntaxKind.OutKeyword) || i.IsKind(SyntaxKind.RefKeyword));
}
public static bool IsOutOrRef(this SyntaxToken token) {
return token.IsKind(SyntaxKind.OutKeyword) || token.IsKind(SyntaxKind.RefKeyword);
}
public static bool EQ(this ISymbol a, ISymbol b) {
return SymbolEqualityComparer.Default.Equals(a, b);
}
public static bool IsBasicType(this ITypeSymbol type) {
return type.SpecialType is >= SpecialType.System_Enum and <= SpecialType.System_Double;
}
public static bool IsStringType(this ITypeSymbol type) {
return type.SpecialType == SpecialType.System_String;
}
public static bool IsDelegateType(this ITypeSymbol type) {
return type.TypeKind == TypeKind.Delegate;
}
public static bool IsIntegerType(this ITypeSymbol type, bool withNullable = true) {
if (withNullable && type.IsNullableType()) {
type = ((INamedTypeSymbol)type).TypeArguments.First();
}
return type.SpecialType is >= SpecialType.System_SByte and <= SpecialType.System_UInt64;
}
public static bool IsCastIntegerType(this ITypeSymbol type) {
return type.SpecialType is >= SpecialType.System_Char and <= SpecialType.System_UInt64;
}
public static bool IsNumberType(this ITypeSymbol type, bool withNullable = true) {
if (withNullable && type.IsNullableType()) {
type = ((INamedTypeSymbol)type).TypeArguments.First();
}
return type.SpecialType is >= SpecialType.System_SByte and <= SpecialType.System_Double;
}
public static bool IsDoubleOrFloatType(this ITypeSymbol type, bool withNullable = true) {
if (withNullable && type.IsNullableType()) {
type = ((INamedTypeSymbol)type).TypeArguments.First();
}
return type.SpecialType is SpecialType.System_Double or SpecialType.System_Single;
}
public static bool IsBoolType(this ITypeSymbol type, bool withNullable = true) {
if (withNullable && type.IsNullableType()) {
type = ((INamedTypeSymbol)type).TypeArguments.First();
}
return type.SpecialType == SpecialType.System_Boolean;
}
public static bool IsNullableType(this ITypeSymbol type) {
return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
}
public static bool IsNullableType(this ITypeSymbol type, out ITypeSymbol elementType) {
elementType = type.NullableElementType();
return elementType != null;
}
public static ITypeSymbol NullableElementType(this ITypeSymbol type) {
return type.IsNullableType() ? ((INamedTypeSymbol)type).TypeArguments.First() : null;
}
public static bool IsNullableWithBasicElementType(this ITypeSymbol type) {
return type.IsNullableType(out var elementType)
&& (elementType.IsBasicType() || type.SpecialType == SpecialType.System_DateTime || type.IsTimeSpanType());
}
public static bool IsEnumType(this ITypeSymbol type, out ITypeSymbol symbol, out bool isNullable) {
if (type.TypeKind == TypeKind.Enum) {
symbol = type;
isNullable = false;
return true;
}
var nullableElementType = type.NullableElementType();
if (nullableElementType is {TypeKind: TypeKind.Enum}) {
symbol = nullableElementType;
isNullable = true;
return true;
}
symbol = null;
isNullable = false;
return false;
}
public static bool IsImmutable(this ITypeSymbol type) {
bool isImmutable = (type.IsValueType && type.IsDefinition) || type.IsStringType() || type.IsDelegateType();
return isImmutable;
}
public static bool IsSystemTuple(this ITypeSymbol type) {
return type.Name == "Tuple" && type.ContainingNamespace.Name == "System";
}
public static bool IsSystemIndex(this ITypeSymbol type) {
return type.Name == "Index" && type.ContainingNamespace.Name == "System";
}
private static bool IsSystemIComparableT(this INamedTypeSymbol type) {
return type.Name == "IComparable" && type.ContainingNamespace.Name == "System" && type.IsGenericType;
}
private static bool IsSystemIEquatableT(this INamedTypeSymbol type) {
return type.Name == "IEquatable" && type.ContainingNamespace.Name == "System" && type.IsGenericType;
}
private static bool IsSystemIFormattable(this INamedTypeSymbol type) {
return type.Name == "IFormattable" && type.ContainingNamespace.Name == "System";
}
public static bool IsBasicTypInterface(this INamedTypeSymbol type) {
return type.TypeKind == TypeKind.Interface && (type.IsSystemIComparableT() || type.IsSystemIEquatableT() || type.IsSystemIFormattable());
}
public static bool IsSystemTask(this ITypeSymbol symbol) {
return (symbol.Name is "Task" or "ValueTask")
&& symbol.ContainingNamespace.Name == "Tasks"
&& symbol.ContainingNamespace.ContainingNamespace.Name == "Threading"
&& symbol.ContainingNamespace.ContainingNamespace.ContainingNamespace.Name == "System";
}
public static bool IsInterfaceImplementation<T>(this T symbol) where T : ISymbol {
if (!symbol.IsStatic) {
var type = symbol.ContainingType;
if (type != null) {
var interfaceSymbols = type.AllInterfaces.SelectMany(i => i.GetMembers().OfType<T>());
return interfaceSymbols.Any(i => symbol.Equals(type.FindImplementationForInterfaceMember(i)));
}
}
return false;
}
public static IEnumerable<T> InterfaceImplementations<T>(this T symbol) where T : ISymbol {
if (!symbol.IsStatic) {
var type = symbol.ContainingType;
if (type != null) {
var interfaceSymbols = type.AllInterfaces.SelectMany(i => i.GetMembers().OfType<T>());
return interfaceSymbols.Where(i => symbol.Equals(type.FindImplementationForInterfaceMember(i)));
}
}
return Array.Empty<T>();
}
public static bool IsFromCode(this ISymbol symbol) {
return !symbol.DeclaringSyntaxReferences.IsEmpty;
}
public static bool IsFromAssembly(this ISymbol symbol) {
return !symbol.IsFromCode();
}
public static bool IsOverridable(this ISymbol symbol) {
return !symbol.IsStatic && (symbol.IsAbstract || symbol.IsVirtual || symbol.IsOverride);
}
public static ISymbol OverriddenSymbol(this ISymbol symbol) {
switch (symbol.Kind) {
case SymbolKind.Method: {
IMethodSymbol methodSymbol = (IMethodSymbol)symbol;
return methodSymbol.OverriddenMethod;
}
case SymbolKind.Property: {
IPropertySymbol propertySymbol = (IPropertySymbol)symbol;
return propertySymbol.OverriddenProperty;
}
case SymbolKind.Event: {
IEventSymbol eventSymbol = (IEventSymbol)symbol;
return eventSymbol.OverriddenEvent;
}
}
return null;
}
public static bool IsOverridden(this ISymbol symbol, ISymbol superSymbol) {
while (true) {
ISymbol overriddenSymbol = symbol.OverriddenSymbol();
if (overriddenSymbol != null) {
CheckOriginalDefinition(ref overriddenSymbol);
if (overriddenSymbol.EQ(superSymbol)) {
return true;
}
symbol = overriddenSymbol;
} else {
return false;
}
}
}
public static bool HasMetadataAttribute(this ISymbol symbol) {
var node = symbol.GetDeclaringSyntaxNode();
if (node != null) {
return node.HasCSharpLuaAttribute(LuaDocumentStatement.AttributeFlags.Metadata);
}
return false;
}
public static bool HasParamsAttribute(this ISymbol symbol) {
var node = symbol.GetDeclaringSyntaxNode();
if (node != null) {
return node.HasCSharpLuaAttribute(LuaDocumentStatement.AttributeFlags.Params);
}
return false;
}
public static bool HasCSharpLuaAttribute(this SyntaxNode node, LuaDocumentStatement.AttributeFlags attribute) {
return node.HasCSharpLuaAttribute(attribute, out _);
}
public static bool HasCSharpLuaAttribute(this SyntaxNode node, LuaDocumentStatement.AttributeFlags attribute, out string text) {
text = null;
var documentTrivia = node.GetLeadingTrivia().FirstOrDefault(i => i.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia));
if (documentTrivia != default) {
string document = documentTrivia.ToString();
if (document.Contains(LuaDocumentStatement.ToString(attribute))) {
text = document;
return true;
}
}
return false;
}
public static string GetCodeTemplateFromAttribute(this ISymbol symbol) {
var node = symbol.GetDeclaringSyntaxNode();
if (node != null) {
if (symbol.Kind == SymbolKind.Field) {
node = node.Parent.Parent;
}
if (node.HasCSharpLuaAttribute(LuaDocumentStatement.AttributeFlags.Template, out string text)) {
return GetCodeTemplateFromAttributeText(text);
}
} else {
string xml = symbol.GetDocumentationCommentXml();
if (xml != null) {
return GetCodeTemplateFromAttributeText(xml);
}
}
return null;
}
private static readonly Regex codeTemplateAttributeRegex_ = new(@"@CSharpLua.Template\s*=\s*(.+)\s*", RegexOptions.Compiled);
private static string GetCodeTemplateFromAttributeText(string document) {
var matches = codeTemplateAttributeRegex_.Matches(document);
if (matches.Count > 0) {
string text = matches[0].Groups[1].Value;
return text.Trim().Trim('"');
}
return null;
}
public static bool IsAssignment(this SyntaxKind kind) {
return kind is >= SyntaxKind.SimpleAssignmentExpression and <= SyntaxKind.RightShiftAssignmentExpression;
}
public static bool IsTupleDeclaration(this SyntaxKind kind) {
return kind is SyntaxKind.DeclarationExpression or SyntaxKind.TupleExpression;
}
public static bool IsTypeDeclaration(this SyntaxKind kind) {
return kind is >= SyntaxKind.ClassDeclaration and <= SyntaxKind.EnumDeclaration;
}
public static bool IsLiteralExpression(this SyntaxKind kind) {
return kind is >= SyntaxKind.NumericLiteralExpression and <= SyntaxKind.DefaultLiteralExpression;
}
public static bool IsSystemLinqEnumerable(this INamedTypeSymbol symbol) {
return symbol.Name == "Enumerable" && symbol.ContainingNamespace.Name == "Linq" && symbol.ContainingNamespace.ContainingNamespace.Name == "System";
}
public static string GetLocationString(this SyntaxNode node) {
var location = node.SyntaxTree.GetLocation(node.Span);
var methodInfo = location.GetType().GetMethod("GetDebuggerDisplay", BindingFlags.Instance | BindingFlags.NonPublic);
return (string)methodInfo.Invoke(location, null);
}
public static bool IsGetExpressionNode(this ExpressionSyntax node) {
bool isGet;
if (!node.Parent.Kind().IsAssignment()) {
isGet = true;
} else {
var assignment = (AssignmentExpressionSyntax)node.Parent;
isGet = assignment.Right == node;
}
return isGet;
}
public static bool IsNull(this ExpressionSyntax node) {
return node == null || node.IsKind(SyntaxKind.NullLiteralExpression);
}
public static bool IsSubclassOf(this ITypeSymbol child, ITypeSymbol parent) {
if (parent.SpecialType == SpecialType.System_Object) {
return true;
}
ITypeSymbol p = child;
if (p.EQ(parent)) {
return false;
}
while (p != null) {
if (p.EQ(parent)) {
return true;
}
p = p.BaseType;
}
return false;
}
private static bool IsImplementInterface(this ITypeSymbol implementType, ITypeSymbol interfaceType) {
Contract.Assert(interfaceType.TypeKind == TypeKind.Interface);
ITypeSymbol t = implementType;
while (t != null) {
var interfaces = implementType.AllInterfaces;
foreach (var i in interfaces) {
if (i.EQ(interfaceType) || i.IsImplementInterface(interfaceType)) {
return true;
}
}
t = t.BaseType;
}
return false;
}
private static bool IsBaseNumberType(this SpecialType specialType) {
return specialType is >= SpecialType.System_Char and <= SpecialType.System_Double;
}
public static bool IsNumberTypeAssignableFrom(this ITypeSymbol left, ITypeSymbol right) {
if (left.SpecialType.IsBaseNumberType() && right.SpecialType.IsBaseNumberType()) {
if (left.EQ(right)) {
return true;
}
SpecialType begin;
switch (right.SpecialType) {
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Byte: {
begin = SpecialType.System_Int16;
break;
}
case SpecialType.System_Int16:
case SpecialType.System_UInt16: {
begin = SpecialType.System_Int32;
break;
}
case SpecialType.System_Int32:
case SpecialType.System_UInt32: {
begin = SpecialType.System_Int64;
break;
}
case SpecialType.System_Int64:
case SpecialType.System_UInt64: {
begin = SpecialType.System_Decimal;
break;
}
default: {
begin = SpecialType.System_Double;
break;
}
}
SpecialType end = SpecialType.System_Double;
return left.SpecialType >= begin && left.SpecialType <= end;
}
return false;
}
public static bool Is(this ITypeSymbol left, ITypeSymbol right) {
if (left.EQ(right)) {
return true;
}
if (left.IsSubclassOf(right)) {
return true;
}
if (right.TypeKind == TypeKind.Interface) {
return left.IsImplementInterface(right);
}
return false;
}
private static void CheckSymbolDefinition<T>(ref T symbol) where T : class, ISymbol {
var originalDefinition = (T)symbol.OriginalDefinition;
if (originalDefinition != symbol) {
symbol = originalDefinition;
}
}
public static void CheckMethodDefinition(ref IMethodSymbol symbol) {
if (symbol.IsExtensionMethod) {
if (symbol.ReducedFrom != null && !symbol.ReducedFrom.EQ(symbol)) {
symbol = symbol.ReducedFrom;
} else {
CheckSymbolDefinition(ref symbol);
}
} else {
CheckSymbolDefinition(ref symbol);
}
}
public static void CheckOriginalDefinition(ref ISymbol symbol) {
if (symbol.Kind == SymbolKind.Method) {
IMethodSymbol methodSymbol = (IMethodSymbol)symbol;
CheckMethodDefinition(ref methodSymbol);
if (!methodSymbol.EQ(symbol)) {
symbol = methodSymbol;
}
} else {
CheckSymbolDefinition(ref symbol);
}
}
public static bool IsMainEntryPoint(this IMethodSymbol symbol) {
if (symbol.IsStatic && symbol.MethodKind == MethodKind.Ordinary && symbol.TypeArguments.IsEmpty && symbol.ContainingType.TypeArguments.IsEmpty && symbol.Name == "Main") {
if (symbol.ReturnsVoid || symbol.ReturnType.SpecialType == SpecialType.System_Int32) {
if (symbol.Parameters.IsEmpty) {
return true;
}
if (symbol.Parameters.Length == 1) {
var parameterType = symbol.Parameters[0].Type;
if (parameterType.TypeKind == TypeKind.Array) {
var arrayType = (IArrayTypeSymbol)parameterType;
if (arrayType.ElementType.SpecialType == SpecialType.System_String) {
return true;
}
}
}
}
}
return false;
}
public static bool IsExtendSelf(INamedTypeSymbol typeSymbol, INamedTypeSymbol baseTypeSymbol) {
if (baseTypeSymbol.IsGenericType) {
foreach (var baseTypeArgument in baseTypeSymbol.TypeArguments) {
if (baseTypeSymbol.Kind != SymbolKind.TypeParameter) {
if (!baseTypeArgument.EQ(typeSymbol) && baseTypeArgument.Is(typeSymbol)) {
return true;
}
}
}
}
return false;
}
public static bool IsTimeSpanType(this ITypeSymbol typeSymbol) {
return typeSymbol.IsValueType && typeSymbol.ContainingNamespace.Name == "System" && typeSymbol.Name == "TimeSpan";
}
public static bool IsKeyValuePairType(this ITypeSymbol typeSymbol) {
return typeSymbol.IsValueType && typeSymbol.Name == "KeyValuePair" && typeSymbol.ContainingNamespace.Name == "Generic";
}
public static bool IsGenericIEnumerableType(this ITypeSymbol typeSymbol) {
return typeSymbol.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T;
}
public static bool IsGenericIAsyncEnumerableType(this ITypeSymbol typeSymbol) {
return typeSymbol.Name == "IAsyncEnumerable" && typeSymbol.IsCollectionType();
}
public static bool IsCustomValueType(this ITypeSymbol typeSymbol) {
return typeSymbol.IsValueType
&& typeSymbol.TypeKind != TypeKind.Enum
&& typeSymbol.TypeKind != TypeKind.Pointer
&& (typeSymbol.SpecialType == SpecialType.None && !typeSymbol.IsTimeSpanType());
}
public static bool IsMaybeValueType(this ITypeSymbol typeSymbol) {
if (typeSymbol.IsValueType) {
return true;
}
if (typeSymbol.IsReferenceType) {
return false;
}
return typeSymbol.TypeKind == TypeKind.TypeParameter;
}
public static bool IsExplicitInterfaceImplementation(this ISymbol symbol) {
switch (symbol.Kind) {
case SymbolKind.Property: {
IPropertySymbol property = (IPropertySymbol)symbol;
if (property.GetMethod != null) {
if (property.GetMethod.MethodKind == MethodKind.ExplicitInterfaceImplementation) {
return true;
}
if (property.SetMethod is {MethodKind: MethodKind.ExplicitInterfaceImplementation}) {
return true;
}
}
break;
}
case SymbolKind.Method: {
IMethodSymbol method = (IMethodSymbol)symbol;
if (method.MethodKind == MethodKind.ExplicitInterfaceImplementation) {
return true;
}
break;
}
}
return false;
}
public static bool IsExportSyntaxTrivia(this SyntaxTrivia syntaxTrivia, SyntaxNode rootNode) {
SyntaxKind kind = syntaxTrivia.Kind();
switch (kind) {
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineDocumentationCommentTrivia:
case SyntaxKind.DisabledTextTrivia:
case SyntaxKind.RegionDirectiveTrivia:
case SyntaxKind.EndRegionDirectiveTrivia: {
var span = rootNode.IsKind(SyntaxKind.CompilationUnit) ? rootNode.FullSpan : rootNode.Span;
return span.Contains(syntaxTrivia.Span);
}
default:
return false;
}
}
public static ITypeSymbol GetIEnumerableElementType(this ITypeSymbol symbol) {
var interfaceType = symbol.IsGenericIEnumerableType() ? (INamedTypeSymbol)symbol : symbol.AllInterfaces.FirstOrDefault(i => i.IsGenericIEnumerableType());
return interfaceType?.TypeArguments.First();
}
public static ITypeSymbol GetIAsyncEnumerableElementType(this ITypeSymbol symbol) {
var interfaceType = symbol.IsGenericIAsyncEnumerableType() ? (INamedTypeSymbol)symbol : symbol.AllInterfaces.FirstOrDefault(i => i.IsGenericIAsyncEnumerableType());
return interfaceType?.TypeArguments.First();
}
public static IEnumerable<ITypeSymbol> GetTupleElementTypes(this ITypeSymbol typeSymbol) {
var nameSymbol = (INamedTypeSymbol)typeSymbol;
return nameSymbol.TupleElements.Select(i => i.Type);
}
public static int GetTupleElementIndex(this IFieldSymbol fieldSymbol) {
Contract.Assert(fieldSymbol.ContainingType.IsTupleType);
var fields = fieldSymbol.ContainingType.GetMembers().OfType<IFieldSymbol>().Where(i => i.CorrespondingTupleField.EQ(i));
int index = fields.IndexOf(fieldSymbol.CorrespondingTupleField);
Contract.Assert(index != -1);
return index + 1;
}
public static bool IsStringConstNotInline(this IFieldSymbol field) {
if (field.IsConst && field.Type.SpecialType == SpecialType.System_String && field.ConstantValue != null) {
if (((string)field.ConstantValue).Length > LuaSyntaxNodeTransform.kStringConstInlineCount) {
return true;
}
}
return false;
}
public static bool IsLocalVariableField(this IFieldSymbol field) {
if (!field.IsImplicitlyDeclared) {
if (!field.IsConst) {
return field.IsStatic && (field.IsPrivate() || field.IsReadOnly);
}
if (field.IsStringConstNotInline()) {
return true;
}
}
return false;
}
public static bool IsIndexerProperty(this ISymbol symbol) {
if (symbol.Kind == SymbolKind.Property) {
var propertySymbol = (IPropertySymbol)symbol;
return propertySymbol.IsIndexer;
}
return false;
}
public static bool IsAutoProperty(this IPropertySymbol symbol) {
var node = symbol.GetDeclaringSyntaxNode();
if (node != null) {
switch (node.Kind()) {
case SyntaxKind.PropertyDeclaration: {
var property = (PropertyDeclarationSyntax)node;
bool hasGet = false;
bool hasSet = false;
if (property.AccessorList != null) {
foreach (var accessor in property.AccessorList.Accessors) {
if (accessor.Body != null || accessor.ExpressionBody != null) {
if (accessor.IsKind(SyntaxKind.GetAccessorDeclaration)) {
Contract.Assert(!hasGet);
hasGet = true;
} else {
Contract.Assert(!hasSet);
hasSet = true;
}
}
}
} else {
Contract.Assert(!hasGet);
hasGet = true;
}
bool isField = !hasGet && !hasSet;
if (isField) {
if (property.HasCSharpLuaAttribute(LuaDocumentStatement.AttributeFlags.NoField)) {
isField = false;
}
}
return isField;
}
case SyntaxKind.IndexerDeclaration: {
return false;
}
case SyntaxKind.AnonymousObjectMemberDeclarator: {
return true;
}
case SyntaxKind.Parameter: {
return true;
}
default: {
throw new InvalidOperationException();
}
}
}
return false;
}
private static readonly Regex identifierRegex_ = new(@"^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled);