Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Compiler Add]allow direct assignment to UInt160, UInt256, and ECPoint. #974

Merged
merged 8 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
4 changes: 2 additions & 2 deletions examples/Example.SmartContract.Transfer/TransferContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ namespace Transfer;
[ContractPermission(Permission.WildCard, Method.WildCard)]
public class TransferContract : SmartContract
{
[Hash160("NUuJw4C4XJFzxAvSZnFTfsNoWZytmQKXQP")]
private static readonly UInt160 Owner = default;
// [Hash160("NUuJw4C4XJFzxAvSZnFTfsNoWZytmQKXQP")]
private static readonly UInt160 Owner = "NUuJw4C4XJFzxAvSZnFTfsNoWZytmQKXQP";

/// <summary>
/// Transfer method that demonstrate how to transfer NEO and GAS
Expand Down
48 changes: 45 additions & 3 deletions src/Neo.Compiler.CSharp/MethodConvert/Expression/Expression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,61 @@
using Neo.SmartContract.Native;
using Neo.VM;
using System.Numerics;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Wallets;

namespace Neo.Compiler;

partial class MethodConvert
{
private void ConvertExpression(SemanticModel model, ExpressionSyntax syntax)
private void ConvertExpression(SemanticModel model, ExpressionSyntax syntax, SyntaxNode? syntaxNode = null)
{
using var sequence = InsertSequencePoint(syntax);

Optional<object?> constant = model.GetConstantValue(syntax);
if (constant.HasValue)
{
Push(constant.Value);
var value = constant.Value;

ITypeSymbol? typeSymbol = null;
if (syntaxNode is VariableDeclaratorSyntax variableDeclarator)
{
var declaration = variableDeclarator.Parent as VariableDeclarationSyntax;
if (declaration != null)
{
typeSymbol = ModelExtensions.GetTypeInfo(model, declaration.Type).Type;
}
}
else if (syntaxNode is PropertyDeclarationSyntax propertyDeclaration)
{
typeSymbol = ModelExtensions.GetTypeInfo(model, propertyDeclaration.Type).Type;
}

if (typeSymbol != null)
{
string fullName = typeSymbol.ToDisplayString();

switch (fullName)
{
case "Neo.SmartContract.Framework.UInt160":
var strValue = (string)value;
value = (UInt160.TryParse(strValue, out var hash)
? hash
: strValue.ToScriptHash(_context.Options.AddressVersion)).ToArray();
break;
case "Neo.SmartContract.Framework.ECPoint":
strValue = (string)value;
value = ECPoint.Parse(strValue, ECCurve.Secp256r1).EncodePoint(true);
break;
case "Neo.SmartContract.Framework.ByteArray":
strValue = (string)value;
value = strValue.HexToBytes(true);
break;
}
}

Push(value);
return;
}

Expand Down Expand Up @@ -165,7 +207,7 @@ private void EnsureIntegerInRange(ITypeSymbol type)

private void ConvertObjectToString(SemanticModel model, ExpressionSyntax expression)
{
ITypeSymbol? type = model.GetTypeInfo(expression).Type;
ITypeSymbol? type = ModelExtensions.GetTypeInfo(model, expression).Type;
switch (type?.ToString())
{
case "sbyte":
Expand Down
2 changes: 1 addition & 1 deletion src/Neo.Compiler.CSharp/MethodConvert/MethodConvert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ private void ProcessFieldInitializer(SemanticModel model, IFieldSymbol field, Ac
using (InsertSequencePoint(syntaxNode))
{
preInitialize?.Invoke();
ConvertExpression(model, initializer.Value);
ConvertExpression(model, initializer.Value, syntaxNode);
postInitialize?.Invoke();
}
}
Expand Down
21 changes: 16 additions & 5 deletions src/Neo.SmartContract.Framework/ECPoint.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright (C) 2015-2023 The Neo Project.
//
// The Neo.SmartContract.Framework 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
//
// The Neo.SmartContract.Framework 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.

using System;
using Neo.SmartContract.Framework.Attributes;

namespace Neo.SmartContract.Framework
Expand Down Expand Up @@ -39,5 +40,15 @@ public extern bool IsValid

[OpCode(OpCode.CONVERT, StackItemType.Buffer)]
public static extern explicit operator byte[](ECPoint value);

/// <summary>
/// Implicitly converts a hexadecimal string to a PublicKey object.
/// Assumes the string is a valid hexadecimal representation.
/// </summary>
public static implicit operator ECPoint(string value)
{
Jim8y marked this conversation as resolved.
Show resolved Hide resolved
return value;
}

shargon marked this conversation as resolved.
Show resolved Hide resolved
}
}
29 changes: 24 additions & 5 deletions src/Neo.SmartContract.Framework/UInt160.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright (C) 2015-2023 The Neo Project.
//
// The Neo.SmartContract.Framework 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
//
// The Neo.SmartContract.Framework 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.

using System;
using Neo.SmartContract.Framework.Attributes;
using Neo.SmartContract.Framework.Native;
using Neo.SmartContract.Framework.Services;
Expand Down Expand Up @@ -71,5 +72,23 @@ public string ToAddress(byte version)
data = Helper.Concat(data, this);
return StdLib.Base58CheckEncode((ByteString)data);
}


shargon marked this conversation as resolved.
Show resolved Hide resolved
/// <summary>
/// Implicitly converts a hexadecimal string to a UInt160 object.
/// Assumes the string is a valid hexadecimal representation.
/// </summary>
public static implicit operator UInt160(string value)
{
// Convert the hexadecimal string to a byte array.
// Ensure the byte array is of the expected size for a UInt160.
if (value.Length != 20) // UInt160 is expected to be 20 bytes.
Jim8y marked this conversation as resolved.
Show resolved Hide resolved
{
throw new Exception("The provided string does not represent a valid UInt160 value.");
}
// Use the explicit byte[] to UInt160 conversion defined earlier.
return value;
}

shargon marked this conversation as resolved.
Show resolved Hide resolved
}
}
17 changes: 11 additions & 6 deletions tests/Neo.Compiler.CSharp.TestContracts/Contract_StaticVar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,21 @@ public class Contract_StaticVar : SmartContract.Framework.SmartContract
/// A static field of type ECPoint initialized with the InitialValue attribute. This is used to demonstrate initializing
/// complex types like ECPoint at compile time to avoid runtime overhead.
/// </summary>
[PublicKey("024700db2e90d9f02c4f9fc862abaca92725f95b4fddcc8d7ffa538693ecf463a9")]
private static readonly ECPoint eCPoint = default;
// [PublicKey("024700db2e90d9f02c4f9fc862abaca92725f95b4fddcc8d7ffa538693ecf463a9")]
private static readonly ECPoint eCPoint = "024700db2e90d9f02c4f9fc862abaca92725f95b4fddcc8d7ffa538693ecf463a9";

