This repository has been archived by the owner on Aug 24, 2022. It is now read-only.
/
JavascriptAstEmitter.cs
1374 lines (1087 loc) · 43.7 KB
/
JavascriptAstEmitter.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ICSharpCode.Decompiler.ILAst;
using JSIL.Ast;
using JSIL.Internal;
using JSIL.Transforms;
using Mono.Cecil;
namespace JSIL {
public enum BlockType {
Switch,
While,
ForHeader,
ForBody,
Do
}
public class JavascriptAstEmitter : JSAstVisitor {
public readonly ITypeInfoSource TypeInfo;
public readonly JavascriptFormatter Output;
public readonly TypeSystem TypeSystem;
public readonly JSILIdentifier JSIL;
public readonly TypeReferenceContext ReferenceContext = new TypeReferenceContext();
protected readonly Stack<JSExpression> ThisReplacementStack = new Stack<JSExpression>();
protected readonly Stack<bool> IncludeTypeParens = new Stack<bool>();
protected readonly Stack<Func<string, bool>> GotoStack = new Stack<Func<string, bool>>();
protected readonly Stack<BlockType> BlockStack = new Stack<BlockType>();
public JavascriptAstEmitter (JavascriptFormatter output, JSILIdentifier jsil, TypeSystem typeSystem, ITypeInfoSource typeInfo) {
Output = output;
JSIL = jsil;
TypeSystem = typeSystem;
TypeInfo = typeInfo;
IncludeTypeParens.Push(false);
}
protected void CommaSeparatedList (IEnumerable<JSExpression> values, bool withNewlines = false) {
bool isFirst = true;
foreach (var value in values) {
if (!isFirst) {
Output.Comma();
if (withNewlines)
Output.NewLine();
}
Visit(value);
isFirst = false;
}
}
public override void VisitNode (JSNode node) {
if ((node != null) && !node.IsNull) {
Console.Error.WriteLine("Cannot emit {0}", node.GetType().Name);
Output.Identifier("JSIL.UntranslatableNode", null);
Output.LPar();
Output.Value(node.GetType().Name);
Output.RPar();
Output.Semicolon();
}
base.VisitNode(node);
}
public void VisitNode (JSBlockStatement block) {
VisitNode(block, false);
}
public void VisitNode (JSBlockStatement block, bool includeBraces) {
if (includeBraces)
Output.OpenBrace();
for (var i = 0; i < block.Statements.Count; i++)
Visit(block.Statements[i]);
if (includeBraces)
Output.CloseBrace();
}
public void VisitNode (JSLabelGroupStatement labelGroup) {
Output.NewLine();
var stepLabel = String.Format("$labelgroup{0}", labelGroup.GroupIndex);
var labelVar = String.Format("$label{0}", labelGroup.GroupIndex);
var firstLabel = labelGroup.Labels.First().Key;
Output.WriteRaw("var");
Output.Space();
Output.Identifier(labelVar);
Output.WriteRaw(" = ");
Output.Value(firstLabel);
Output.Semicolon();
Output.Label(stepLabel);
Output.WriteRaw("while");
Output.Space();
Output.LPar();
Output.WriteRaw("true");
Output.RPar();
Output.Space();
Output.OpenBrace();
Output.WriteRaw("switch");
Output.Space();
Output.LPar();
Output.Identifier(labelVar);
Output.RPar();
Output.Space();
Output.OpenBrace();
bool isFirst = true;
Func<string, bool> emitGoto = (labelName) => {
if (labelName != null) {
if (!labelGroup.Labels.ContainsKey(labelName))
return false;
Output.Identifier(labelVar);
Output.WriteRaw(" = ");
Output.Value(labelName);
Output.Semicolon();
}
Output.WriteRaw("continue");
Output.Space();
Output.Identifier(stepLabel);
return true;
};
GotoStack.Push(emitGoto);
bool needsTrailingBreak = true;
foreach (var kvp in labelGroup.Labels) {
if (!isFirst && needsTrailingBreak) {
Output.Indent();
emitGoto(kvp.Key);
Output.Semicolon(true);
Output.Unindent();
}
Output.WriteRaw("case");
Output.Space();
Output.Value(kvp.Key);
Output.WriteRaw(":");
Output.Indent();
Output.NewLine();
Visit(kvp.Value);
Func<JSNode, bool> isNotNull = (n) => {
if (n.IsNull)
return false;
if (n is JSNullStatement)
return false;
if (n is JSNullExpression)
return false;
var es = n as JSExpressionStatement;
if (es != null) {
if (es.Expression.IsNull)
return false;
if (es.Expression is JSNullExpression)
return false;
}
return true;
};
var nonNullChildren = kvp.Value.Children.Where(isNotNull);
var lastStatement = nonNullChildren.LastOrDefault();
JSBlockStatement lastBlockStatement;
while ((lastBlockStatement = lastStatement as JSBlockStatement) != null) {
if (lastBlockStatement.IsControlFlow)
break;
else {
nonNullChildren = lastStatement.Children.Where(isNotNull);
lastStatement = nonNullChildren.LastOrDefault();
}
}
var lastExpressionStatement = lastStatement as JSExpressionStatement;
if (
(lastExpressionStatement != null) &&
(
(lastExpressionStatement.Expression is JSContinueExpression) ||
(lastExpressionStatement.Expression is JSBreakExpression) ||
(lastExpressionStatement.Expression is JSGotoExpression)
)
) {
needsTrailingBreak = false;
} else {
needsTrailingBreak = true;
}
isFirst = false;
Output.Unindent();
Output.NewLine();
}
GotoStack.Pop();
if (needsTrailingBreak) {
Output.Indent();
Output.WriteRaw("break");
Output.Space();
Output.Identifier(stepLabel);
Output.Semicolon(true);
Output.Unindent();
}
Output.CloseBrace();
Output.CloseBrace();
}
public void VisitNode (JSVariableDeclarationStatement vars) {
if (vars.Declarations.Count == 0)
return;
Output.WriteRaw("var");
Output.Space();
CommaSeparatedList(vars.Declarations);
if ((BlockStack.Count == 0) ||
(BlockStack.Peek() != BlockType.ForHeader)
) {
Output.Semicolon();
}
}
public void VisitNode (JSExpressionStatement statement) {
bool isNull = (statement.IsNull ||
statement.Expression.IsNull) &&
!(statement.Expression is JSUntranslatableExpression) &&
!(statement.Expression is JSIgnoredMemberReference);
Visit(statement.Expression);
if (!isNull &&
((BlockStack.Count == 0) ||
(BlockStack.Peek() != BlockType.ForHeader))
) {
Output.Semicolon();
}
}
public void VisitNode (JSDotExpression dot) {
VisitDotExpression(dot);
}
protected void VisitDotExpression (JSDotExpressionBase dot) {
var parens = (dot.Target is JSNumberLiteral) ||
(dot.Target is JSIntegerLiteral);
if (parens)
Output.LPar();
Visit(dot.Target);
if (parens)
Output.RPar();
Output.Dot();
Visit(dot.Member);
}
public void VisitNode (JSFieldAccess fa) {
VisitDotExpression(fa);
}
public void VisitNode (JSPropertyAccess pa) {
VisitDotExpression(pa);
}
public void VisitNode (JSMethodAccess ma) {
var parens = (ma.Target is JSNumberLiteral) ||
(ma.Target is JSIntegerLiteral);
if (parens)
Output.LPar();
Visit(ma.Target);
if (parens)
Output.RPar();
if (!ma.IsStatic) {
Output.Dot();
Output.Identifier("prototype");
}
Output.Dot();
Visit(ma.Member);
}
public void VisitNode (JSChangeTypeExpression cte) {
Visit(cte.Expression);
}
public void VisitNode (JSStructCopyExpression sce) {
Visit(sce.Struct);
Output.Dot();
Output.Identifier("MemberwiseClone");
Output.LPar();
Output.RPar();
}
public void VisitNode (JSIndexerExpression idx) {
Visit(idx.Target);
Output.OpenBracket();
Visit(idx.Index);
Output.CloseBracket();
}
public void VisitNode (JSFakeMethod fakeMethod) {
Output.Identifier(fakeMethod.Name);
var ga = fakeMethod.GenericArguments;
if (ga != null) {
Output.LPar();
CommaSeparatedList(ga);
Output.RPar();
}
}
public void VisitNode (JSMethod method) {
Output.Identifier(method.GetNameForInstanceReference());
var ga = method.GenericArguments;
if (ga != null) {
Output.LPar();
Output.CommaSeparatedList(ga, ReferenceContext, ListValueType.Identifier);
Output.RPar();
}
}
public void VisitNode (JSIdentifier identifier) {
Output.Identifier(identifier.Identifier);
}
public void VisitNode (JSRawOutputIdentifier identifier) {
identifier.Emitter(Output);
}
public void VisitNode (JSCharLiteral ch) {
Output.Value(ch.Value);
}
public void VisitNode (JSStringLiteral str) {
Output.Value(str.Value);
}
public void VisitNode (JSVerbatimLiteral verbatim) {
bool parens =
(ParentNode is JSBinaryOperatorExpression) || (ParentNode is JSUnaryOperatorExpression);
var regex = new Regex(@"(\$(?'name'(typeof\(this\))|([a-zA-Z_]([a-zA-Z0-9_]*)))|(?'text'[^\$]*)|)", RegexOptions.ExplicitCapture);
if (parens)
Output.LPar();
bool isFirst = true;
foreach (var line in verbatim.Expression.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) {
if (String.IsNullOrWhiteSpace(line))
continue;
if (!isFirst)
Output.NewLine();
var matches = regex.Matches(line);
foreach (Match m in matches) {
if (m.Groups["text"].Success) {
Output.WriteRaw(m.Groups["text"].Value);
} else if (m.Groups["name"].Success) {
var key = m.Groups["name"].Value;
if (verbatim.Variables.ContainsKey(key))
Visit(verbatim.Variables[key]);
else
Output.WriteRaw("null");
}
}
isFirst = false;
}
if (parens)
Output.RPar();
}
public void VisitNode (JSTypeNameLiteral type) {
Output.Value(type.Value);
}
public void VisitNode (JSAssemblyNameLiteral asm) {
Output.Value(asm.Value.FullName);
}
public void VisitNode (JSIntegerLiteral integer) {
Output.Value(integer.Value);
}
public void VisitNode (JSNumberLiteral number) {
Output.Value(number.Value);
}
public void VisitNode (JSBooleanLiteral b) {
Output.Value(b.Value);
}
public void VisitNode (JSEnumLiteral enm) {
bool isFirst = true;
if (enm.Names.Length == 1) {
Output.Identifier(enm.EnumType, ReferenceContext);
Output.Dot();
Output.Identifier(enm.Names[0]);
} else {
Output.Identifier(enm.EnumType, ReferenceContext);
Output.Dot();
Output.Identifier("Flags");
Output.LPar();
Output.CommaSeparatedList(
enm.Names, ReferenceContext, ListValueType.Primitive
);
Output.RPar();
}
}
public void VisitNode (JSNullLiteral nil) {
Output.WriteRaw("null");
}
public void VisitNode (JSGotoExpression go) {
if (GotoStack.Count > 0) {
foreach (var eg in GotoStack) {
if (eg(go.TargetLabel))
return;
}
}
Output.Identifier("JSIL.UntranslatableInstruction", null);
Output.LPar();
Output.Value(go.ToString());
Output.RPar();
}
public void VisitNode (JSUntranslatableStatement us) {
Output.Identifier("JSIL.UntranslatableNode", null);
Output.LPar();
Output.Value((us.Type ?? "").ToString());
Output.RPar();
Output.Semicolon();
}
public void VisitNode (JSUntranslatableExpression ue) {
Output.Identifier("JSIL.UntranslatableInstruction", null);
Output.LPar();
Output.Value((ue.Type ?? "").ToString());
Output.RPar();
}
public void VisitNode (JSIgnoredMemberReference imr) {
Output.Identifier("JSIL.IgnoredMember", null);
Output.LPar();
if (imr.Member != null) {
var method = imr.Member as MethodInfo;
if (method != null)
Output.Value(String.Format(
"{0}({1})", method.Name, String.Join(", ",
(from p in method.Member.Parameters select p.Name).ToArray()
)
));
else
Output.Value(imr.Member.Name);
}
var args = (from a in imr.Arguments where (a != null) && !a.IsNull select a).ToArray();
if (args.Length != 0) {
if (imr.Member != null)
Output.Comma();
CommaSeparatedList(args);
}
Output.RPar();
}
public void VisitNode (JSDefaultValueLiteral defaultValue) {
if (TypeUtil.IsEnum(defaultValue.Value)) {
var enumInfo = TypeInfo.Get(defaultValue.Value);
if (enumInfo.FirstEnumMember != null) {
Output.Identifier(defaultValue.Value, ReferenceContext);
Output.Dot();
Output.Identifier(enumInfo.FirstEnumMember.Name);
} else {
Output.WriteRaw("0");
}
} else if (TypeUtil.IsIntegralOrEnum(defaultValue.Value)) {
Output.Value(0);
} else if (!defaultValue.Value.IsValueType) {
Output.WriteRaw("null");
} else {
switch (defaultValue.Value.FullName) {
case "System.Nullable`1":
Output.WriteRaw("null");
break;
case "System.Single":
case "System.Double":
case "System.Decimal":
Output.Value(0.0);
break;
case "System.Char":
Output.Value("\0");
break;
case "System.Boolean":
Output.WriteRaw("false");
break;
default:
VisitNode(new JSNewExpression(new JSType(defaultValue.Value), null, null));
break;
}
}
}
public void VisitNode (JSAssembly asm) {
Output.AssemblyReference(asm.Assembly);
}
public void VisitNode (JSTypeReference tr) {
Output.TypeReference(tr.Type, new TypeReferenceContext {
EnclosingType = tr.Context,
EnclosingMethod = Output.CurrentMethod
});
}
public void VisitNode (JSType type) {
Output.Identifier(
type.Type, ReferenceContext, IncludeTypeParens.Peek()
);
}
public void VisitNode (JSTypeOfExpression toe) {
Output.Identifier(
toe.Type, ReferenceContext, IncludeTypeParens.Peek()
);
if (toe.Type is GenericParameter) {
// Generic parameters are type objects, not public interfaces
} else {
Output.Dot();
Output.Identifier("__Type__");
}
}
public void VisitNode (JSPublicInterfaceOfExpression poe) {
VisitChildren(poe);
Output.Dot();
Output.Identifier("__PublicInterface__");
}
public void VisitNode (JSEliminatedVariable variable) {
throw new InvalidOperationException(String.Format("'{0}' was eliminated despite being in use.", variable.Variable));
}
public void VisitNode (JSVariable variable) {
if (variable.IsThis) {
if (ThisReplacementStack.Count > 0) {
var thisRef = ThisReplacementStack.Peek();
if (thisRef != null)
Visit(thisRef);
return;
} else {
Output.WriteRaw("this");
}
} else
Output.Identifier(variable.Identifier);
// Don't emit .value when initializing a reference in a declaration.
var boe = ParentNode as JSBinaryOperatorExpression;
if (
(boe != null) &&
(boe.Left == variable) &&
(Stack.Skip(2).FirstOrDefault() is JSVariableDeclarationStatement)
) {
return;
}
if (variable.IsReference) {
if (variable.IsThis) {
if (JSExpression.DeReferenceType(variable.Type).IsValueType)
return;
else
throw new InvalidOperationException(String.Format(
"The this-reference '{0}' was a reference to a non-value type: {1}",
variable, variable.Type
));
}
Output.Dot();
Output.Identifier("value");
}
}
public void VisitNode (JSPassByReferenceExpression byref) {
JSExpression referent;
if (JSReferenceExpression.TryMaterialize(JSIL, byref.Referent, out referent)) {
Output.Comment("ref");
Visit(referent);
} else {
Output.Identifier("JSIL.UnmaterializedReference", null);
Output.LPar();
Output.RPar();
}
}
public void VisitNode (JSReferenceExpression reference) {
Visit(reference.Referent);
}
public void VisitNode (JSLambda lambda) {
if (!lambda.UseBind)
ThisReplacementStack.Push(lambda.This);
Visit(lambda.Value);
if (lambda.UseBind) {
Output.Dot();
Output.WriteRaw("bind");
Output.LPar();
Visit(lambda.This);
Output.RPar();
} else {
ThisReplacementStack.Pop();
}
}
public void VisitNode (JSFunctionExpression function) {
var oldCurrentMethod = Output.CurrentMethod;
if (function.Method != null) {
Output.CurrentMethod = function.Method.Reference;
} else {
Output.CurrentMethod = null;
}
Output.OpenFunction(
function.DisplayName,
(o) => o.WriteParameterList(function.Parameters)
);
Visit(function.Body);
Output.CloseBrace(false);
Output.CurrentMethod = oldCurrentMethod;
}
public void VisitNode (JSSwitchStatement swtch) {
BlockStack.Push(BlockType.Switch);
WriteLabel(swtch);
Output.WriteRaw("switch");
Output.Space();
Output.LPar();
Visit(swtch.Condition);
Output.RPar();
Output.Space();
Output.OpenBrace();
foreach (var c in swtch.Cases) {
if (c.Values != null) {
foreach (var value in c.Values) {
Output.WriteRaw("case ");
Visit(value);
Output.WriteRaw(": ");
Output.NewLine();
}
} else {
Output.WriteRaw("default: ");
Output.NewLine();
}
Output.Indent();
Visit(c.Body);
Output.Unindent();
Output.NewLine();
}
Output.CloseBrace();
BlockStack.Pop();
}
protected void WriteLoopLabel (JSLoopStatement loop) {
if (loop.Index.HasValue)
Output.Label(String.Format("$loop{0}", loop.Index.Value));
}
protected void WriteLabel (JSStatement stmt) {
if (!String.IsNullOrWhiteSpace(stmt.Label))
Output.Label(stmt.Label);
}
public void VisitNode (JSIfStatement ifs) {
Output.WriteRaw("if");
Output.Space();
Output.LPar();
Visit(ifs.Condition);
Output.RPar();
Output.Space();
Output.OpenBrace();
Visit(ifs.TrueClause);
JSStatement falseClause = ifs.FalseClause;
while (falseClause != null) {
var nestedBlock = falseClause as JSBlockStatement;
var nestedIf = falseClause as JSIfStatement;
if ((nestedBlock != null) && (nestedBlock.Statements.Count == 1))
nestedIf = nestedBlock.Statements[0] as JSIfStatement;
if (nestedIf != null) {
Output.CloseAndReopenBrace((o) => {
if (o != this.Output)
throw new InvalidOperationException("Output mismatch");
o.WriteRaw("else if");
o.Space();
o.LPar();
Visit(nestedIf.Condition);
o.RPar();
});
Visit(nestedIf.TrueClause);
falseClause = nestedIf.FalseClause;
} else {
Output.CloseAndReopenBrace("else");
Visit(falseClause);
falseClause = null;
}
}
Output.CloseBrace();
}
public void VisitNode (JSTryCatchBlock tcb) {
if ((tcb.Catch ?? tcb.Finally) == null) {
Visit(tcb.Body);
return;
}
Output.WriteRaw("try");
Output.Space();
Output.OpenBrace();
Visit(tcb.Body);
if (tcb.Catch != null) {
Output.CloseAndReopenBrace((o) => {
if (o != Output)
throw new InvalidOperationException("Output mismatch");
o.WriteRaw("catch");
o.Space();
o.LPar();
Visit(tcb.CatchVariable);
o.RPar();
});
Visit(tcb.Catch);
}
if (tcb.Finally != null) {
Output.CloseAndReopenBrace("finally");
Visit(tcb.Finally);
}
Output.CloseBrace();
}
public void VisitNode (JSForLoop loop) {
Output.NewLine();
BlockStack.Push(BlockType.ForHeader);
WriteLoopLabel(loop);
Output.WriteRaw("for");
Output.Space();
Output.LPar();
if ((loop.Initializer != null) && !loop.Initializer.IsNull)
Visit(loop.Initializer);
Output.Semicolon(false);
Visit(loop.Condition);
Output.Semicolon(false);
if ((loop.Increment != null) && !loop.Increment.IsNull)
Visit(loop.Increment);
Output.RPar();
Output.Space();
BlockStack.Pop();
BlockStack.Push(BlockType.ForBody);
VisitNode((JSBlockStatement)loop, true);
BlockStack.Pop();
}
public void VisitNode (JSWhileLoop loop) {
Output.NewLine();
BlockStack.Push(BlockType.While);
WriteLoopLabel(loop);
Output.WriteRaw("while");
Output.Space();
Output.LPar();
Visit(loop.Condition);
Output.RPar();
Output.Space();
VisitNode((JSBlockStatement)loop, true);
BlockStack.Pop();
}
public void VisitNode (JSDoLoop loop) {
Output.NewLine();
BlockStack.Push(BlockType.Do);
WriteLoopLabel(loop);
Output.WriteRaw("do");
Output.Space();
Output.OpenBrace();
VisitNode((JSBlockStatement)loop, false);
Output.CloseBrace(false);
Output.Space();
Output.WriteRaw("while");
Output.Space();
Output.LPar();
Visit(loop.Condition);
Output.RPar();
Output.Semicolon();
BlockStack.Pop();
}
public void VisitNode (JSReturnExpression ret) {
Output.WriteRaw("return");
if (ret.Value != null) {
Output.Space();
Visit(ret.Value);
}
}
public void VisitNode (JSThrowExpression ret) {
Output.WriteRaw("throw");
Output.Space();
Visit(ret.Exception);
}
public void VisitNode (JSBreakExpression brk) {
if (brk.TargetLoop.HasValue) {
Output.WriteRaw("break");
Output.Space();
Output.Identifier(String.Format("$loop{0}", brk.TargetLoop.Value));
return;
}
if (BlockStack.Count == 0) {
throw new NotImplementedException("Break expression found outside of block");
}
switch (BlockStack.Peek()) {
case BlockType.Switch:
Output.WriteRaw("break");
break;
default:
throw new NotImplementedException("Break statement found outside of switch statement or loop");
break;
}
}
public void VisitNode (JSContinueExpression cont) {
if (cont.TargetLoop.HasValue) {
Output.WriteRaw("continue");
Output.Space();
Output.Identifier(String.Format("$loop{0}", cont.TargetLoop.Value));
} else if (GotoStack.Count > 0) {
GotoStack.Peek()(null);
} else {
Output.WriteRaw("continue");
}
}
public void VisitNode (JSUnaryOperatorExpression uop) {
if (!uop.IsPostfix)
Output.WriteRaw(uop.Operator.Token);
Visit(uop.Expression);
if (uop.IsPostfix)
Output.WriteRaw(uop.Operator.Token);
}
public void VisitNode (JSBinaryOperatorExpression bop) {
bool parens = true;
bool needsTruncation = false, needsCast = false;
if (ParentNode is JSIfStatement)
parens = false;
else if ((ParentNode is JSWhileLoop) && ((JSWhileLoop)ParentNode).Condition == bop)
parens = false;
else if ((ParentNode is JSDoLoop) && ((JSDoLoop)ParentNode).Condition == bop)
parens = false;
else if (ParentNode is JSForLoop) {
var fl = (JSForLoop)ParentNode;
if (
(fl.Condition == bop) ||
(fl.Increment.SelfAndChildrenRecursive.Any((n) => bop.Equals(n))) ||
(fl.Initializer.SelfAndChildrenRecursive.Any((n) => bop.Equals(n)))
) {
parens = false;
}
} else if ((ParentNode is JSSwitchStatement) && ((JSSwitchStatement)ParentNode).Condition == bop)
parens = false;
else if (
(ParentNode is JSBinaryOperatorExpression) &&
((JSBinaryOperatorExpression)ParentNode).Operator == bop.Operator &&
bop.Operator is JSLogicalOperator
) {
parens = false;
} else if (ParentNode is JSVariableDeclarationStatement)
parens = false;
else if (ParentNode is JSExpressionStatement)
parens = false;
var leftType = bop.Left.GetActualType(TypeSystem);
var rightType = bop.Right.GetActualType(TypeSystem);
var resultType = bop.GetActualType(TypeSystem);
// We need to perform manual truncation to maintain the semantics of C#'s division operator
if ((bop.Operator == JSOperator.Divide)) {
needsTruncation =
(TypeUtil.IsIntegral(leftType) ||
TypeUtil.IsIntegral(rightType)) &&
TypeUtil.IsIntegral(resultType);
}
// Arithmetic on enum types needs a cast at the end.
if (bop.Operator is JSArithmeticOperator) {
if (TypeUtil.IsEnum(TypeUtil.StripNullable(resultType))) {
needsCast = true;
}
}
if (needsTruncation) {
if (bop.Operator is JSAssignmentOperator)
throw new NotImplementedException("Truncation of assignment operations not implemented");
Output.WriteRaw("Math.floor");
} else if (needsCast) {