Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1999355
allow multiple smart contract exist in one project
Feb 17, 2024
136fc1f
fix remaining issues
Feb 18, 2024
f2f35d8
update unit tests
Feb 18, 2024
2019abb
code optimization
Feb 18, 2024
8d2d4bc
Update tests/Neo.SmartContract.TestEngine/TestEngine.cs
shargon Feb 18, 2024
5ad5bd9
Test it: Compile to artifacts
shargon Feb 18, 2024
fbf7a89
clean changes
shargon Feb 18, 2024
3152f36
fix complication issue
Feb 18, 2024
e96d5e6
multiple smart contract topology analysis. Making it easier to suppor…
Feb 18, 2024
b1c2efa
Merge branch 'master' into multi-contracts
shargon Feb 19, 2024
6ed8b6b
Move artifact generation to the test project
shargon Feb 19, 2024
cc022b1
Merge branch 'multi-contracts' of https://github.com/Liaojinghui/neo-…
shargon Feb 19, 2024
f6cffd9
Merge branch 'master' into multi-contracts
shargon Feb 19, 2024
1ddf9ba
Merge branch 'master' into multi-contracts
Jim8y Feb 23, 2024
4d6e622
fix conflict
Feb 23, 2024
8ccbb90
Merge branch 'master' into multi-contracts
shargon Feb 23, 2024
a08b749
Merge branch 'master' into multi-contracts
Jim8y Feb 24, 2024
50c5c26
update neo
Feb 24, 2024
d9a3d4c
fix error
Feb 24, 2024
e04f5a6
this pr apply latest neo to devpack
Feb 24, 2024
1a30ea1
Merge branch 'update-neo' into multi-contracts
Feb 24, 2024
33a377a
Merge branch 'master' into multi-contracts
Feb 24, 2024
cf94f21
update signle contract check
Feb 24, 2024
2a4a2fd
add comments
Feb 24, 2024
74f613b
Merge branch 'master' into multi-contracts
Jim8y Feb 24, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
313 changes: 96 additions & 217 deletions src/Neo.Compiler.CSharp/CompilationContext.cs

Large diffs are not rendered by default.

258 changes: 258 additions & 0 deletions src/Neo.Compiler.CSharp/CompilationEngine.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
// Copyright (C) 2015-2024 The Neo Project.
//
// The Neo.Compiler.CSharp is free software distributed under the MIT
// software license, see the accompanying file LICENSE in the main directory
// of the project 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.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using BigInteger = System.Numerics.BigInteger;

namespace Neo.Compiler
{
public class CompilationEngine
{
internal Compilation? Compilation;
internal Options Options { get; private set; }
private static readonly MetadataReference[] CommonReferences;
private static readonly Dictionary<string, MetadataReference> MetaReferences = new();
internal readonly Dictionary<INamedTypeSymbol, CompilationContext> Contexts = new(SymbolEqualityComparer.Default);

static CompilationEngine()
{
string coreDir = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
CommonReferences = new MetadataReference[]
{
MetadataReference.CreateFromFile(Path.Combine(coreDir, "System.Runtime.dll")),
MetadataReference.CreateFromFile(Path.Combine(coreDir, "System.Runtime.InteropServices.dll")),
MetadataReference.CreateFromFile(typeof(string).Assembly.Location),
MetadataReference.CreateFromFile(typeof(DisplayNameAttribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(BigInteger).Assembly.Location)
};
}

public CompilationEngine(Options options)
{
Options = options;
}

public List<CompilationContext> Compile(IEnumerable<string> sourceFiles, IEnumerable<MetadataReference> references)
{
IEnumerable<SyntaxTree> syntaxTrees = sourceFiles.OrderBy(p => p).Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), options: Options.GetParseOptions(), path: p));
if (IsSingleAbstractClass(syntaxTrees)) throw new FormatException("The given class is abstract, no valid neo SmartContract found.");
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true, nullableContextOptions: Options.Nullable);
Compilation = CSharpCompilation.Create(null, syntaxTrees, references, compilationOptions);
return CompileProjectContracts(Compilation);
}

public List<CompilationContext> CompileSources(string[] sourceFiles)
{
List<MetadataReference> references = new(CommonReferences)
{
MetadataReference.CreateFromFile(typeof(scfx.Neo.SmartContract.Framework.SmartContract).Assembly.Location)
};
return Compile(sourceFiles, references);
}

