Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

### C# -> VB

* Evaluate built-in nint/nuint operators on Long/ULong, so the distance between two pointers doesn't throw or fail to compile
* Don't emit Me on the first parameter of an extension method - [#1118](https://github.com/icsharpcode/CodeConverter/issues/1118)
* Truncate towards zero when converting a fractional number to an integer, instead of inheriting VB's rounding - [#1021](https://github.com/icsharpcode/CodeConverter/issues/1021)
* Convert nint/nuint to IntPtr/UIntPtr instead of the undefined nint/System.nint

## [10.0.2] - 2026-11-08

Expand Down
1 change: 1 addition & 0 deletions CodeConverter/Util/VBUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public static SyntaxKind GetExpressionOperatorTokenKind(this SyntaxKind op)
SyntaxKind.SubtractExpression => SyntaxKind.MinusToken,
SyntaxKind.MultiplyExpression => SyntaxKind.AsteriskToken,
SyntaxKind.DivideExpression => SyntaxKind.SlashToken,
SyntaxKind.IntegerDivideExpression => SyntaxKind.BackslashToken,
SyntaxKind.ModuloExpression => SyntaxKind.ModKeyword,
SyntaxKind.LeftShiftExpression => SyntaxKind.LessThanLessThanToken,
SyntaxKind.RightShiftExpression => SyntaxKind.GreaterThanGreaterThanToken,
Expand Down
27 changes: 26 additions & 1 deletion CodeConverter/VB/CsExpander.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,34 @@ public SyntaxNode ExpandNode(SyntaxNode node, SemanticModel semanticModel,
Workspace workspace)
{
SyntaxNode expandedNode = Simplifier.Expand(node, semanticModel, workspace);
return WithoutGlobalOverqualification(expandedNode);
return WithNativeIntegerKeywords(WithoutGlobalOverqualification(expandedNode));
}

/// <summary>
/// Roslyn displays System.IntPtr/UIntPtr with the C# keywords nint/nuint (the same types since C# 11), so the expansion
/// qualifies them as System.nint/System.nuint, which don't exist. Put the keyword back so the name still binds.
/// </summary>
private static SyntaxNode WithNativeIntegerKeywords(SyntaxNode expandedNode)
{
var qualifiedNativeIntegers = expandedNode.DescendantNodesAndSelf()
.Where(n => n is QualifiedNameSyntax { Left: var left, Right: var right } && IsSystemNamespace(left) && IsNativeIntegerKeyword(right)
|| n is MemberAccessExpressionSyntax { Expression: var expression, Name: var name } && IsSystemNamespace(expression) && IsNativeIntegerKeyword(name))
.ToArray();
if (!qualifiedNativeIntegers.Any()) return expandedNode;
return expandedNode.ReplaceNodes(qualifiedNativeIntegers, (original, _) => {
var keyword = original is QualifiedNameSyntax q ? q.Right : ((MemberAccessExpressionSyntax)original).Name;
return keyword.WithTriviaFrom(original);
});
}

private static bool IsNativeIntegerKeyword(SimpleNameSyntax name) => name is IdentifierNameSyntax { IsNint: true } or IdentifierNameSyntax { IsNuint: true };

private static bool IsSystemNamespace(ExpressionSyntax expression) => expression switch {
IdentifierNameSyntax id => id.Identifier.ValueText == nameof(System),
AliasQualifiedNameSyntax alias => alias.Alias.IsGlobalId() && alias.Name.Identifier.ValueText == nameof(System),
_ => false
};

/// <summary>
/// The VB reduction step doesn't seem to reduce things qualified with global, so don't add it anywhere it isn't already
/// </summary>
Expand Down
142 changes: 142 additions & 0 deletions CodeConverter/VB/NativeIntegerOperators.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.VisualBasic;
using ExpressionSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.ExpressionSyntax;
using SyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory;
using SyntaxKind = Microsoft.CodeAnalysis.VisualBasic.SyntaxKind;

namespace ICSharpCode.CodeConverter.VB;