/// <summary>
/// A static field of type UInt160 initialized with the InitialValue attribute. This allows for compile-time
/// initialization of blockchain-specific types like addresses, represented here as Hash160.
/// </summary>
[Hash160("NXV7ZhHiyM1aHXwpVsRZC6BwNFP2jghXAq")]
private static readonly UInt160 uInt160 = default;
// [Hash160("NXV7ZhHiyM1aHXwpVsRZC6BwNFP2jghXAq")]
private static readonly UInt160 uInt160 = "NXV7ZhHiyM1aHXwpVsRZC6BwNFP2jghXAq";

/// <summary>
/// A static string field initialized with the InitialValue attribute. This demonstrates initializing contract fields that cannot be directly assigned with their value at compile time.
/// </summary>
[String("hello world")]
public static readonly string a4 = default;
// [String("hello world")]
public static readonly string a4 = "hello world";

/// <summary>
/// Tests retrieval of the static field initialized with an initial value.
Expand Down Expand Up @@ -82,5 +82,10 @@ public static ECPoint testGetECPoint()
{
return eCPoint;
}

public static string testGetString()
{
return a4;
}
}
}
11 changes: 11 additions & 0 deletions tests/Neo.Compiler.CSharp.UnitTests/UnitTest_StaticVar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,16 @@ public void Test_GetECPoint()

Assert.AreEqual(value.ToArray().ToHexString(), "024700db2e90d9f02c4f9fc862abaca92725f95b4fddcc8d7ffa538693ecf463a9");
}

[TestMethod]
public void Test_GetString()
{
using var testengine = new TestEngine(snapshot: new TestDataCache());
testengine.AddEntryScript(Utils.Extensions.TestContractRoot + "Contract_StaticVar.cs");
var result = testengine.ExecuteTestCaseStandard("testGetString");
var value = result.Pop().GetString();

Assert.AreEqual(value, "hello world");
}
}
}
Loading