forked from neo-project/neo-devpack-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystemCall.Enum.cs
More file actions
1064 lines (920 loc) · 49.4 KB
/
Copy pathSystemCall.Enum.cs
File metadata and controls
1064 lines (920 loc) · 49.4 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 (C) 2015-2026 The Neo Project.
//
// SystemCall.Enum.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Neo.SmartContract.Native;
using Neo.VM;
namespace Neo.Compiler;
internal partial class MethodConvert
{
/// <summary>
/// Gets the module symbol for error reporting purposes.
/// </summary>
/// <param name="symbol">The symbol to get the module for</param>
/// <param name="symbolInfo">Symbol information for error messages</param>
/// <returns>The module symbol</returns>
/// <exception cref="CompilationException">Thrown when module metadata is not available</exception>
private static IModuleSymbol GetSymbolMetadataModule(ISymbol symbol, string symbolInfo)
{
var metadata = symbol.Locations.FirstOrDefault()?.MetadataModule;
if (metadata is null)
throw new CompilationException(symbol, DiagnosticId.InvalidArgument, $"Unexpected symbol location metadata module for {symbolInfo}");
return metadata;
}
private static IFieldSymbol[] GetEnumFields(INamedTypeSymbol enumTypeSymbol)
{
return enumTypeSymbol.GetMembers()
.OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false })
.ToArray();
}
/// <summary>
/// Handles the Enum.Parse method by parsing a string representation into an enum value.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Iterates through enum members, compares string names, returns matching value or throws
/// </remarks>
private static void HandleEnumParse(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 0 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.Parse"), DiagnosticId.InvalidArgument, "Enum.Parse requires at least two arguments");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments![0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
var endTarget = new JumpTarget();
foreach (var t in enumMembers)
{
methodConvert.EmitIf(
conditionEmitter: () =>
{
methodConvert.Dup(); // Stack: [type, inputString,inputString]
methodConvert.Push(t.Name); // Stack: [type, inputString,inputString, enumName]
methodConvert.Equal(); // Stack: [type,inputString, isEqual]
},
thenEmitter: () =>
{
methodConvert.Drop(2); // Stack: [type, inputString]
methodConvert.Push(t.ConstantValue); // Stack: [enumValue]
methodConvert.JumpAlwaysLong(endTarget);
});
}
// No match found
// Remove the inputString from the stack
methodConvert.Drop();
methodConvert.Push("No such enum value");
methodConvert.Throw();
endTarget.Instruction = methodConvert.Nop();
}
/// <summary>
/// Handles the Enum.Parse method with case-insensitive parsing support.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Similar to Parse but with optional case-insensitive string comparison using uppercase conversion
/// </remarks>
private static void HandleEnumParseIgnoreCase(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
using var tempScope = methodConvert.PreserveAnonymousVariables();
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 0 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.Parse"), DiagnosticId.InvalidArgument, "Enum.Parse requires at least two arguments");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments![0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
var ignoreCase = new JumpTarget();
byte ignoreCaseSlot = methodConvert.AddAnonymousVariable();
methodConvert.AccessSlot(OpCode.STLOC, ignoreCaseSlot);
methodConvert.AccessSlot(OpCode.LDLOC, ignoreCaseSlot);
methodConvert.JumpIfNot(ignoreCase);
ConvertToUpper(methodConvert); // Convert inputString to upper case
ignoreCase.Instruction = methodConvert.Nop();
var endTarget = new JumpTarget();
foreach (var t in enumMembers)
{
// Duplicate inputString
methodConvert.Dup(); // Stack: [..., inputString, inputString]
methodConvert.AccessSlot(OpCode.LDLOC, ignoreCaseSlot);
JumpTarget lowerCaseName = new();
methodConvert.JumpIfNot(lowerCaseName);
JumpTarget endCase = new JumpTarget();
// Push enum name
methodConvert.Push(t.Name.ToUpper()); // Stack: [..., inputString, inputString, enumName]
methodConvert.Jump(endCase);
lowerCaseName.Instruction = methodConvert.Nop();
methodConvert.Push(t.Name);
endCase.Instruction = methodConvert.Nop();
// Equal comparison
methodConvert.Equal(); // Stack: [..., inputString, isEqual]
var nextCheck = new JumpTarget();
// If not equal, discard duplicated inputString and proceed to next
methodConvert.JumpIfFalse(nextCheck);
// If equal:
// Remove the duplicated inputString from the stack
methodConvert.Drop(2);
// Push enum value
methodConvert.Push(t.ConstantValue);
methodConvert.JumpAlwaysLong(endTarget);
nextCheck.Instruction = methodConvert.Nop();
}
// No match found
// Remove the inputString from the stack
methodConvert.Drop(2);
methodConvert.Push("No such enum value");
methodConvert.Throw();
endTarget.Instruction = methodConvert.Nop();
}
/// <summary>
/// Handles the Enum.TryParse method with case-insensitive parsing and out parameter support.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Attempts to parse enum with case-insensitive option, stores result in out parameter
/// </remarks>
private static void HandleEnumTryParseIgnoreCase(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
using var tempScope = methodConvert.PreserveAnonymousVariables();
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 2 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.TryParse"), DiagnosticId.InvalidArgument, "Enum.TryParse requires at least three arguments");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments![0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
if (!methodConvert._context.TryGetCapturedStaticField(symbol.Parameters[3], out var index))
throw new CompilationException(symbol, DiagnosticId.SyntaxNotSupported, "Out parameter must be captured in a static field.");
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
byte ignoreCaseSlot = methodConvert.AddAnonymousVariable();
var endTarget = new JumpTarget();
var ignoreCase = new JumpTarget(); // Stack: [..., EnumType, string, ignoreCase, out parameter]
methodConvert.Drop(); // Stack: [..., EnumType, string, ignoreCase]
methodConvert.Dup(); // Stack: [..., EnumType, string, ignoreCase, ignoreCase]
methodConvert.AccessSlot(OpCode.STLOC, ignoreCaseSlot); // Stack: [..., EnumType, string, ignoreCase]
methodConvert.JumpIfNot(ignoreCase); // Stack: [..., EnumType, string]
ConvertToUpper(methodConvert, preserveInput: false); // Stack: [..., EnumType, string-upper]
ignoreCase.Instruction = methodConvert.Nip(); // Stack: [..., string or string-upper]
foreach (var t in enumMembers)
{
methodConvert.Dup(); // Stack: [..., string, string]
JumpTarget lowerCaseName = new();
JumpTarget endCase = new();
methodConvert.AccessSlot(OpCode.LDLOC, ignoreCaseSlot); // Stack: [..., string, string, ignoreCase]
methodConvert.JumpIfNot(lowerCaseName); // Stack: [..., string, string]
methodConvert.Push(t.Name.ToUpper()); // Stack: [..., string, string, enumNameUpper]
methodConvert.Jump(endCase);
lowerCaseName.Instruction = methodConvert.Nop();
methodConvert.Push(t.Name); // Stack: [..., string, string, enumName]
endCase.Instruction = methodConvert.Nop();
methodConvert.Equal(); // Stack: [..., string, isEqual]
var nextCheck = new JumpTarget();
methodConvert.JumpIfFalse(nextCheck); // Stack: [..., string], If not equal, discard duplicated string and proceed to next
methodConvert.Drop(); // Stack: [...]
methodConvert.Push(t.ConstantValue); // Stack: [..., enumValue]
methodConvert.AccessSlot(OpCode.STSFLD, index); // Stack: [...]
methodConvert.Push(true); // Stack: [..., true]
methodConvert.JumpAlways(endTarget);
nextCheck.Instruction = methodConvert.Nop();
}
methodConvert.Drop(); // Remove the string from the stack
methodConvert.Push(0); // Push default value (0) for the out parameter
methodConvert.AccessSlot(OpCode.STSFLD, index); // Store the default value (0) in the out parameter
methodConvert.Push(false); // Push false to indicate failure
endTarget.Instruction = methodConvert.Nop();
}
/// <summary>
/// Handles the Enum.IsDefined method by checking if a string name exists in the enum.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Iterates through enum members, compares names, returns true if found
/// </remarks>
private static void HandleEnumIsDefinedByName(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 0 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.IsDefined"), DiagnosticId.InvalidArgument, "Enum.IsDefined requires at least two arguments");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments![0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
var endTarget = new JumpTarget();
foreach (var t in enumMembers)
{
methodConvert.Dup(); // Duplicate input name
methodConvert.Push(t.Name); // Push enum name
methodConvert.Equal(); // Compare strings
var nextCheck = new JumpTarget();
methodConvert.JumpIfNot(nextCheck); // If not equal, check next
methodConvert.Drop(); // Remove the duplicated input name
methodConvert.Push(true); // Push true (enum name is defined)
methodConvert.JumpAlways(endTarget);
nextCheck.Instruction = methodConvert.Nop();
}
// No match found
methodConvert.Drop(); // Remove the input name
methodConvert.Push(false); // Push false (enum name is not defined)
endTarget.Instruction = methodConvert.Nop();
}
/// <summary>
/// Handles the Enum.GetName method by returning the name for a given enum value.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Iterates through enum members, compares values, returns matching name or null
/// </remarks>
private static void HandleEnumGetName(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the Enum value
var enumType = symbol.Parameters[0].Type;
if (enumType is not INamedTypeSymbol enumTypeSymbol)
{
throw new CompilationException(symbol.Locations.FirstOrDefault()!.MetadataModule!, DiagnosticId.InvalidType, "Unable to determine enum type");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
var endTarget = new JumpTarget();
foreach (var t in enumMembers)
{
methodConvert.Dup(); // Duplicate input value
methodConvert.Push(t.ConstantValue); // Push enum value, the enum value is an int value
var nextCheck = new JumpTarget();
methodConvert.Jump(OpCode.JMPNE, nextCheck); // If not numeric equal, check next
methodConvert.Drop(); // Remove the duplicated input value
methodConvert.Push(t.Name); // Push enum name
methodConvert.JumpAlways(endTarget);
nextCheck.Instruction = methodConvert.Nop();
}
// No match found
methodConvert.Drop(); // Remove the input value
methodConvert.PushNull(); // Push null (no matching enum name)
endTarget.Instruction = methodConvert.Nop();
}
/// <summary>
/// Handles the Enum.GetName method with explicit type parameter.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Similar to GetName but uses explicit type from typeof argument
/// </remarks>
private static void HandleEnumGetNameWithType(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is not null && arguments.Count > 0)
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.GetName"), DiagnosticId.InvalidArgument, "Enum.GetName requires at least two arguments");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
var endTarget = new JumpTarget();
var valueItem = methodConvert.PopInstruction(); // The second argument is the value to get the name of
var enumTypeItem = methodConvert.PopInstruction(); // The first argument is the enum type, It's unused when running
methodConvert.AddInstruction(valueItem);
foreach (var t in enumMembers)
{
methodConvert.Dup(); // Duplicate input value
methodConvert.Push(t.ConstantValue); // Push enum value, the enum value is an int value
var nextCheck = new JumpTarget();
methodConvert.Jump(OpCode.JMPNE, nextCheck); // If not numeric equal, check next
methodConvert.Drop(); // Remove the duplicated input value
methodConvert.Push(t.Name); // Push enum name
methodConvert.JumpAlways(endTarget);
nextCheck.Instruction = methodConvert.Nop();
}
// No match found
methodConvert.Drop(); // Remove the input value
methodConvert.PushNull(); // Push null (no matching enum name)
endTarget.Instruction = methodConvert.Nop();
}
/// <summary>
/// Handles the Enum.TryParse method by attempting to parse a string into an enum value.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Attempts to parse enum name, stores result in out parameter, returns success flag
/// </remarks>
private static void HandleEnumTryParse(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
if (!methodConvert._context.TryGetCapturedStaticField(symbol.Parameters[2], out var index))
throw new CompilationException(symbol, DiagnosticId.SyntaxNotSupported, "Out parameter must be captured in a static field.");
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 0 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.TryParse"), DiagnosticId.InvalidArgument, "Enum.TryParse requires at least three arguments");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
JumpTarget endTarget = new();
methodConvert.Drop();
foreach (var t in enumMembers)
{
methodConvert.Dup(); // Stack: [..., inputString, inputString]
methodConvert.Push(t.Name); // Stack: [..., inputString, inputString, enumName]
// Equal comparison
methodConvert.Equal(); // Stack: [..., inputString, isEqual]
JumpTarget nextCheck = new();
methodConvert.JumpIfNot(nextCheck);
// If equal:
methodConvert.Drop(2); // Remove the EnumType and inputString
methodConvert.Push(t.ConstantValue); // Stack: [..., enumValue]
methodConvert.AccessSlot(OpCode.STSFLD, index); // Store enum value in out parameter
methodConvert.Push(true); // Stack: [..., true]
methodConvert.JumpAlways(endTarget);
nextCheck.Instruction = methodConvert.Nop();
}
// No match found
methodConvert.Drop(2); // Remove the EumType and inputString
methodConvert.Push(0); // Default enum value
methodConvert.AccessSlot(OpCode.STSFLD, index); // Store default value in out parameter
methodConvert.Push(false); // Success flag set to false
endTarget.Instruction = methodConvert.Nop();
}
/// <summary>
/// Handles the Enum.GetNames method by returning all enum member names as an array.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Pushes all enum names onto stack then packs them into an array
/// </remarks>
private static void HandleEnumGetNames(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 0 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.GetNames"), DiagnosticId.InvalidArgument, "Enum.GetNames requires one argument");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments![0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
// Create an array of names
foreach (IFieldSymbol m in enumMembers.Reverse()) // PACK works in a reversed way
methodConvert.Push(m.Name);
methodConvert.Pack(enumMembers.Length);
}
/// <summary>
/// Handles the Enum.GetValues method by returning all enum member values as an array.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Pushes all enum constant values onto stack then packs them into an array
/// </remarks>
private static void HandleEnumGetValues(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 0 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.GetValues"), DiagnosticId.InvalidArgument, "Enum.GetValues requires one argument");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments![0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
// Create an array of values
foreach (IFieldSymbol m in enumMembers.Reverse()) // PACK works in a reversed way
methodConvert.Push(m.ConstantValue);
methodConvert.Pack(enumMembers.Length);
}
/// <summary>
/// Handles the Enum.IsDefined method by checking if a value or name exists in the enum.
/// </summary>
/// <param name="methodConvert">The method converter instance</param>
/// <param name="model">The semantic model</param>
/// <param name="symbol">The method symbol</param>
/// <param name="instanceExpression">The instance expression (if any)</param>
/// <param name="arguments">The method arguments</param>
/// <remarks>
/// Algorithm: Determines if checking by name or value, iterates through enum members for matches
/// </remarks>
private static void HandleEnumIsDefined(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is not null)
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Get the enum type from the first argument (typeof(enum))
ITypeSymbol? enumTypeSymbol = null;
if (arguments is { Count: > 0 })
{
if ((arguments[0] as ArgumentSyntax)?.Expression is TypeOfExpressionSyntax typeOfExpression)
{
var typeInfo = model.GetTypeInfo(typeOfExpression.Type);
enumTypeSymbol = typeInfo.Type;
}
else
{
throw new CompilationException(arguments[0], DiagnosticId.InvalidArgument, "First argument must be a typeof(enum)");
}
}
else
{
throw new CompilationException(GetSymbolMetadataModule(symbol, "Enum.IsDefined"), DiagnosticId.InvalidArgument, "Enum.IsDefined requires at least two arguments");
}
if (enumTypeSymbol is not { TypeKind: TypeKind.Enum })
{
throw new CompilationException(arguments![0], DiagnosticId.InvalidType, "Unable to determine enum type from first argument");
}
var enumMembers = enumTypeSymbol.GetMembers().OfType<IFieldSymbol>()
.Where(field => field is { HasConstantValue: true, IsImplicitlyDeclared: false }).ToArray();
if (arguments[1] is not ArgumentSyntax argument) // unexpected case
throw new CompilationException(arguments[1], DiagnosticId.InvalidArgument, "Invalid second argument");
var valueType = model.GetTypeInfo(argument.Expression).Type;
// We need to compare the input value against the enum values
var endTarget = new JumpTarget();
// here add check logic to verify if valueType is string
var isName = valueType is INamedTypeSymbol { Name: "String" };
foreach (var t in enumMembers)
{
methodConvert.Dup(); // Duplicate value to compare
if (isName)
{
methodConvert.Push(t.Name);
}
else
{
methodConvert.Push(t.ConstantValue);
}
// Equal comparison
methodConvert.Equal(); // Stack: [..., isEqual]
var nextCheck = new JumpTarget();
methodConvert.JumpIfNot(nextCheck);
// If equal, set result to true
methodConvert.Drop(2); // Remove the EnumType and duplicated value
methodConvert.Push(true); // Set result to true
methodConvert.JumpAlways(endTarget);
nextCheck.Instruction = methodConvert.Nop();
}
methodConvert.Drop(2); // Remove the EnumType and duplicated value
methodConvert.Push(false);
endTarget.Instruction = methodConvert.Nop();
}
private static INamedTypeSymbol EnsureEnumTypeArgument(IMethodSymbol symbol, int index, SyntaxNode? errorNode)
{
if (symbol.TypeArguments.Length <= index) throw new CompilationException(symbol, DiagnosticId.InvalidType, "Generic enum operation requires an enum type argument.");
if (symbol.TypeArguments[index] is not INamedTypeSymbol enumType)
throw new CompilationException(symbol, DiagnosticId.InvalidType, "Generic enum operation requires an enum type argument.");
if (enumType.TypeKind != TypeKind.Enum)
{
if (errorNode is not null)
throw new CompilationException(errorNode, DiagnosticId.InvalidType, "Type argument must be an enum.");
throw new CompilationException(symbol, DiagnosticId.InvalidType, "Type argument must be an enum.");
}
return enumType;
}
private static void HandleEnumToString(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
if (instanceExpression is null)
throw new CompilationException(symbol, DiagnosticId.InvalidArgument, "Enum.ToString requires an instance.");
methodConvert.ConvertExpression(model, instanceExpression);
var enumType = model.GetTypeInfo(instanceExpression).Type as INamedTypeSymbol
?? throw new CompilationException(symbol, DiagnosticId.InvalidType, "Unable to determine enum type for ToString.");
if (enumType.TypeKind != TypeKind.Enum)
throw new CompilationException(symbol, DiagnosticId.InvalidType, "Enum.ToString is only supported on enum values.");
var enumMembers = GetEnumFields(enumType);
var endTarget = new JumpTarget();
foreach (var member in enumMembers)
{
methodConvert.Dup();
methodConvert.Push(member.ConstantValue);
methodConvert.Equal();
var next = new JumpTarget();
methodConvert.JumpIfFalse(next);
methodConvert.Drop();
methodConvert.Push(member.Name);
methodConvert.JumpAlways(endTarget);
next.Instruction = methodConvert.Nop();
}
// Fallback to numeric representation
methodConvert.CallContractMethod(NativeContract.StdLib.Hash, "itoa", 1, true);
endTarget.Instruction = methodConvert.Nop();
}
private static void HandleEnumHasFlag(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
using var tempScope = methodConvert.PreserveAnonymousVariables();
if (instanceExpression is null)
throw new CompilationException(symbol, DiagnosticId.InvalidArgument, "Enum.HasFlag requires an instance.");
methodConvert.ConvertExpression(model, instanceExpression);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
// Stack: [value, flag]
byte flagSlot = methodConvert.AddAnonymousVariable();
methodConvert.AccessSlot(OpCode.STLOC, flagSlot); // store flag, keep value on stack
methodConvert.AccessSlot(OpCode.LDLOC, flagSlot);
methodConvert.And();
methodConvert.AccessSlot(OpCode.LDLOC, flagSlot);
methodConvert.Equal();
}
private static void HandleEnumParseGeneric(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
using var tempScope = methodConvert.PreserveAnonymousVariables();
var enumType = EnsureEnumTypeArgument(symbol, 0, instanceExpression);
var members = GetEnumFields(enumType);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
byte resultSlot = methodConvert.AddAnonymousVariable();
JumpTarget success = new();
foreach (var member in members)
{
methodConvert.Dup();
methodConvert.Push(member.Name);
methodConvert.Equal();
JumpTarget next = new();
methodConvert.JumpIfFalse(next);
methodConvert.Drop();
methodConvert.Push(member.ConstantValue);
methodConvert.AccessSlot(OpCode.STLOC, resultSlot);
methodConvert.JumpAlwaysLong(success);
next.Instruction = methodConvert.Nop();
}
methodConvert.Drop();
methodConvert.Push("No such enum value");
methodConvert.Throw();
success.Instruction = methodConvert.Nop();
methodConvert.AccessSlot(OpCode.LDLOC, resultSlot);
}
private static void HandleEnumParseGenericIgnoreCase(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
using var tempScope = methodConvert.PreserveAnonymousVariables();
var enumType = EnsureEnumTypeArgument(symbol, 0, instanceExpression);
var members = GetEnumFields(enumType);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
byte resultSlot = methodConvert.AddAnonymousVariable();
JumpTarget success = new();
byte ignoreSlot = methodConvert.AddAnonymousVariable();
methodConvert.AccessSlot(OpCode.STLOC, ignoreSlot); // store bool, keep input string
JumpTarget skipUpper = new();
methodConvert.AccessSlot(OpCode.LDLOC, ignoreSlot);
methodConvert.JumpIfFalse(skipUpper);
ConvertToUpper(methodConvert);
skipUpper.Instruction = methodConvert.Nop();
foreach (var member in members)
{
methodConvert.Dup();
JumpTarget lowerCaseName = new();
JumpTarget endChoose = new();
methodConvert.AccessSlot(OpCode.LDLOC, ignoreSlot);
methodConvert.JumpIfFalse(lowerCaseName);
methodConvert.Push(member.Name.ToUpper());
methodConvert.Jump(endChoose);
lowerCaseName.Instruction = methodConvert.Nop();
methodConvert.Push(member.Name);
endChoose.Instruction = methodConvert.Nop();
methodConvert.Equal();
var next = new JumpTarget();
methodConvert.JumpIfFalse(next);
methodConvert.Drop();
methodConvert.Push(member.ConstantValue);
methodConvert.AccessSlot(OpCode.STLOC, resultSlot);
methodConvert.JumpAlwaysLong(success);
next.Instruction = methodConvert.Nop();
}
methodConvert.Drop();
methodConvert.Push("No such enum value");
methodConvert.Throw();
success.Instruction = methodConvert.Nop();
methodConvert.AccessSlot(OpCode.LDLOC, resultSlot);
}
private static void HandleEnumTryParseGeneric(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
using var tempScope = methodConvert.PreserveAnonymousVariables();
var enumType = EnsureEnumTypeArgument(symbol, 0, instanceExpression);
var members = GetEnumFields(enumType);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
if (!methodConvert._context.TryGetCapturedStaticField(symbol.Parameters[1], out var index))
throw new CompilationException(symbol, DiagnosticId.SyntaxNotSupported, "Out parameter must be captured in a static field.");
methodConvert.Drop(); // drop out-parameter placeholder
byte resultSlot = methodConvert.AddAnonymousVariable();
byte successSlot = methodConvert.AddAnonymousVariable();
var successTarget = new JumpTarget();
methodConvert.Push(0);
methodConvert.AccessSlot(OpCode.STLOC, resultSlot);
methodConvert.Push(false);
methodConvert.AccessSlot(OpCode.STLOC, successSlot);
foreach (var member in members)
{
methodConvert.Dup();
methodConvert.Push(member.Name);
methodConvert.Equal();
var next = new JumpTarget();
methodConvert.JumpIfFalse(next);
methodConvert.Drop();
methodConvert.Push(member.ConstantValue);
methodConvert.AccessSlot(OpCode.STLOC, resultSlot);
methodConvert.Push(true);
methodConvert.AccessSlot(OpCode.STLOC, successSlot);
methodConvert.JumpAlways(successTarget);
next.Instruction = methodConvert.Nop();
}
methodConvert.Drop();
successTarget.Instruction = methodConvert.Nop();
methodConvert.AccessSlot(OpCode.LDLOC, resultSlot);
methodConvert.AccessSlot(OpCode.STSFLD, index);
methodConvert.AccessSlot(OpCode.LDLOC, successSlot);
}
private static void HandleEnumTryParseGenericIgnoreCase(MethodConvert methodConvert, SemanticModel model, IMethodSymbol symbol,
ExpressionSyntax? instanceExpression, IReadOnlyList<SyntaxNode>? arguments)
{
using var tempScope = methodConvert.PreserveAnonymousVariables();
var enumType = EnsureEnumTypeArgument(symbol, 0, instanceExpression);
var members = GetEnumFields(enumType);
if (arguments is not null)
methodConvert.PrepareArgumentsForMethod(model, symbol, arguments, CallingConvention.StdCall);
if (!methodConvert._context.TryGetCapturedStaticField(symbol.Parameters[2], out var index))
throw new CompilationException(symbol, DiagnosticId.SyntaxNotSupported, "Out parameter must be captured in a static field.");
methodConvert.Drop(); // drop out-parameter placeholder
byte resultSlot = methodConvert.AddAnonymousVariable();
byte successSlot = methodConvert.AddAnonymousVariable();
byte ignoreSlot = methodConvert.AddAnonymousVariable();
methodConvert.AccessSlot(OpCode.STLOC, ignoreSlot); // store bool, keep input string
methodConvert.Push(0);
methodConvert.AccessSlot(OpCode.STLOC, resultSlot);
methodConvert.Push(false);
methodConvert.AccessSlot(OpCode.STLOC, successSlot);
var skipUpper = new JumpTarget();