/// <summary>
/// C#'s built-in operators on nint/nuint (also spelled IntPtr/UIntPtr since C# 11) have no VB counterpart: VB only sees
/// IntPtr/UIntPtr's own operators (+ and - with an Integer offset, =, &lt;&gt;) and explicit conversions, because .NET 7's
/// numeric operators are explicit interface implementations. With Option Strict Off VB would otherwise narrow an operand
/// to Integer (throwing beyond Int32, e.g. for the distance between two pointers) or not compile at all.
/// So such an operation is evaluated on Long/ULong, with the result converted back when C#'s result is a native integer.
/// Where VB's own IntPtr/UIntPtr operator does what C#'s does, the output is left as it is.
/// Like other integer arithmetic, the Long/ULong operation is overflow-checked in VB where C#'s is unchecked by default.
/// </summary>
internal class NativeIntegerOperators
{
private readonly SemanticModel _semanticModel;
private readonly CommonConversions _commonConversions;

public NativeIntegerOperators(SemanticModel semanticModel, CommonConversions commonConversions)
{
_semanticModel = semanticModel;
_commonConversions = commonConversions;
}

/// <returns>Null when the operation needs nothing special</returns>
public ExpressionSyntax ConvertBinaryOrNull(CSSyntax.BinaryExpressionSyntax node, ExpressionSyntax vbLeft, ExpressionSyntax vbRight)
{
if (_semanticModel.GetOperation(node) is not IBinaryOperation { OperatorMethod: null } operation) return null;
var operatorType = IsNativeInteger(operation.LeftOperand.Type) ? operation.LeftOperand.Type
: IsNativeInteger(operation.RightOperand.Type) ? operation.RightOperand.Type
: null;
return ConvertOrNull(operation.OperatorKind, operatorType, OriginalType(operation.LeftOperand), vbLeft,
OriginalType(operation.RightOperand), vbRight, operation.Type);
}

/// <returns>The value to assign to the target, or null when the compound assignment needs nothing special</returns>
public ExpressionSyntax ConvertCompoundAssignmentValueOrNull(CSSyntax.AssignmentExpressionSyntax node, ExpressionSyntax vbTarget, ExpressionSyntax vbValue)
{
if (_semanticModel.GetOperation(node) is not ICompoundAssignmentOperation { OperatorMethod: null } operation) return null;
var targetType = operation.Target.Type;
var operatorType = IsNativeInteger(targetType) ? targetType : null;
return ConvertOrNull(operation.OperatorKind, operatorType, targetType, vbTarget, OriginalType(operation.Value), vbValue, targetType);
}

/// <returns>Null when the operation needs nothing special</returns>
public ExpressionSyntax ConvertUnaryOrNull(CSSyntax.PrefixUnaryExpressionSyntax node, ExpressionSyntax vbOperand)
{
if (_semanticModel.GetOperation(node) is not IUnaryOperation { OperatorMethod: null } operation || !IsNativeInteger(operation.Type)) return null;
var kind = operation.OperatorKind switch {
UnaryOperatorKind.Minus => SyntaxKind.UnaryMinusExpression,
UnaryOperatorKind.Plus => SyntaxKind.UnaryPlusExpression,
UnaryOperatorKind.BitwiseNegation => SyntaxKind.NotExpression,
_ => SyntaxKind.None
};
if (kind == SyntaxKind.None) return null;
var unary = SyntaxFactory.UnaryExpression(kind, SyntaxFactory.Token(kind.GetExpressionOperatorTokenKind()), To64Bit(vbOperand, operation.Type));
return ToNativeInteger(unary, operation.Type);
}

private ExpressionSyntax ConvertOrNull(BinaryOperatorKind operatorKind, ITypeSymbol operatorType,
ITypeSymbol leftType, ExpressionSyntax vbLeft, ITypeSymbol rightType, ExpressionSyntax vbRight, ITypeSymbol resultType)
{
if (operatorType == null && !IsNativeInteger(leftType) && !IsNativeInteger(rightType)) return null;
if (operatorType != null && HasMatchingVbOperator(operatorKind, leftType, rightType)) return null;
var kind = ToVbBinaryKind(operatorKind);
if (kind == SyntaxKind.None) return null;

var isShift = operatorKind is BinaryOperatorKind.LeftShift or BinaryOperatorKind.RightShift;
var binary = SyntaxFactory.BinaryExpression(kind,
ConvertOperand(vbLeft, leftType, operatorType),
SyntaxFactory.Token(kind.GetExpressionOperatorTokenKind()),
isShift ? vbRight : ConvertOperand(vbRight, rightType, operatorType));
return IsNativeInteger(resultType) ? ToNativeInteger(binary, resultType) : binary;
}

/// <summary>
/// IntPtr/UIntPtr declare = and &lt;&gt;, and + and - with an Integer offset, which are unchecked like C#'s.
/// An operand narrower than Integer widens to it.
/// </summary>
private static bool HasMatchingVbOperator(BinaryOperatorKind operatorKind, ITypeSymbol leftType, ITypeSymbol rightType) =>
operatorKind switch {
BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals => true,
BinaryOperatorKind.Add or BinaryOperatorKind.Subtract => IsNativeInteger(leftType) && WidensToInteger(rightType),
_ => false
};

private static bool WidensToInteger(ITypeSymbol type) =>
type?.SpecialType is SpecialType.System_SByte or SpecialType.System_Byte or SpecialType.System_Int16
or SpecialType.System_UInt16 or SpecialType.System_Int32;

/// <summary>
/// A native integer operand becomes Long/ULong. With a ULong operator, VB would otherwise pick Decimal for ULong with
/// a signed operand, so the other operand becomes ULong too; with a Long operator VB widens it.
/// </summary>
private static ExpressionSyntax ConvertOperand(ExpressionSyntax vbOperand, ITypeSymbol operandType, ITypeSymbol operatorType)
{
if (IsNativeInteger(operandType)) return To64Bit(vbOperand, operandType);
if (operatorType?.SpecialType == SpecialType.System_UIntPtr && operandType?.SpecialType != SpecialType.System_UInt64) {
return To64Bit(vbOperand, operatorType);
}
return vbOperand;
}

private static ExpressionSyntax To64Bit(ExpressionSyntax vbOperand, ITypeSymbol nativeIntegerType)
{
var keyword = nativeIntegerType.SpecialType == SpecialType.System_UIntPtr ? SyntaxKind.CULngKeyword : SyntaxKind.CLngKeyword;
return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(keyword), vbOperand);
}