public List<CompilationContext> CompileProject(string csproj)
{
Compilation = GetCompilation(csproj);
return CompileProjectContracts(Compilation);
}

private List<CompilationContext> CompileProjectContracts(Compilation compilation)
{
var classDependencies = new Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>>(SymbolEqualityComparer.Default);
var allSmartContracts = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);

foreach (var tree in compilation.SyntaxTrees)
{
var semanticModel = compilation.GetSemanticModel(tree);
var classNodes = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>();

foreach (var classNode in classNodes)
{
var classSymbol = semanticModel.GetDeclaredSymbol(classNode);
if (classSymbol != null && IsDerivedFromSmartContract(classSymbol, "Neo.SmartContract.Framework.SmartContract", semanticModel))
{
allSmartContracts.Add(classSymbol);
classDependencies[classSymbol] = new List<INamedTypeSymbol>();
foreach (var member in classSymbol.GetMembers())
{
var memberTypeSymbol = (member as IFieldSymbol)?.Type ?? (member as IPropertySymbol)?.Type;
if (memberTypeSymbol is INamedTypeSymbol namedTypeSymbol && allSmartContracts.Contains(namedTypeSymbol))
{
classDependencies[classSymbol].Add(namedTypeSymbol);
}
}
}
}
}

var sortedClasses = TopologicalSort(classDependencies);
foreach (var classSymbol in sortedClasses)
{
new CompilationContext(this, classSymbol).Compile();
}

return Contexts.Select(p => p.Value).ToList();
}

private static List<INamedTypeSymbol> TopologicalSort(Dictionary<INamedTypeSymbol, List<INamedTypeSymbol>> dependencies)
{
var sorted = new List<INamedTypeSymbol>();
var visited = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default);
var visiting = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); // 添加中间状态以检测循环依赖

void Visit(INamedTypeSymbol classSymbol)
{
if (visited.Contains(classSymbol))
{
return;
}
if (visiting.Contains(classSymbol))
{
throw new InvalidOperationException("Cyclic dependency detected");
}

visiting.Add(classSymbol);

if (dependencies.TryGetValue(classSymbol, out var dependency))
{
foreach (var dep in dependency)
{
Visit(dep);
}
}

visiting.Remove(classSymbol);
visited.Add(classSymbol);
sorted.Add(classSymbol);
}

foreach (var classSymbol in dependencies.Keys)
{
Visit(classSymbol);
}

return sorted;
}

static bool IsDerivedFromSmartContract(INamedTypeSymbol classSymbol, string smartContractFullyQualifiedName, SemanticModel semanticModel)
{
var baseType = classSymbol.BaseType;
while (baseType != null)
{
if (baseType.ToDisplayString() == smartContractFullyQualifiedName)
{
return true;
}
baseType = baseType.BaseType;
}
return false;
}

public Compilation GetCompilation(string csproj)
{
string folder = Path.GetDirectoryName(csproj)!;
string obj = Path.Combine(folder, "obj");
HashSet<string> sourceFiles = Directory.EnumerateFiles(folder, "*.cs", SearchOption.AllDirectories)
.Where(p => !p.StartsWith(obj))
.GroupBy(Path.GetFileName)
Comment thread
shargon marked this conversation as resolved.
.Select(g => g.First())
.ToHashSet(StringComparer.OrdinalIgnoreCase);
List<MetadataReference> references = new(CommonReferences);
CSharpCompilationOptions compilationOptions = new(OutputKind.DynamicallyLinkedLibrary, deterministic: true, nullableContextOptions: Options.Nullable);
XDocument document = XDocument.Load(csproj);
sourceFiles.UnionWith(document.Root!.Elements("ItemGroup").Elements("Compile").Attributes("Include").Select(p => Path.GetFullPath(p.Value, folder)));
Process.Start(new ProcessStartInfo
{
FileName = "dotnet",
Arguments = $"restore \"{csproj}\"",
WorkingDirectory = folder
})!.WaitForExit();
string assetsPath = Path.Combine(folder, "obj", "project.assets.json");
JObject assets = (JObject)JToken.Parse(File.ReadAllBytes(assetsPath))!;
foreach (var (name, package) in ((JObject)assets["targets"]![0]!).Properties)
{
MetadataReference? reference = GetReference(name, (JObject)package!, assets, folder, Options, compilationOptions);
if (reference is not null) references.Add(reference);
}
IEnumerable<SyntaxTree> syntaxTrees = sourceFiles.OrderBy(p => p).Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), options: Options.GetParseOptions(), path: p));
return CSharpCompilation.Create(assets["project"]!["restore"]!["projectName"]!.GetString(), syntaxTrees, references, compilationOptions);
}

