forked from neo-project/neo-devpack-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompilationContext.cs
More file actions
825 lines (747 loc) · 38.7 KB
/
Copy pathCompilationContext.cs
File metadata and controls
825 lines (747 loc) · 38.7 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
// Copyright (C) 2015-2026 The Neo Project.
//
// CompilationContext.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.
extern alias scfx;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Neo.Compiler.ABI;
using Neo.Compiler.Optimizer;
using Neo.Cryptography.ECC;
using Neo.Extensions;
using Neo.Json;
using Neo.SmartContract;
using Neo.SmartContract.Manifest;
using scfx::Neo.SmartContract.Framework;
using scfx::Neo.SmartContract.Framework.Attributes;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Diagnostic = Microsoft.CodeAnalysis.Diagnostic;
using ECPoint = Neo.Cryptography.ECC.ECPoint;
namespace Neo.Compiler
{
public partial class CompilationContext
{
private readonly CompilationEngine _engine;
private readonly INamedTypeSymbol _targetContract;
private readonly INamedTypeSymbol? _frameworkSafeAttribute;
private readonly System.Collections.Generic.List<INamedTypeSymbol>? _nonDependencies;
internal CompilationOptions Options => _engine.Options;
private string? _displayName, _className;
private readonly System.Collections.Generic.List<Diagnostic> _diagnostics = new();
private readonly HashSet<string> _supportedStandards = new();
private readonly System.Collections.Generic.List<AbiMethod> _methodsExported = new();
private readonly System.Collections.Generic.List<AbiEvent> _eventsExported = new();
private readonly PermissionBuilder _permissions = new();
private readonly HashSet<string> _trusts = new();
private readonly JObject _manifestExtra = new();
// We can not reuse these converted methods as the offsets are determined while converting
private readonly MethodConvertCollection _methodsConverted = new();
private readonly MethodConvertCollection _methodsForward = new();
private readonly System.Collections.Generic.List<MethodToken> _methodTokens = new();
private readonly Dictionary<IFieldSymbol, byte> _staticFields = new(SymbolEqualityComparer.Default);
private readonly System.Collections.Generic.List<byte> _anonymousStaticFields = new();
private readonly Dictionary<ITypeSymbol, byte> _vtables = new(SymbolEqualityComparer.Default);
private readonly Dictionary<ISymbol, byte> _capturedStaticFields = new(SymbolEqualityComparer.Default);
private readonly ConcurrentDictionary<IMethodSymbol, bool> _needInstanceConstructorCache = new(SymbolEqualityComparer.Default);
internal readonly struct OutSyncTarget
{
public OutSyncTarget(ISymbol symbol, byte? instanceSlot = null)
{
Symbol = symbol;
InstanceSlot = instanceSlot;
}
public ISymbol Symbol { get; }
public byte? InstanceSlot { get; }
}
// This dictionary is used to sync value from key symbol to value symbol
// We need to sync the value symbol to the key symbol when the key symbol is updated
internal Dictionary<ISymbol, System.Collections.Generic.List<OutSyncTarget>> OutStaticFieldsSync { get; } = new Dictionary<ISymbol, System.Collections.Generic.List<OutSyncTarget>>(SymbolEqualityComparer.Default);
private byte[]? _script;
public bool Success => _diagnostics.All(p => p.Severity != DiagnosticSeverity.Error);
public IReadOnlyList<Diagnostic> Diagnostics => _diagnostics;
public string? ContractName => _displayName ?? (_allowBaseName ? Options.BaseName : null) ?? _className;
private string? Source { get; set; }
internal IEnumerable<IFieldSymbol> StaticFieldSymbols => _staticFields.OrderBy(p => p.Value).Select(p => p.Key);
internal IEnumerable<(byte, ITypeSymbol)> VTables => _vtables.OrderBy(p => p.Value).Select(p => (p.Value, p.Key));
internal int StaticFieldCount => _staticFields.Count + _anonymousStaticFields.Count + _vtables.Count;
private byte[] Script => _script ??= GetInstructions().Select(p => p.ToArray()).SelectMany(p => p).ToArray();
/// <summary>
/// Specify the contract to be compiled.
/// </summary>
/// <param name="engine"> CompilationEngine that contains the compilation syntax tree and compiled methods</param>
/// <param name="targetContract">Contract to be compiled</param>
/// <param name="nonDependencies">Classes that is not supposed to be compiled into current target contract.</param>
private readonly bool _allowBaseName;
internal INamedTypeSymbol TargetContract => _targetContract;
internal INamedTypeSymbol? FrameworkSafeAttribute => _frameworkSafeAttribute;
internal CompilationContext(CompilationEngine engine, INamedTypeSymbol targetContract, System.Collections.Generic.List<INamedTypeSymbol>? nonDependencies = null, bool allowBaseName = true)
{
_engine = engine;
_targetContract = targetContract;
_frameworkSafeAttribute = ResolveFrameworkSafeAttribute(engine);
_nonDependencies = nonDependencies;
_allowBaseName = allowBaseName;
}
private static INamedTypeSymbol? ResolveFrameworkSafeAttribute(CompilationEngine engine)
{
if (engine.Compilation is null || engine.FrameworkReference is null)
return null;
return (engine.Compilation.GetAssemblyOrModuleSymbol(engine.FrameworkReference) as IAssemblySymbol)?
.GetTypeByMetadataName(typeof(SafeAttribute).FullName!);
}
private void RemoveEmptyInitialize()
{
int index = _methodsExported.FindIndex(p => p.Name == "_initialize");
if (index < 0) return;
AbiMethod method = _methodsExported[index];
if (_methodsConverted[method.Symbol].Instructions.Count <= 1)
{
_methodsExported.RemoveAt(index);
_methodsConverted.Remove(method.Symbol);
}
}
private IEnumerable<Instruction> GetInstructions()
{
return _methodsConverted.SelectMany(p => p.Instructions).Concat(_methodsForward.SelectMany(p => p.Instructions));
}
private int GetAbiOffset(IMethodSymbol method)
{
if (!_methodsForward.TryGetValue(method, out MethodConvert? convert))
convert = _methodsConverted[method];
return convert.Instructions[0].Offset;
}
private static bool ValidateContractDescriptor(string value)
{
if (value == "*") return true;
if (UInt160.TryParse(value, out _)) return true;
try
{
return ECPoint.TryParse(value, ECCurve.Secp256r1, out _);
}
catch (Exception ex) when (ex is FormatException or ArgumentException or IndexOutOfRangeException)
{
}
return false;
}
private static void ValidateContractPermission(INamedTypeSymbol symbol, string contract, IReadOnlyCollection<string> methods)
{
if (!ValidateContractDescriptor(contract))
throw new CompilationException(symbol, DiagnosticId.InvalidArgument, $"The value {contract} is not a valid ContractPermission descriptor.");
foreach (string method in methods)
{
if (string.IsNullOrEmpty(method))
throw new CompilationException(symbol, DiagnosticId.InvalidArgument, "ContractPermission methods cannot contain empty strings.");
}
}
internal void Compile()
{
_diagnostics.AddRange(_engine.AnalyzerDiagnostics);
HashSet<INamedTypeSymbol> processed = new(SymbolEqualityComparer.Default);
foreach (SyntaxTree tree in _engine.Compilation!.SyntaxTrees)
{
SemanticModel model = _engine.Compilation!.GetSemanticModel(tree);
_diagnostics.AddRange(model.GetDiagnostics().Where(u => u.Severity != DiagnosticSeverity.Hidden));
if (!Success) continue;
try
{
ProcessCompilationUnit(processed, model, tree.GetCompilationUnitRoot());
}
catch (CompilationException ex)
{
_diagnostics.Add(ex.Diagnostic);
}
}
if (Success)
{
RemoveEmptyInitialize();
Instruction[] instructions = GetInstructions().ToArray();
instructions.RebuildOffsets();
// Jump encoding is a size/canonicalization pass. Even when full optimizations are
// disabled, we still prefer short-form jumps when the target is within range.
BasicOptimizer.CompressJumps(instructions);
instructions.RebuildOperands();
}
if (Success)
{
// A method advertised as [Safe] promises wallets and dApps it is read-only and can
// be invoked without a signature prompt. Verify that promise: fail the build when a
// Safe method mutates contract state, so the manifest cannot ship a false guarantee.
foreach (CompilationException violation in GetSafeMethodViolations())
_diagnostics.Add(violation.Diagnostic);
}
if (Success && _supportedStandards.Count > 0)
{
// A contract that advertises a NEP standard in its manifest must implement it
// correctly; otherwise the declaration is misleading to wallets and explorers.
// Surface any violation as a compilation error so the build fails.
foreach (CompilationException violation in CreateManifest().GetStandardsViolations())
_diagnostics.Add(violation.Diagnostic);
}
}
public (NefFile nef, ContractManifest manifest, JObject debugInfo) CreateResults(string folder = "")
{
NefFile nef = CreateExecutable();
ContractManifest manifest = CreateManifest();
JObject debugInfo = CreateDebugInformation(folder);
if (Options.Optimize.HasFlag(CompilationOptions.OptimizationType.Experimental))
{
try
{
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
(nef, manifest, debugInfo) = Neo.Optimizer.Optimizer.Optimize(nef, manifest, debugInfo: debugInfo!.Clone() as JObject, optimizationType: Options.Optimize);
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.
}
catch (Exception ex)
{
Console.Error.WriteLine($"Failed to optimize: {ex}");
Console.Error.WriteLine("Please try again without using the experimental optimizer.");
Console.Error.WriteLine($"e.g. --{nameof(Options.Optimize).ToLower()}={CompilationOptions.OptimizationType.Basic}");
throw;
}
}
// Define the optimization type inside the manifest
if (Options.Optimize != CompilationOptions.OptimizationType.None)
{
manifest.Extra ??= new JObject();
manifest.Extra["nef"] = new JObject();
manifest.Extra["nef"]!["optimization"] = Options.Optimize.ToString();
}
return (nef, manifest, debugInfo!);
}
public NefFile CreateExecutable()
{
NefFile nef = new()
{
Compiler = _engine.Options.CompilerVersion,
Source = Source ?? string.Empty,
Tokens = _methodTokens.ToArray(),
Script = Script
};
if (nef.Compiler.Length > 64)
{
// Neo.Compiler.CSharp 3.6.2+470d9a8608b41de658849994a258200d8abf7caa
nef.Compiler = nef.Compiler.Substring(0, 61) + "...";
}
nef.CheckSum = NefFile.ComputeChecksum(nef);
// Ensure that is serializable
return nef.ToArray().AsSerializable<NefFile>();
}
public string CreateAssembly()
{
static void WriteMethod(StringBuilder builder, MethodConvert method)
{
foreach (Instruction i in method.Instructions)
{
builder.Append($"{i.Offset:x8}: ");
i.ToString(builder, stringInJson: true);
builder.AppendLine();
}
builder.AppendLine();
builder.AppendLine();
}
StringBuilder builder = new();
foreach (MethodConvert method in _methodsConverted)
{
builder.Append("// ");
builder.AppendLine(method.Symbol.ToString());
builder.AppendLine();
WriteMethod(builder, method);
}
foreach (MethodConvert method in _methodsForward)
{
builder.Append("// ");
builder.Append(method.Symbol.ToString());
builder.AppendLine(" (Forward)");
builder.AppendLine();
WriteMethod(builder, method);
}
return builder.ToString();
}
public ContractManifest CreateManifest()
{
// Check if we need to add the version from the project file
string? versionKey = ManifestExtraAttribute.AttributeType[nameof(ContractVersionAttribute)];
if (!_manifestExtra.ContainsProperty(versionKey))
{
string? projectVersion = _engine.GetProjectVersion();
if (!string.IsNullOrEmpty(projectVersion))
{
_manifestExtra[versionKey] = projectVersion;
}
}
JObject json = new()
{
["name"] = ContractName,
["groups"] = new JArray(),
["features"] = new JObject(),
["supportedstandards"] = _supportedStandards.OrderBy(p => p).Select(p => (JString)p!).ToArray(),
["abi"] = new JObject
{
["methods"] = _methodsExported.Select(CreateAbiMethod).ToArray(),
["events"] = _eventsExported.Select(p => new JObject
{
["name"] = p.Name,
["parameters"] = p.Parameters.Select(p => p.ToJson()).ToArray()
}).ToArray()
},
["permissions"] = _permissions.ToJson(),
["trusts"] = _trusts.Contains("*") ? "*" : _trusts.OrderBy(p => p.Length).ThenBy(p => p).Select(u => new JString(u)).ToArray(),
["extra"] = _manifestExtra
};
// Ensure that is serializable
return ContractManifest.Parse(json.ToString(false));
}
private JObject CreateAbiMethod(AbiMethod method)
{
return new JObject
{
["name"] = method.Name,
["offset"] = GetAbiOffset(method.Symbol),
["safe"] = method.Safe,
["returntype"] = method.ReturnType,
["parameters"] = method.Parameters.Select(p => p.ToJson()).ToArray()
};
}
public JObject CreateDebugInformation(string folder = "")
{
System.Collections.Generic.List<string> documents = [];
System.Collections.Generic.List<JObject> methods = [];
foreach (var m in _methodsConverted.Where(p => p.SyntaxNode is not null))
{
System.Collections.Generic.List<JString> sequencePoints = [];
JObject sequencePointsV2 = new();
foreach (var ins in m.Instructions.Where(i => i.Location?.Source?.Location.SourceTree is not null))
{
var doc = ins.Location!.Source!.Location.SourceTree!.FilePath;
if (!string.IsNullOrEmpty(folder))
{
doc = Path.GetRelativePath(folder, doc);
}
var index = documents.IndexOf(doc);
if (index == -1)
{
index = documents.Count;
documents.Add(doc);
}
var range = ins.Location.Source.GetRange();
var str = $"{ins.Offset}[{index}]{range}";
sequencePoints.Add(new JString(str));
// Create sequence-points-v2
var v2 = new JObject();
v2["optimization"] = CompilationOptions.OptimizationType.None.ToString().ToLowerInvariant();
v2["source"] = ins.Location.Source.ToJson(index);
if (ins.Location.Compiler != null)
{
v2["compiler"] = ins.Location.Compiler.ToJson();
}
sequencePointsV2[ins.Offset.ToString()] = v2;
}
var jsonMethod = new JObject
{
["id"] = m.Symbol.ToString(),
["name"] = $"{m.Symbol.ContainingType},{m.Symbol.Name}",
["range"] = $"{m.Instructions[0].Offset}-{m.Instructions[^1].Offset}",
["params"] = (m.Symbol.IsStatic ? Array.Empty<string>() : ["this,Any"])
.Concat(m.Symbol.Parameters.Select(p => $"{p.Name},{p.Type.GetContractParameterType()}"))
.Select((p, i) => ((JString)$"{p},{i}")!)
.ToArray(),
["return"] = m.Symbol.ReturnType.GetContractParameterType().ToString(),
["variables"] = m.Variables.Select(p => ((JString)$"{p.Symbol.Name},{p.Symbol.Type.GetContractParameterType()},{p.SlotIndex}")!).ToArray(),
["sequence-points"] = sequencePoints.ToArray()
};
if (Options.Debug == CompilationOptions.DebugType.Extended)
{
// Add extra information for sequencePoints
jsonMethod["sequence-points-v2"] = sequencePointsV2;
// Add abi
var exported = _methodsExported.FirstOrDefault(u => SymbolEqualityComparer.Default.Equals(u.Symbol, m.Symbol));
if (exported != null)
{
// Add abi information if the method is exported
jsonMethod["abi"] = CreateAbiMethod(exported);
}
}
methods.Add(jsonMethod);
}
var ret = new JObject
{
["hash"] = Script.ToScriptHash().ToString(),
["documents"] = documents.Select(p => (JString)p!).ToArray(),
["document-root"] = string.IsNullOrEmpty(folder) ? JToken.Null : folder,
["static-variables"] = _staticFields.OrderBy(p => p.Value).Select(p => ((JString)$"{p.Key.Name},{p.Key.Type.GetContractParameterType()},{p.Value}")!).ToArray(),
["methods"] = methods.ToArray(),
["events"] = _eventsExported.Select(e => new JObject
{
["id"] = e.Name,
["name"] = $"{e.Symbol.ContainingType},{e.Symbol.Name}",
["params"] = e.Parameters.Select((p, i) => ((JString)$"{p.Name},{p.Type},{i}")!).ToArray()
}).ToArray()
};
if (Options.Debug == CompilationOptions.DebugType.Extended)
{
ret["compiler"] = Options.CompilerVersion;
}
return ret;
}
private void ProcessCompilationUnit(HashSet<INamedTypeSymbol> processed, SemanticModel model, CompilationUnitSyntax syntax)
{
foreach (MemberDeclarationSyntax member in syntax.Members)
ProcessMemberDeclaration(processed, model, member);
}
private void ProcessMemberDeclaration(HashSet<INamedTypeSymbol> processed, SemanticModel model, MemberDeclarationSyntax syntax)
{
switch (syntax)
{
case BaseNamespaceDeclarationSyntax @namespace:
foreach (MemberDeclarationSyntax member in @namespace.Members)
ProcessMemberDeclaration(processed, model, member);
break;
case ClassDeclarationSyntax @class:
INamedTypeSymbol symbol = model.GetDeclaredSymbol(@class)!;
if (!SymbolEqualityComparer.Default.Equals(symbol, _targetContract) &&
_nonDependencies != null &&
_nonDependencies.Contains(symbol, SymbolEqualityComparer.Default))
return;
if (processed.Add(symbol)) ProcessClass(model, symbol);
break;
}
}
private void ProcessClass(SemanticModel model, INamedTypeSymbol symbol)
{
if (symbol.IsSubclassOf(nameof(Attribute))) return;
bool isPublic = symbol.DeclaredAccessibility == Accessibility.Public;
bool isAbstract = symbol.IsAbstract;
bool isContractType = symbol.IsSubclassOf(nameof(scfx.Neo.SmartContract.Framework.SmartContract));
bool isSmartContract = isPublic && !isAbstract && isContractType;
if (isSmartContract)
{
// Considering that the complication will process all classes for every smart contract
// it is possible to process multiple smart contract classes in the same project
// As a result, we must stop the process if the current contract class is not the target contract
// For example, if the target contract is "Contract1" and the project contains "Contract1" and "Contract2"
// the process must skip when the "Contract2" class is processed
if (!SymbolEqualityComparer.Default.Equals(_targetContract, symbol))
{
return;
}
foreach (var attribute in symbol.GetAttributesWithInherited())
{
if (attribute.AttributeClass!.IsSubclassOf(nameof(ManifestExtraAttribute)))
{
_manifestExtra[ManifestExtraAttribute.AttributeType[attribute.AttributeClass!.Name]] = (string)attribute.ConstructorArguments[0].Value!;
continue;
}
switch (attribute.AttributeClass!.Name)
{
case nameof(DisplayNameAttribute):
string displayName = (string)attribute.ConstructorArguments[0].Value!;
if (string.IsNullOrEmpty(displayName))
throw new CompilationException(symbol, DiagnosticId.InvalidArgument, "Contract display name cannot be empty.");
_displayName = displayName;
break;
case nameof(ContractSourceCodeAttribute):
Source = (string)attribute.ConstructorArguments[0].Value!;
break;
case nameof(ManifestExtraAttribute):
_manifestExtra[(string)attribute.ConstructorArguments[0].Value!] = (string)attribute.ConstructorArguments[1].Value!;
break;
case nameof(ContractPermissionAttribute):
string contract = (string)attribute.ConstructorArguments[0].Value!;
string[] methods = attribute.ConstructorArguments[1].Values.Select(p => (string)p.Value!).ToArray();
ValidateContractPermission(symbol, contract, methods);
_permissions.Add(contract, methods);
break;
case nameof(ContractTrustAttribute):
string trust = (string)attribute.ConstructorArguments[0].Value!;
if (!ValidateContractDescriptor(trust))
throw new CompilationException(symbol, DiagnosticId.InvalidArgument, $"The value {trust} is not a valid ContractTrust descriptor.");
_trusts.Add(trust);
break;
case nameof(SupportedStandardsAttribute):
_supportedStandards.UnionWith(
attribute.ConstructorArguments[0].Values
.Select(p => p.Value)
.Select(p =>
p is int ip && Enum.IsDefined(typeof(NepStandard), ip)
? ((NepStandard)ip).ToStandard()
: p as string
)
.Where(v => v != null)! // Ensure null values are not added
);
break;
}
}
foreach (var attribute in symbol.AllInterfaces
.SelectMany(i => i.GetAttributes())
.Where(a => a.AttributeClass?.Name == nameof(SupportedStandardsAttribute)))
{
_supportedStandards.UnionWith(
attribute.ConstructorArguments[0].Values
.Select(p => p.Value)
.Select(p =>
p is int ip && Enum.IsDefined(typeof(NepStandard), ip)
? ((NepStandard)ip).ToStandard()
: p as string
)
.Where(v => v != null)!);
}
_className = symbol.Name;
}
Dictionary<(string, int), IMethodSymbol> export = new();
// export methods `new`ed in child class, not those hidden in parent class
foreach (ISymbol member in symbol.GetAllMembers())
{
switch (member)
{
//case IEventSymbol @event when isSmartContract:
// ProcessEvent(@event);
// break;
case IMethodSymbol method when method.Name != "_initialize" && method.MethodKind != MethodKind.StaticConstructor:
if (method.DeclaredAccessibility == Accessibility.Public)
if (export.TryGetValue((method.Name, method.Parameters.Length), out IMethodSymbol? existingMethod))
{
INamedTypeSymbol containingType = method.ContainingType;
INamedTypeSymbol existingType = existingMethod.ContainingType;
if (Helper.InheritsFrom(containingType, existingType))
export[(method.Name, method.Parameters.Length)] = method;
else if (!Helper.InheritsFrom(existingType, containingType))
// no inheritance relationship, but having 2 methods of same name and same count of args
throw new CompilationException(symbol, DiagnosticId.MethodNameConflict, $"Duplicate method key: {method.Name},{method.Parameters.Length}.");
// else existingType inherits from containingType; do nothing
}
else
export.Add((method.Name, method.Parameters.Length), method);
break;
}
}
HashSet<IMethodSymbol> exportMethods = [.. export.Values];
foreach (ISymbol member in symbol.GetAllMembers())
{
switch (member)
{
case IEventSymbol @event when isSmartContract:
ProcessEvent(@event);
break;
case IMethodSymbol method when method.Name != "_initialize" && method.MethodKind != MethodKind.StaticConstructor:
if (method.DeclaredAccessibility != Accessibility.Public)
ProcessMethod(model, method, isSmartContract);
else if (exportMethods.Contains(method))
ProcessMethod(model, method, isSmartContract);
break;
}
}
if (isSmartContract)
{
IMethodSymbol initialize = symbol.StaticConstructors.Length == 0
? symbol.GetAllMembers().OfType<IMethodSymbol>().First(p => p.Name == "_initialize")
: symbol.StaticConstructors[0];
ProcessMethod(model, initialize, true);
}
}
private void ProcessEvent(IEventSymbol symbol)
{
if (symbol.DeclaredAccessibility != Accessibility.Public) return;
INamedTypeSymbol type = (INamedTypeSymbol)symbol.Type;
if (!type.DelegateInvokeMethod!.ReturnsVoid)
throw new CompilationException(symbol, DiagnosticId.EventReturns, $"Event return value is not supported.");
AddEvent(new AbiEvent(symbol), true);
}
internal void AddEvent(AbiEvent ev, bool throwErrorIfExists)
{
ValidateExportedEventName(ev);
if (_eventsExported.Any(u => u.Name == ev.Name))
{
if (!throwErrorIfExists) return;
throw new CompilationException(ev.Symbol, DiagnosticId.EventNameConflict, $"Duplicate event name: {ev.Name}.");
}
_eventsExported.Add(ev);
}
private static void ValidateExportedEventName(AbiEvent ev)
{
if (string.IsNullOrEmpty(ev.Name))
throw new CompilationException(ev.Symbol, DiagnosticId.InvalidArgument, "Contract event display name cannot be empty.");
}
private static void ValidateExportedMethodName(AbiMethod method)
{
if (string.IsNullOrEmpty(method.Name))
throw new CompilationException(method.Symbol, DiagnosticId.InvalidMethodName, "Contract method display name cannot be empty.");
}
private void ProcessMethod(SemanticModel model, IMethodSymbol symbol, bool export)
{
if (symbol.IsAbstract) return;
if (symbol.MethodKind != MethodKind.StaticConstructor)
{
if (symbol.DeclaredAccessibility != Accessibility.Public)
export = false;
if (symbol.MethodKind != MethodKind.Ordinary && symbol.MethodKind != MethodKind.PropertyGet && symbol.MethodKind != MethodKind.PropertySet)
return;
}
if (export)
{
AbiMethod method = new(symbol, _frameworkSafeAttribute);
ValidateExportedMethodName(method);
if (_methodsExported.Any(u => u.Name == method.Name && u.Parameters.Length == method.Parameters.Length))
throw new CompilationException(symbol, DiagnosticId.MethodNameConflict, $"Duplicate method key: {method.Name},{method.Parameters.Length}.");
_methodsExported.Add(method);
}
if (symbol.IsAggressiveInlineMethod())
{
if (export)
throw new CompilationException(symbol, DiagnosticId.SyntaxNotSupported, $"Cannot set contract interface '{symbol.Name}' as inline. Remove [MethodImpl(MethodImplOptions.AggressiveInlining)] attribute from contract interface methods.");
return;
}
MethodConvert convert = ConvertMethod(model, symbol);
if (export && NeedInstanceConstructor(symbol))
{
MethodConvert forward = new(this, symbol);
forward.ConvertForward(model, convert);
_methodsForward.Add(forward);
}
}
/// <summary>
/// Determines whether non-static calls need an explicit instance constructor receiver.
/// </summary>
internal bool NeedInstanceConstructor(IMethodSymbol symbol)
{
if (_needInstanceConstructorCache.TryGetValue(symbol, out bool result))
return result;
result = NeedInstanceConstructorCore(symbol);
_needInstanceConstructorCache[symbol] = result;
return result;
static bool NeedInstanceConstructorCore(IMethodSymbol symbol)
{
if (symbol.IsStatic || symbol.MethodKind == MethodKind.AnonymousFunction)
return false;
INamedTypeSymbol? containingClass = symbol.ContainingType;
if (containingClass == null)
return false;
// non-static methods in class
if ((symbol.MethodKind == MethodKind.Constructor || symbol.MethodKind == MethodKind.SharedConstructor)
&& !CompilationEngine.IsDerivedFromSmartContract(containingClass))
// is constructor, and is not smart contract
// typically seen in framework methods
return true;
if (containingClass!.Constructors
.FirstOrDefault(p => p.Parameters.Length == 0 && !p.IsStatic)?
.DeclaringSyntaxReferences.Length > 0)
// has explicit constructor
return true;
// No explicit non-static constructor in class
// is smart contract, or is normal non-static method (whether contract or not)
if (!MethodConvert.s_pattern.IsMatch(containingClass?.BaseType?.ToString() ?? string.Empty))
// class itself is not directly inheriting smart contract; can have more base classes
return true;
// is non-static method, directly inheriting smart contract
if (containingClass!.GetFields().Any((IFieldSymbol f) => !f.IsStatic))
// has non-static fields
return true;
return false;
}
}
internal MethodConvert ConvertMethod(SemanticModel model, IMethodSymbol symbol)
{
if (!_methodsConverted.TryGetValue(symbol, out MethodConvert? method))
{
method = new MethodConvert(this, symbol);
_methodsConverted.Add(method);
if (!symbol.DeclaringSyntaxReferences.IsEmpty
&& symbol.ToString() != "Neo.SmartContract.Framework.SmartContract._initialize()")
{
// The following codes typically switch the code context from user's contract to devpack framework codes.
// Be aware that, the context of the _initialize method should be remained in the user's contract
ISourceAssemblySymbol assembly = (ISourceAssemblySymbol)symbol.ContainingAssembly;
model = assembly.Compilation.GetSemanticModel(symbol.DeclaringSyntaxReferences[0].SyntaxTree);
}
method.Convert(model);
}
return method;
}
internal ushort AddMethodToken(UInt160 hash, string method, ushort parametersCount, bool hasReturnValue, CallFlags callFlags)
{
int index = _methodTokens.FindIndex(p => p.Hash == hash && p.Method == method &&
p.ParametersCount == parametersCount && p.HasReturnValue == hasReturnValue && p.CallFlags == callFlags);
if (index >= 0) return (ushort)index;
const int MaxMethodTokens = 128;
if (_methodTokens.Count >= MaxMethodTokens)
throw new CompilationException(DiagnosticId.SyntaxNotSupported, $"Contract method calls limit({MaxMethodTokens}) exceeded.");
_methodTokens.Add(new MethodToken
{
Hash = hash,
Method = method,
ParametersCount = parametersCount,
HasReturnValue = hasReturnValue,
CallFlags = callFlags
});
_permissions.Add(hash.ToString(), method);
return (ushort)(_methodTokens.Count - 1);
}
internal byte AddStaticField(IFieldSymbol symbol)
{
if (!_staticFields.TryGetValue(symbol, out byte index))
{
index = GetNextStaticSlot(symbol);
_staticFields.Add(symbol, index);
}
return index;
}
internal byte AddAnonymousStaticField()
{
byte index = GetNextStaticSlot();
_anonymousStaticFields.Add(index);
return index;
}
internal byte GetOrAddCapturedStaticField(ISymbol symbol)
{
if (_capturedStaticFields.TryGetValue(symbol, out var field))
{
return field;
}
byte index = GetNextStaticSlot(symbol);
_anonymousStaticFields.Add(index);
_capturedStaticFields.TryAdd(symbol, index);
return index;
}
internal bool TryGetCapturedStaticField(ISymbol local, out byte staticFieldIndex)
{
return _capturedStaticFields.TryGetValue(local, out staticFieldIndex);
}
internal byte AddVTable(ITypeSymbol type)
{
if (!_vtables.TryGetValue(type, out byte index))
{
index = GetNextStaticSlot(type);
_vtables.Add(type, index);
}
return index;
}
private byte GetNextStaticSlot(ISymbol? symbol = null)
{
if (StaticFieldCount >= byte.MaxValue)
{
string message = $"Contracts with more than {byte.MaxValue} static slots are not supported.";
throw symbol is null
? new CompilationException(DiagnosticId.SyntaxNotSupported, message)
: new CompilationException(symbol, DiagnosticId.SyntaxNotSupported, message);
}
return (byte)StaticFieldCount;
}
internal void AssociateCapturedStaticField(ISymbol symbol, byte index)
{
_capturedStaticFields[symbol] = index;
}
internal UInt160? GetContractHash() => Script.ToScriptHash();
}
}