private ExpressionSyntax ToNativeInteger(ExpressionSyntax vbExpression, ITypeSymbol nativeIntegerType) =>
SyntaxFactory.CTypeExpression(vbExpression, _commonConversions.GetFullyQualifiedNameSyntax(nativeIntegerType, allowGlobalPrefix: false));

private static SyntaxKind ToVbBinaryKind(BinaryOperatorKind operatorKind) =>
operatorKind switch {
BinaryOperatorKind.Add => SyntaxKind.AddExpression,
BinaryOperatorKind.Subtract => SyntaxKind.SubtractExpression,
BinaryOperatorKind.Multiply => SyntaxKind.MultiplyExpression,
BinaryOperatorKind.Divide => SyntaxKind.IntegerDivideExpression,
BinaryOperatorKind.Remainder => SyntaxKind.ModuloExpression,
BinaryOperatorKind.LeftShift => SyntaxKind.LeftShiftExpression,
BinaryOperatorKind.RightShift => SyntaxKind.RightShiftExpression,
BinaryOperatorKind.And => SyntaxKind.AndExpression,
BinaryOperatorKind.Or => SyntaxKind.OrExpression,
BinaryOperatorKind.ExclusiveOr => SyntaxKind.ExclusiveOrExpression,
BinaryOperatorKind.Equals => SyntaxKind.EqualsExpression,
BinaryOperatorKind.NotEquals => SyntaxKind.NotEqualsExpression,
BinaryOperatorKind.LessThan => SyntaxKind.LessThanExpression,
BinaryOperatorKind.LessThanOrEqual => SyntaxKind.LessThanOrEqualExpression,
BinaryOperatorKind.GreaterThan => SyntaxKind.GreaterThanExpression,
BinaryOperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanOrEqualExpression,
_ => SyntaxKind.None
};

private static ITypeSymbol OriginalType(IOperation operand) =>
operand is IConversionOperation { IsImplicit: true } conversion ? conversion.Operand.Type : operand.Type;

private static bool IsNativeInteger(ITypeSymbol type) => type?.SpecialType is SpecialType.System_IntPtr or SpecialType.System_UIntPtr;
}
15 changes: 15 additions & 0 deletions CodeConverter/VB/NativeIntegerTypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace ICSharpCode.CodeConverter.VB;

/// <summary>
/// C# <c>nint</c>/<c>nuint</c> are contextual keywords for System.IntPtr/System.UIntPtr (the same types since C# 11),
/// and Roslyn displays those types with them, e.g. in the casts that Simplifier.Expand adds.
/// VB has no keyword for them, and there is no System.nint type to qualify them with.
/// </summary>
internal static class NativeIntegerTypeExtensions
{
public static ITypeSymbol GetNativeIntegerTypeOrNull(this SemanticModel semanticModel, CSSyntax.IdentifierNameSyntax name)
{
if (!name.IsNint && !name.IsNuint || name.SyntaxTree != semanticModel.SyntaxTree) return null;
return semanticModel.GetSymbolInfo(name).Symbol is ITypeSymbol { IsNativeIntegerType: true } type ? type : null;
}
}
18 changes: 16 additions & 2 deletions CodeConverter/VB/NodesVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ internal class NodesVisitor : CS.CSharpSyntaxVisitor<VisualBasicSyntaxNode>
private readonly HashSet<string> _extraImports = new();
private readonly CSharpHelperMethodDefinition _cSharpHelperMethodDefinition;
private readonly CommonConversions _commonConversions;
private readonly NativeIntegerOperators _nativeIntegerOperators;
private readonly HashSet<string> _addedNames = new();

