forked from nhabuiduc/TypescriptSyntaxPaste
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHelper.cs
More file actions
647 lines (543 loc) · 22.6 KB
/
Helper.cs
File metadata and controls
647 lines (543 loc) · 22.6 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
/*
* Copyright (c) 2019-2021 João Pedro Martins Neves (shivayl) - All Rights Reserved.
*
* CSharpToTypescript is licensed under the GPLv3.0 license (GNU General Public License v3.0),
* located in the root of this project, under the name "LICENSE.md".
*
*/
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using RoslynTypeScript.Constants;
using RoslynTypeScript.Translation;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RoslynTypeScript
{
public static class Helper
{
public static string GetAttributeList(SyntaxList<AttributeListSyntax> attributeList)
{
var attr = attributeList.ToString();
return string.IsNullOrWhiteSpace( attr ) ? string.Empty : "/*" + attr + "*/" + Environment.NewLine;
}
public static string NormalizeVariabeleName(string name)
{
if (name.StartsWith( "@" ))
{
name = "$" + name.Substring( 1 );
}
return name;
}
public static bool IsSupportOperator(string operatorStr)
{
switch (operatorStr)
{
case OperatorConstants.OperatorEquals:
case OperatorConstants.OperatorNotEqual:
case OperatorConstants.OperatorGreaterThan:
case OperatorConstants.OperatorLessThan:
case OperatorConstants.OperatorGreaterThanOrEqual:
case OperatorConstants.OperatorLessThanOrEqual:
return true;
}
return false;
}
public static string GetNewLineIfExist(string trivia)
{
return trivia.Contains( Environment.NewLine ) ? Environment.NewLine : "";
}
public static string GetNewLineIfExist(SyntaxTriviaList triviaList)
{
return triviaList.Any( f => f.IsKind( SyntaxKind.EndOfLineTrivia ) ) ? Environment.NewLine : "";
}
public static bool IsInKinds(SyntaxNode node, params SyntaxKind[] kinds)
{
return kinds.Any( f => node.IsKind( f ) );
}
public static string OperatorToMethod(string operatorStr)
{
switch (operatorStr)
{
case OperatorConstants.OperatorEquals: return OperatorConstants.MethodEquals;
case OperatorConstants.OperatorNotEqual: return OperatorConstants.MethodNotEqual;
case OperatorConstants.OperatorGreaterThan: return OperatorConstants.MethodGreaterThan;
case OperatorConstants.OperatorLessThan: return OperatorConstants.MethodLessThan;
case OperatorConstants.OperatorGreaterThanOrEqual: return OperatorConstants.MethodGreaterThanOrEqual;
case OperatorConstants.OperatorLessThanOrEqual: return OperatorConstants.MethodLessThanOrEqual;
}
throw new NotSupportedException();
}
public static bool IsInteger(SpecialType specialType)
{
return specialType == SpecialType.System_Int32
|| specialType == SpecialType.System_Int64
|| specialType == SpecialType.System_Int16
|| specialType == SpecialType.System_Byte
|| specialType == SpecialType.System_UInt16
|| specialType == SpecialType.System_UInt32
|| specialType == SpecialType.System_UInt64;
}
public static bool IsUnsignedInterger(SpecialType specialType)
{
return
specialType == SpecialType.System_UInt16
|| specialType == SpecialType.System_UInt32
|| specialType == SpecialType.System_UInt64;
}
public static bool IsNumber(SpecialType specialType)
{
if (IsInteger( specialType ))
{
return true;
}
switch (specialType)
{
case SpecialType.System_Double:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
return true;
}
return false;
}
public static string GetTSValueTypeToCheck(TypeTranslation type, ITypeSymbol typeSymbol)
{
if (Helper.IsNumber( typeSymbol.SpecialType ))
{
return "Number";
}
if (typeSymbol.SpecialType == SpecialType.System_Char)
{
return "TSChar";
}
if (typeSymbol.SpecialType == SpecialType.System_Boolean)
{
return "Boolean";
}
if (typeSymbol.TypeKind == TypeKind.Enum)
{
return "Number";
}
if (typeSymbol.IsValueType)
{
return type.Translate();
}
return null;
}
public static bool IsDefinedStruct(ITypeSymbol typeSymbol)
{
if (typeSymbol == null)
{
return false;
}
if (typeSymbol.IsReferenceType)
{
return false;
}
if (Helper.IsNumber( typeSymbol.SpecialType ))
{
return false;
}
if (typeSymbol.SpecialType == SpecialType.System_Char)
{
return false;
}
if (typeSymbol.SpecialType == SpecialType.System_Boolean)
{
return false;
}
if (typeSymbol.TypeKind == TypeKind.Enum)
{
return false;
}
if (typeSymbol.IsValueType)
{
return true;
}
return false;
}
public static string GetDefaultValue(TypeTranslation type)
{
if (type.Syntax.IsKind( SyntaxKind.BoolKeyword ))
{
return "false";
}
if (type.Syntax.IsKind( SyntaxKind.ObjectKeyword ))
{
return "null";
}
if (type.Syntax.IsKind( SyntaxKind.IntKeyword )
|| type.Syntax.IsKind( SyntaxKind.UIntKeyword )
|| type.Syntax.IsKind( SyntaxKind.FloatKeyword )
|| type.Syntax.IsKind( SyntaxKind.DecimalKeyword )
|| type.Syntax.IsKind( SyntaxKind.DoubleKeyword )
|| type.Syntax.IsKind( SyntaxKind.ByteKeyword )
|| type.Syntax.IsKind( SyntaxKind.LongKeyword )
|| type.Syntax.IsKind( SyntaxKind.ULongKeyword )
)
{
return "0";
}
return "null";
}
public static string GetDefaultValue(TypeTranslation type, ITypeSymbol typeSymbol)
{
if (Helper.IsNumber( typeSymbol.SpecialType ))
{
return "0";
}
if (typeSymbol.SpecialType == SpecialType.System_Char)
{
return "''";
}
if (typeSymbol.SpecialType == SpecialType.System_Boolean)
{
return "false";
}
if (typeSymbol.SpecialType == SpecialType.System_String)
{
return "null";
}
if (typeSymbol.TypeKind == TypeKind.Enum)
{
return "0";
}
if (typeSymbol.IsValueType)
{
if (type is GenericNameTranslation)
{
return $"<{type.Translate()}> structDefault({type.GetTypeIgnoreGeneric()})";
}
else
{
return $"structDefault({type.GetTypeIgnoreGeneric()})";
}
}
return "null";
}
public static string TranslateTypeFromSymbols(IEnumerable<ITypeSymbol> types, string ns)
{
var join = string.Join( ",", types.Select( f => TranslateTypeFromSymbol( f, ns ) ) );
return $"<{join}>";
}
public static string TranslateConvernsion(Conversion conversion, NamespaceDeclarationTranslation ns, string innerTranslation)
{
var name = Helper.GetUniqueHashName( conversion.MethodSymbol.OriginalDefinition );
var clss = Helper.GetClassOfMethod( conversion.MethodSymbol.OriginalDefinition );
var generic = string.Empty;
INamedTypeSymbol returnType = conversion.MethodSymbol.ReturnType as INamedTypeSymbol;
if (returnType.IsGenericType)
{
generic = Helper.TranslateTypeFromSymbols( returnType.TypeArguments, ns?.Name.Translate() );
}
var fullInvoke = $"{clss}.{name}";
if (ns != null)
{
fullInvoke = Helper.GetReduceNameWithNamespace( fullInvoke, ns.Name.Translate() );
}
fullInvoke = $"{fullInvoke}{generic}";
return $"{fullInvoke}({innerTranslation})";
}
public static string TranslateTypeFromSymbol(ITypeSymbol typeSymbol, string ns)
{
if (Helper.IsNumber( typeSymbol.SpecialType ))
{
return "number";
}
if (typeSymbol.SpecialType == SpecialType.System_Boolean)
{
return "boolean";
}
if (typeSymbol.SpecialType == SpecialType.System_String)
{
return "string";
}
if (typeSymbol.SpecialType == SpecialType.System_Array)
{
return "Array";
}
if (typeSymbol.SpecialType == SpecialType.System_DateTime)
{
return "Date";
}
//var result = typeSymbol.ToFullNameWithoutGeneric();
var nameType = typeSymbol as INamedTypeSymbol;
if (nameType == null || !nameType.IsGenericType)
{
return typeSymbol.ToFullNameGeneric();
}
var fullName = typeSymbol.ToFullNameWithoutGeneric();
fullName = GetReduceNameWithNamespace( fullName, ns );
return $"{fullName}<{TranslateTypeFromSymbols( nameType.TypeArguments, ns )}> ";
}
public static string GetReduceNameWithNamespace(string fullName, string ns)
{
if (string.IsNullOrEmpty( ns ))
{
return fullName;
}
var split = fullName.Split( '.' );
string namePrefix = string.Join( ".", split.Take( split.Length - 1 ) );
var common = FindCommonPrefix( namePrefix, ns );
if (string.IsNullOrWhiteSpace( common ))
{
return split.Last();
}
return $"{common}.{split.Last()}";
}
public static string GetPrefix(SyntaxTranslation syntax, SemanticModel semanticModel = null)
{
if (semanticModel == null)
{
semanticModel = syntax.GetSemanticModel();
}
var symbolInfo = semanticModel.GetSymbolInfo( syntax.Syntax );
string foundNsName = FindScopeName( syntax, semanticModel );
if (foundNsName != null)
{
string namespaceName = Helper.GetPrefixName( symbolInfo.Symbol );
string common = Helper.FindCommonPrefix( namespaceName, foundNsName );
string dot = string.IsNullOrEmpty( common ) ? "" : ".";
return $"{common}{dot}";
}
return null;
}
public static string FindScopeName(SyntaxTranslation syntax, SemanticModel semanticModel = null)
{
if (semanticModel == null)
{
semanticModel = syntax.GetSemanticModel();
}
var symbolInfo = semanticModel.GetSymbolInfo( syntax.Syntax );
string foundNsName = null;
var foundClssOrStr = (TypeDeclarationTranslation)syntax.TravelUpNotMe( f => f is ClassDeclarationTranslation || f is StructDeclarationTranslation );
if (foundClssOrStr != null)
{
var clssSemanticModel = foundClssOrStr.GetSemanticModel();
var clssOrStrSymbol = clssSemanticModel.GetDeclaredSymbol( foundClssOrStr.Syntax );
if (clssOrStrSymbol != null)
{
foundNsName = Helper.GetPrefixName( clssOrStrSymbol );
}
}
if (foundNsName == null)
{
if (symbolInfo.Symbol.Kind == SymbolKind.Namespace)
{
return null;
}
var foundNs = (NamespaceDeclarationTranslation)syntax.TravelUpNotMe( f => f is NamespaceDeclarationTranslation );
foundNsName = foundNs.Name.Translate();
}
return foundNsName;
}
public static string GetPrefixName(ISymbol symbol)
{
SymbolDisplayFormat format = new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.None );
if (symbol.ContainingType != null)
{
return symbol.ContainingType.ToDisplayString( format );
}
if (symbol.ContainingNamespace != null)
{
return symbol.ContainingNamespace.ToDisplayString( format );
}
return null;
}
public static string FindCommonPrefix(string typePrefix, string scope)
{
var typePrefixSplit = typePrefix.Split( '.' );
var containingPrefixSplit = scope.Split( '.' );
int length = Math.Min( typePrefixSplit.Length, containingPrefixSplit.Length );
List<string> result = new List<string>();
int i = 0;
for (i = 0; i < length; i++)
{
if (typePrefixSplit[i] != containingPrefixSplit[i])
{
break;
}
}
// what if the last part of contating namespace match with first part of prefix?
if (i < typePrefixSplit.Length && containingPrefixSplit.Last() == typePrefixSplit[i])
{
i--;
}
for (; i < typePrefixSplit.Length; i++)
{
result.Add( typePrefixSplit[i] );
}
return string.Join( ".", result );
}
public static string ApplyThis(SemanticModel semanticModel, SyntaxTranslation syntaxTranslation, string property)
{
SymbolInfo symbolInfo = semanticModel.GetSymbolInfo( syntaxTranslation.Syntax );
var found = (TypeDeclarationTranslation)syntaxTranslation.TravelUpNotMe( f => f is TypeDeclarationTranslation );
if (found != null)
{
var classSymbol = semanticModel.GetDeclaredSymbol( found.Syntax ) as INamedTypeSymbol;
if (classSymbol != null && IsEqualOrBaseOf( symbolInfo.Symbol.ContainingType, classSymbol ))
{
string prefixName = symbolInfo.Symbol.IsStatic ? classSymbol.Name : "this";
return $"{prefixName}.{property}";
}
}
return null;
}
public static SymbolDisplayFormat ConvertHashDisplayFormat =
new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType,
parameterOptions: SymbolDisplayParameterOptions.IncludeType );
public static string GetUniqueHashName(IMethodSymbol methodSymbol)
{
var str = methodSymbol.ToDisplayString( ConvertHashDisplayFormat );
string name = methodSymbol.Name;
if (name == ".ctor")
{
SymbolDisplayFormat format = new SymbolDisplayFormat( SymbolDisplayGlobalNamespaceStyle.Omitted,
SymbolDisplayTypeQualificationStyle.NameOnly, SymbolDisplayGenericsOptions.None,
SymbolDisplayMemberOptions.None, parameterOptions: SymbolDisplayParameterOptions.None );
var clssName = methodSymbol.ToDisplayString( format );
name = "ctor";
//if(clssName == "SyntaxTrivia" && )
//{
// name += "_C";
//}
}
var result = $"{name}_{Hash( str )}";
return result;
}
public static bool HasSource(this ISymbol symbol)
{
return symbol.Locations.Where( f => f.IsInSource ).Any();
}
public static string GetUnitHashNameIfRequire(IMethodSymbol methodSymbol)
{
// only consider our defined overload
if (!HasSource( methodSymbol ))
{
return methodSymbol.Name;
}
// always translate constructor
if (methodSymbol.Name == ".ctor")
{
return GetUniqueHashName( methodSymbol );
}
if (methodSymbol.OverriddenMethod != null)
{
return GetUnitHashNameIfRequire( methodSymbol.OverriddenMethod );
}
// check overloading in the same class
// ignore interface explicit
var overloadings = GetOverloading( methodSymbol );
if (overloadings.Length > 1)
{
return GetUniqueHashName( methodSymbol );
}
return methodSymbol.Name;
}
public static ISymbol[] GetMemberInInterfaces(this ITypeSymbol symbol, string member)
{
List<ISymbol> result = new List<ISymbol>();
result.AddRange( symbol.GetMembers( member ) );
result.AddRange( symbol.AllInterfaces.SelectMany( item => item.GetMembers( member ) ) );
return result.ToArray();
}
private static IMethodSymbol[] GetOverloading(this IMethodSymbol methodSymbol)
{
return methodSymbol.ContainingType.GetMembers( methodSymbol.Name ).OfType<IMethodSymbol>().ToArray();
}
public static string Hash(string str)
{
return Math.Abs( str.GetHashCode() ).ToString( "0000" ).Substring( 0, 4 );
}
public static T GetNodeFromSymbol<T>(this ISymbol symbol) where T : SyntaxNode
{
var sourceTree = symbol.Locations[0].SourceTree;
return (T)sourceTree.GetRoot().DescendantNodes( symbol.Locations[0].SourceSpan ).Last();
}
public static string ToFullNameWithoutGeneric(this ISymbol symbol)
{
return symbol.ToDisplayString( new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.None ) );
}
public static string ToFullNameGeneric(this ISymbol symbol)
{
return symbol.ToDisplayString( new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters ) );
}
public static string GetClassOfMethod(IMethodSymbol methodSymbol)
{
var displayFormat = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.None,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces );
return methodSymbol.ContainingType.ToDisplayString( displayFormat );
}
private static bool IsEqualOrBaseOf(INamedTypeSymbol nameTypeSymbol, INamedTypeSymbol classSymbol)
{
var current = classSymbol;
while (current != null)
{
if (current.ToString() == nameTypeSymbol.ToString())
{
return true;
}
current = current.BaseType;
}
return false;
}
public static string StripTypeParameter(string str)
{
var indx = str.IndexOf( "<" );
if (indx >= 0)
{
return str.Substring( 0, indx );
}
return str;
}
public static bool ApplyFunctionBindToCorrectContext(ExpressionTranslation exp)
{
if (exp == null || exp.Syntax == null)
{
return false;
}
var semanticModel = exp.GetSemanticModel();
if (semanticModel == null)
{
return false;
}
var identifierName = exp as IdentifierNameTranslation;
if (identifierName != null)
{
var symbol = semanticModel.GetSymbolInfo( exp.Syntax );
var method = symbol.Symbol as IMethodSymbol;
if (method == null || method.IsStatic)
{
return false;
}
identifierName.MethodNeedToBind = "this";
return true;
}
var memberAccess = exp as MemberAccessExpressionTranslation;
if (memberAccess != null && memberAccess.Name is IdentifierNameTranslation)
{
var symbol = semanticModel.GetSymbolInfo( memberAccess.Name.Syntax );
var method = symbol.Symbol as IMethodSymbol;
if (method == null || method.IsStatic)
{
return false;
}
((IdentifierNameTranslation)memberAccess.Name).MethodNeedToBind = memberAccess.Expression.Translate();
return true;
}
return false;
}
}
}