-
Notifications
You must be signed in to change notification settings - Fork 3
/
Transpiler.cs
278 lines (231 loc) · 9.04 KB
/
Transpiler.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
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace cs2ts
{
public class Transpiler : CSharpSyntaxWalker
{
private readonly IList<string> _output;
private int _indent;
public Transpiler(string code) : base(SyntaxWalkerDepth.Node)
{
_output = new List<string>();
_indent = 0;
var tree = CSharpSyntaxTree.ParseText(code);
var root = tree.GetRoot();
Visit(root);
}
private string GetIndentation()
{
return new string(' ', _indent * 4);
}
private void Emit(string text, params object[] args)
{
var indentation = GetIndentation();
if (!args.Any())
_output.Add(string.Concat(indentation, text));
else
_output.Add(string.Format(string.Concat(indentation, text), args));
}
private string GetMappedType(TypeSyntax type)
{
if (type.ToString() == "void")
return "void";
if (type.ToString().EndsWith("Exception"))
return type.ToString();
return type.ToString().StartsWith("int") ? "number" : "string";
}
private static string GetVisibilityModifier(SyntaxTokenList tokens)
{
return tokens.Any(m => m.Kind() == SyntaxKind.PublicKeyword) ? "public" : "private";
}
private Transpiler.BlockScope IndentedBracketScope()
{
return new BlockScope(this);
}
private Transpiler.BlockScope IndentedBracketScope(SyntaxNode node)
{
return new BlockScope(this, node.Kind() == SyntaxKind.Block);
}
public void AddIndent()
{
_indent += 1;
}
public void RemoveIndent()
{
_indent -= 1;
}
public string ToTypeScript()
{
return string.Join(Environment.NewLine, _output);
}
public override void VisitBlock(BlockSyntax node)
{
foreach (var statement in node.Statements)
{
base.Visit(statement);
}
}
public override void VisitClassDeclaration(ClassDeclarationSyntax node)
{
string modifier = GetVisibilityModifier(node.Modifiers);
Emit(string.Join(" ", modifier, "class", node.Identifier.Text));
using (IndentedBracketScope())
{
base.VisitClassDeclaration(node);
}
}
public override void VisitFieldDeclaration(FieldDeclarationSyntax node)
{
string visibility = GetVisibilityModifier(node.Modifiers);
foreach (var identifier in node.Declaration.Variables)
{
Emit(string.Format("{0} {1}: {2};", visibility, identifier.GetText(), GetMappedType(node.Declaration.Type)));
}
}
public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
{
string visibility = GetVisibilityModifier(node.Modifiers);
var parameters = string.Format(
"({0})",
node.ParameterList
.Parameters
.Select(p => string.Format("{0}: {1}", p.Identifier.Text, GetMappedType(p.Type)))
.ToCsv()
);
var methodSignature = string.Format("{0}{1}:", node.Identifier.Text, parameters);
Emit(String.Join(" ", visibility, methodSignature, this.GetMappedType(node.ReturnType)));
using (IndentedBracketScope())
{
VisitBlock(node.Body);
}
}
public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
{
Emit("module {0}", node.Name.ToString());
using (IndentedBracketScope())
{
base.VisitNamespaceDeclaration(node);
}
}
public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node)
{
string mappedType = GetMappedType(node.Type);
string visibility = GetVisibilityModifier(node.Modifiers);
if (!(node.AccessorList.Accessors.All(ad => ad.Body == null)))
{
foreach (var accessor in node.AccessorList.Accessors)
{
var signature = (accessor.Keyword.Kind() != SyntaxKind.GetKeyword ? String.Format("(value: {0})", mappedType) : string.Concat(": ", mappedType));
Emit(string.Format("{0} {1} {2}{3}", visibility, accessor.Keyword, node.Identifier.Text, signature));
using (IndentedBracketScope())
{
VisitBlock(accessor.Body);
}
}
}
else
{
Emit(string.Join(" ", visibility, string.Concat(node.Identifier.Text, ":"), mappedType + ";"));
}
}
public override void VisitTryStatement(TryStatementSyntax node)
{
Emit("try");
using (IndentedBracketScope())
{
VisitBlock(node.Block);
}
foreach (var @catch in node.Catches)
{
string arguments = String.Empty;
if (!(@catch.Declaration == null))
{
if (@catch.Declaration.Identifier != null)
arguments = string.Format(" ({0})", @catch.Declaration.Identifier.Text);
}
Emit("catch" + arguments);
using (IndentedBracketScope())
{
VisitBlock(@catch.Block);
}
}
}
public override void VisitExpressionStatement(ExpressionStatementSyntax node)
{
// TODO: Don't just emit the expression as-is. Need to process the nodes of the expression
Emit(node.ToString());
}
public override void VisitReturnStatement(ReturnStatementSyntax node)
{
Emit(node.ToString());
}
public override void VisitVariableDeclaration(VariableDeclarationSyntax node)
{
var type = node.Type.ToString() != "var" ? GetMappedType(node.Type) : String.Empty;
if (node.Variables.SeparatorCount == 0)
{
foreach (var identifier in node.Variables)
{
var initializer = identifier.Initializer != null ? (" " + identifier.Initializer) : String.Empty;
var typeDeclaration = !string.IsNullOrEmpty(type) ? ": " + type : String.Empty;
Emit(string.Format("var {0}{1}{2};", identifier.Identifier.Value, typeDeclaration, initializer));
}
}
else
{
var prefix = "var ";
var identifier = node.Variables.Last();
var initializer = identifier.Initializer != null ? (" " + identifier.Initializer) : String.Empty;
var typeDeclaration = !string.IsNullOrEmpty(type) ? ": " + type : String.Empty;
string padding = new string(' ', prefix.Length);
var separator = String.Concat(",", Environment.NewLine, GetIndentation(), padding);
var lines = prefix + String.Join(separator, node.Variables.Select(v => v.Identifier.Value).ToList());
Emit(string.Format("{0}{1}{2};", lines, typeDeclaration, initializer));
}
}
public override void VisitIfStatement(IfStatementSyntax node)
{
Emit("if ({0})", node.Condition.ToString());
using (IndentedBracketScope(node.Statement))
Visit(node.Statement);
if (node.Else != null)
{
Emit("else");
using (IndentedBracketScope(node.Else.Statement))
Visit(node.Else.Statement);
}
}
public override void VisitWhileStatement(WhileStatementSyntax node)
{
Emit("while ({0})", node.Condition.ToString());
using (IndentedBracketScope(node.Statement))
Visit(node.Statement);
}
internal class BlockScope : IDisposable
{
private readonly Transpiler _visitor;
private readonly bool _requiresBraces;
internal BlockScope(Transpiler visitor) : this(visitor, true)
{
}
internal BlockScope(Transpiler visitor, bool requiresBraces)
{
_requiresBraces = requiresBraces;
_visitor = visitor;
if (_requiresBraces)
_visitor.Emit("{");
_visitor.AddIndent();
}
public void Dispose()
{
_visitor.RemoveIndent();
if (_requiresBraces)
_visitor.Emit("}");
}
}
}
}