private int _placeholder = 1;
Expand All @@ -74,6 +75,7 @@ public NodesVisitor(CS.CSharpCompilation compilation, SemanticModel semanticMode
_outputWillBeOverflowChecked = outputWillBeOverflowChecked;
TriviaConvertingVisitor = new CommentConvertingVisitorWrapper<VisualBasicSyntaxNode>(this);
_commonConversions = new CommonConversions(semanticModel, vbSyntaxGenerator, TriviaConvertingVisitor, _outputWillBeOverflowChecked);
_nativeIntegerOperators = new NativeIntegerOperators(semanticModel, _commonConversions);
_cSharpHelperMethodDefinition = new CSharpHelperMethodDefinition();
}

Expand Down Expand Up @@ -1082,7 +1084,9 @@ public override VisualBasicSyntaxNode VisitPrefixUnaryExpression(CSSyntax.Prefix
ExpressionSyntaxExtensions.CreateArgList((ExpressionSyntax)node.Operand.Accept(TriviaConvertingVisitor))
);
}
return SyntaxFactory.UnaryExpression(kind, SyntaxFactory.Token(kind.GetExpressionOperatorTokenKind()), (ExpressionSyntax)node.Operand.Accept(TriviaConvertingVisitor));
var operand = (ExpressionSyntax)node.Operand.Accept(TriviaConvertingVisitor);
return _nativeIntegerOperators.ConvertUnaryOrNull(node, operand)
?? SyntaxFactory.UnaryExpression(kind, SyntaxFactory.Token(kind.GetExpressionOperatorTokenKind()), operand);
}
private static string GetQualifiedName(params string[] names) {
return names.Aggregate((seed, current) => seed + '.' + current);
Expand Down Expand Up @@ -1195,8 +1199,11 @@ node.Parent is CSSyntax.ForStatementSyntax ||
node.Parent.IsParentKind(CS.SyntaxKind.SetAccessorDeclaration);
}

private static AssignmentStatementSyntax MakeAssignmentStatement(CSSyntax.AssignmentExpressionSyntax node, ExpressionSyntax left, ExpressionSyntax right)
private AssignmentStatementSyntax MakeAssignmentStatement(CSSyntax.AssignmentExpressionSyntax node, ExpressionSyntax left, ExpressionSyntax right)
{
if (_nativeIntegerOperators.ConvertCompoundAssignmentValueOrNull(node, left, right) is { } nativeIntegerValue) {
return SyntaxFactory.SimpleAssignmentStatement(left, nativeIntegerValue);
}
var kind = CS.CSharpExtensions.Kind(node).ConvertToken(TokenContext.Local);
if (node.IsKind(CS.SyntaxKind.AndAssignmentExpression, CS.SyntaxKind.OrAssignmentExpression, CS.SyntaxKind.ExclusiveOrAssignmentExpression, CS.SyntaxKind.ModuloAssignmentExpression)) {
return SyntaxFactory.SimpleAssignmentStatement(
Expand Down Expand Up @@ -1404,6 +1411,10 @@ public override VisualBasicSyntaxNode VisitBinaryExpression(CSSyntax.BinaryExpre
return SyntaxFactory.IsNotExpression(vbLeft, vbRight);
}

if (_nativeIntegerOperators.ConvertBinaryOrNull(node, vbLeft, vbRight) is { } nativeIntegerOperation) {
return nativeIntegerOperation;
}

var kind = CS.CSharpExtensions.Kind(node).ConvertToken(TokenContext.Local);
if (node.IsKind(CS.SyntaxKind.AddExpression) && (leftConvertedType.SpecialType == SpecialType.System_String
|| rightConvertedType.SpecialType == SpecialType.System_String)) {
Expand Down Expand Up @@ -1935,6 +1946,9 @@ public override VisualBasicSyntaxNode VisitOmittedTypeArgument(CSSyntax.OmittedT

public override VisualBasicSyntaxNode VisitIdentifierName(CSSyntax.IdentifierNameSyntax node)
{
if (_semanticModel.GetNativeIntegerTypeOrNull(node) is { } nativeIntegerType) {
return _commonConversions.GetFullyQualifiedNameSyntax(nativeIntegerType, allowGlobalPrefix: false);
}
return WrapTypedNameIfNecessary(SyntaxFactory.IdentifierName(_commonConversions.ConvertIdentifier(node.Identifier)), node);
}

Expand Down
Loading
Loading