private MetadataReference? GetReference(string name, JObject package, JObject assets, string folder, Options options, CSharpCompilationOptions compilationOptions)
{
string assemblyName = Path.GetDirectoryName(name)!;
if (!MetaReferences.TryGetValue(assemblyName, out var reference))
{
switch (assets["libraries"]![name]!["type"]!.GetString())
{
case "package":
string packagesPath = assets["project"]!["restore"]!["packagesPath"]!.GetString();
string namePath = assets["libraries"]![name]!["path"]!.GetString();
string[] files = ((JArray)assets["libraries"]![name]!["files"]!)
.Select(p => p!.GetString())
.Where(p => p.StartsWith("src/"))
.ToArray();
if (files.Length == 0)
{
JObject? dllFiles = (JObject?)(package["compile"] ?? package["runtime"]);
if (dllFiles is null) return null;
foreach (var (file, _) in dllFiles.Properties)
{
if (file.EndsWith("_._")) continue;
string path = Path.Combine(packagesPath, namePath, file);
if (!File.Exists(path)) continue;
reference = MetadataReference.CreateFromFile(path);
break;
}
if (reference is null) return null;
}
else
{
IEnumerable<SyntaxTree> st = files.OrderBy(p => p).Select(p => Path.Combine(packagesPath, namePath, p)).Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), path: p));
CSharpCompilation cr = CSharpCompilation.Create(assemblyName, st, CommonReferences, compilationOptions);
reference = cr.ToMetadataReference();
}
break;
case "project":
string msbuildProject = assets["libraries"]![name]!["msbuildProject"]!.GetString();
msbuildProject = Path.GetFullPath(msbuildProject, folder);
reference = GetCompilation(msbuildProject).ToMetadataReference();
break;
default:
throw new NotSupportedException();
}
MetaReferences.Add(assemblyName, reference);
}
return reference;
}

