forked from joao-neves95/CSharpToTypescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyntaxTranslationFactory.cs
89 lines (77 loc) · 2.99 KB
/
SyntaxTranslationFactory.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
/*
* Copyright (c) 2019 João Pedro Martins Neves (shivayl) - All Rights Reserved.
*
* CSharpToTypescript is licensed under the GNU Lesser General Public License (LGPL),
* version 3, located in the root of this project, under the name "LICENSE.md".
*
*/
using Microsoft.CodeAnalysis;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace RoslynTypeScript.Translation
{
public static class TF
{
private static Dictionary<Type, Type> _mapType = new Dictionary<Type, Type>();
static TF()
{
}
public static T Get<T>(SyntaxNode syntaxNode, SyntaxTranslation parent) where T : SyntaxTranslation
{
try
{
return (T)Get(syntaxNode, parent);
}
catch (Exception exc)
{
// Capture only the exception that caused the error. Ignore the un-winding of the stack.
// Format the exception so it can be visible.
if (exc != null && exc.Message != "Exception has been thrown by the target of an invocation.")
{
string delimiter = new String('=', 80);
string exceptionLine = string.Format("{1}{3}{1}{1}{0}{1}{2}{1}{1}{3}{1}", exc.Message, Environment.NewLine, syntaxNode.GetText().ToString(), delimiter);
throw new Exception(exceptionLine);
}
throw;
}
}
public static T VirtualGet<T>(string code) where T : SyntaxTranslation, new()
{
return new T() { SyntaxString = code };
}
public static SyntaxTranslation Get(SyntaxNode node, SyntaxTranslation parent)
{
Type type = node.GetType();
Type newType = FindMatchedType( type );
SyntaxTranslation translation = (SyntaxTranslation)Activator.CreateInstance( newType, node, parent );
return translation;
}
private static Type FindMatchedType(Type type)
{
if (_mapType.ContainsKey( type ))
{
return _mapType[type];
}
Assembly assembly = typeof( TF ).Assembly;
var newType = assembly.GetType( GetTranslationName( type.Name ) );
if (newType == null)
{
return typeof( GenericTranslation );
}
return newType;
}
private static string GetTranslationName(string syntaxNodeName)
{
string name = syntaxNodeName.Remove( syntaxNodeName.Length - 6 );
return "RoslynTypeScript.Translation." + name + "Translation";
}
public static void RegisterType<TSyntax, TTransaltion>()
where TSyntax : SyntaxNode
where TTransaltion : SyntaxTranslation
{
_mapType[typeof( TSyntax )] = typeof( TTransaltion );
}
}
}