private static bool IsSingleAbstractClass(IEnumerable<SyntaxTree> syntaxTrees)
Comment thread
Jim8y marked this conversation as resolved.
Outdated
{
if (syntaxTrees.Count() != 1) return false;

var tree = syntaxTrees.First();
var classDeclarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().ToList();

return classDeclarations.Count == 1 && classDeclarations[0].Modifiers.Any(SyntaxKind.AbstractKeyword);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private void ConvertFieldIdentifierNameCoalesceAssignment(SemanticModel model, I
JumpTarget endTarget = new();
if (left.IsStatic)
{
byte index = context.AddStaticField(left);
byte index = _context.AddStaticField(left);
AccessSlot(OpCode.LDSFLD, index);
AddInstruction(OpCode.ISNULL);
Jump(OpCode.JMPIF_L, assignmentTarget);
Expand Down Expand Up @@ -232,7 +232,7 @@ private void ConvertFieldMemberAccessCoalesceAssignment(SemanticModel model, Mem
JumpTarget endTarget = new();
if (field.IsStatic)
{
byte index = context.AddStaticField(field);
byte index = _context.AddStaticField(field);
AccessSlot(OpCode.LDSFLD, index);
AddInstruction(OpCode.ISNULL);
Jump(OpCode.JMPIF_L, assignmentTarget);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ private void ConvertFieldIdentifierNameComplexAssignment(SemanticModel model, IT
{
if (left.IsStatic)
{
byte index = context.AddStaticField(left);
byte index = _context.AddStaticField(left);
AccessSlot(OpCode.LDSFLD, index);
ConvertExpression(model, right);
EmitComplexAssignmentOperator(type, operatorToken);
Expand Down Expand Up @@ -184,7 +184,7 @@ private void ConvertFieldMemberAccessComplexAssignment(SemanticModel model, ITyp
{
if (field.IsStatic)
{
byte index = context.AddStaticField(field);
byte index = _context.AddStaticField(field);
AccessSlot(OpCode.LDSFLD, index);
ConvertExpression(model, right);
EmitComplexAssignmentOperator(type, operatorToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ private void ConvertIdentifierNameAssignment(SemanticModel model, IdentifierName
case IFieldSymbol field:
if (field.IsStatic)
{
byte index = context.AddStaticField(field);
byte index = _context.AddStaticField(field);
AccessSlot(OpCode.STSFLD, index);
}
else
Expand Down Expand Up @@ -139,7 +139,7 @@ private void ConvertMemberAccessAssignment(SemanticModel model, MemberAccessExpr
case IFieldSymbol field:
if (field.IsStatic)
{
byte index = context.AddStaticField(field);
byte index = _context.AddStaticField(field);
AccessSlot(OpCode.STSFLD, index);
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ private void ConvertIdentifierNameExpression(SemanticModel model, IdentifierName
}
else if (field.IsStatic)
{
byte index = context.AddStaticField(field);
byte index = _context.AddStaticField(field);
AccessSlot(OpCode.LDSFLD, index);
}
else
Expand All @@ -52,7 +52,7 @@ private void ConvertIdentifierNameExpression(SemanticModel model, IdentifierName
case IMethodSymbol method:
if (!method.IsStatic)
throw new CompilationException(expression, DiagnosticId.NonStaticDelegate, $"Unsupported delegate: {method}");
MethodConvert convert = context.ConvertMethod(model, method);
MethodConvert convert = _context.ConvertMethod(model, method);
Jump(OpCode.PUSHA, convert._startTarget);
break;
case IParameterSymbol parameter:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ private void ConvertMemberAccessExpression(SemanticModel model, MemberAccessExpr
}
else if (field.IsStatic)
{
byte index = context.AddStaticField(field);
byte index = _context.AddStaticField(field);
AccessSlot(OpCode.LDSFLD, index);
}
else
Expand All @@ -46,7 +46,7 @@ private void ConvertMemberAccessExpression(SemanticModel model, MemberAccessExpr
case IMethodSymbol method:
if (!method.IsStatic)
throw new CompilationException(expression, DiagnosticId.NonStaticDelegate, $"Unsupported delegate: {method}");
MethodConvert convert = context.ConvertMethod(model, method);
MethodConvert convert = _context.ConvertMethod(model, method);
Jump(OpCode.PUSHA, convert._startTarget);
break;
case IPropertySymbol property:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ private void ConvertDelegateCreationExpression(SemanticModel model, BaseObjectCr
IMethodSymbol symbol = (IMethodSymbol)model.GetSymbolInfo(expression.ArgumentList.Arguments[0].Expression).Symbol!;
if (!symbol.IsStatic)
throw new CompilationException(expression, DiagnosticId.NonStaticDelegate, $"Unsupported delegate: {symbol}");
MethodConvert convert = context.ConvertMethod(model, symbol);
MethodConvert convert = _context.ConvertMethod(model, symbol);
Jump(OpCode.PUSHA, convert._startTarget);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ private void ConvertFieldIdentifierNamePostIncrementOrDecrementExpression(Syntax
{
if (symbol.IsStatic)
{
byte index = context.AddStaticField(symbol);
byte index = _context.AddStaticField(symbol);
AccessSlot(OpCode.LDSFLD, index);
AddInstruction(OpCode.DUP);
EmitIncrementOrDecrement(operatorToken, symbol.Type);
Expand Down Expand Up @@ -192,7 +192,7 @@ private void ConvertFieldMemberAccessPostIncrementOrDecrementExpression(Semantic
{
if (symbol.IsStatic)
{
byte index = context.AddStaticField(symbol);
byte index = _context.AddStaticField(symbol);
AccessSlot(OpCode.LDSFLD, index);
AddInstruction(OpCode.DUP);
EmitIncrementOrDecrement(operatorToken, symbol.Type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ private void ConvertFieldIdentifierNamePreIncrementOrDecrementExpression(SyntaxT
{
if (symbol.IsStatic)
{
byte index = context.AddStaticField(symbol);
byte index = _context.AddStaticField(symbol);
AccessSlot(OpCode.LDSFLD, index);
EmitIncrementOrDecrement(operatorToken, symbol.Type);
AddInstruction(OpCode.DUP);
Expand Down Expand Up @@ -209,7 +209,7 @@ private void ConvertFieldMemberAccessPreIncrementOrDecrementExpression(SemanticM
{
if (symbol.IsStatic)
{
byte index = context.AddStaticField(symbol);
byte index = _context.AddStaticField(symbol);
AccessSlot(OpCode.LDSFLD, index);
EmitIncrementOrDecrement(operatorToken, symbol.Type);
AddInstruction(OpCode.DUP);
Expand Down
Loading