Repository navigation
VB -> C#: Use explicit array type unless every initializer item already has the target element type - #1331
Open
GrahamTheCoder wants to merge 43 commits into
Open
VB -> C#: Use explicit array type unless every initializer item already has the target element type#1331GrahamTheCoder wants to merge 43 commits into
GrahamTheCoder wants to merge 43 commits into
Conversation
…defined conversion Fixes icsharpcode#1211 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…hoosing explicit array type Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…dy has the target element type
Replaces the operation-based user-defined-conversion check with a type comparison, which also fixes Object() targets (e.g. {1, 2} previously gave a non-compiling int[]).
Document in CONTRIBUTING that type/symbol APIs are preferred over IOperation for performance.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…s back to their VB type
C# promotes byte/short operands of these operators to int, VB keeps the type, so e.g. Byte() = {b And b} produced a non-compiling int[].
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…the bitwise complement kind Not on Byte? gave the logical !, which doesn't compile. The numeric case also built a LogicalNotExpression node with a ~ token, so the syntax tree didn't mean what its text says (the harness reported CS0023 for it). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…here the consumer would see the C# int C# promotes Byte/SByte/Short/UShort operands to int, VB keeps the type. The analyzer only treated the result as int when checking the conversion to its target, so a widening target looked like identity: Dim i As Integer = Not b1 gave ~b1 (-201 rather than 55), b1 << 3 to Long wasn't truncated, b1 Or b2 to Object boxed an int, and a lambda returning b1 And b2 didn't compile. Nullable operands (Byte?) weren't handled at all. The cast is now added where the operator is converted, based on its consumer (SmallIntegerOperatorPromotion): - an operand of a wrapping operator of the same type needs none, since that operator's result is cast (no more (byte)((byte)(b1 & b2) & b2)); - a result that's already in range (e.g. And/Or/Xor of in-range operands, signed Not, Mod) needs none where an int means the same: an operand of another intrinsic operator (so (b1 And b2) = b1 has no cast), widening to Integer/Long/floating, String or Boolean; - anything else (the VB type itself, Object, enums...) gets the cast, unchecked for a constant that C# would reject. Changed expectation: ValueTupleConstructorBecomesTupleLiteral... Short s * s to an Integer element was s * s, which differs from VB once the product leaves Short's range; it's now (int)(short)(s * s) (the (int) keeps the tuple element type). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…pound The non-compound result type was taken from the shift count (always Integer), so b1 <<= 1 looked like it needed a cast and became b1 = (byte)(b1 << 1), and l <<= i became l = l << i. A shift's result has its left operand's type, and C# casts a compound shift's result back to it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…its of the shifted type VB masks the count with 7 for 8-bit and 15 for 16-bit types, C# masks it with 31 after promoting to int, so e.g. a Byte of 200 << 9 gave 0 rather than 144. A constant count is folded to its masked value and left as is when already in range. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ed operators returning one Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
Whether an operator needs a cast depends on whether its operands' values are in range, which depended on them again, twice per level, so a chain of 22 Mods took 47 s to convert. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…f C# would get it out of range (Not C1) * C2 + us on UShort left ~C1 to the wrapping parent's cast, but C# folds the constant -65535 * 40000 and rejects the overflow (CS0220). An out-of-range constant (only Not on an unsigned type and << can give one, since VB rejects any other constant overflow) is now cast unchecked where it is, and a constant with exact operands counts as in range, so (Not C1) * C2 to Integer needs no further cast. The simplifier kept every ancestor of a cast inside unchecked(...) unsimplified, leaving e.g. (int)(((unchecked((byte)~CB))) % b). That protection is only needed for the Roslyn bug with a cast literal (unchecked((int)0x80000010)), so it's now limited to that. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
VB converts it as a Return statement would, so Function() i as Func(Of Byte) (Option Strict Off) gave () => i, which doesn't compile. Multi-line lambdas already got the conversion through their Return statements. Expression trees are left alone: there, e.g. Object comparisons become C# operators that already give the return type, which the VB types don't show. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ed to another numeric type The consumer's type was the operand's own converted type, which for an explicit conversion (CByte, CInt, CType) is just its type, so CInt(b1 And b2) gave (byte)(b1 & b2) and CByte(s1 And s2) gave (byte)(short)(s1 & s2). The target of an explicit conversion now counts, and: - an in-range value converted to any other numeric type needs no cast back, since converting the int gives the same (CInt(b1 And b2) -> b1 & b2, Dim k As Short = b1 And b2 -> (short)(b1 & b2)); - any value converted to an integral type no wider than its VB type needs none either, since that conversion truncates it anyway (CByte(Not us) -> (byte)~us, Dim h As SByte = b1 And b2 -> (sbyte)(b1 & b2)). For those, the conversion to the target is told the source is an int again, as before this branch, so it adds the one cast. The docs now say which targets are accepted and why, and the unary minus case covers any operand of another type (e.g. Boolean), not just unsigned ones. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…gral constant count The binary shift took the mask from the left operand's converted type and the compound shift from the left operand's type, so a Byte enum's e << n was masked but e <<= 9 wasn't. Both now use the type that is shifted, an enum being shifted as its underlying type. A compound shift of an enum also shifts the underlying value now, since C# can't shift an enum (en <<= 9 gave en <<= 9, CS0019; 5347f29 gave en = (E)(en << 9), also CS0019). A constant count of any integral type is folded (b << 9L, b << Nine), and a count already masked by a constant And within range (n And 3) isn't masked again. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…) or an unformatted interpolation If(nb1 And nb2, 0) converts the value to the If's type (Integer), not the operand's own Byte?, so (byte?)(nb1 & nb2) ?? 0 cast for nothing. An interpolation boxes the value, but without a format string an in-range int formats the same; with one it may not (a negative SByte as :X), so that keeps the cast. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… small integer type back for the setter Since compound shifts take the shift's own type as the result type (c9aefb8), Q(1) <<= n on a Byte property gave set_Q(1, get_Q(1) << (n & 7)), which doesn't compile: a C# compound operator casts the promoted int back, a setter call doesn't (5347f29 gave set_Q(1, (byte)(get_Q(1) << n))). Q(1) += b had the same problem already at 5347f29. The setter's argument now converts from the type C# gives the operator, int. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…rries bits out of its type Every constant << was treated as possibly out of range, so Const K1 As Byte = CB1 << 1 got an unchecked cast, which the simplifier then reduced to a bare unchecked(CB1 << 1). The shift's C# value is now compared with VB's. Also: - a shift whose constant count is masked to 0 (1US << 16) is just its left operand; - an unchecked cast doesn't nest another unchecked inside it (unchecked((ushort)~(ushort)~1)). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…xpression trees too, but not a nested lambda The conversion added in 3f3e3e0 wrapped a nested lambda returned as a delegate in a delegate creation (() => new Func<int>(() => 1), was () => () => 1); C# infers the nested lambda's type from the return type, so it's left alone unless the return type isn't a delegate (e.g. Object). Expression trees were skipped entirely, leaving Expression(Of Func(Of Byte)) = Function() i as () => i (CS0266); only an Object comparison is skipped there now, since it becomes a C# comparison that already gives bool. Tests pin the body conversion for Object, async, String, enum, Decimal, Char, Date and Byte returns, expression trees, LINQ query operators, Queryable lambdas and anonymous type members. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…alue or to an enum no wider CByte(nb + nb) gave (byte)(byte?)(nb + nb) and CType(b1 And b2, EB) gave (EB)(byte)(b1 & b2) (5347f29: (byte)(nb + nb), (EB)(b1 & b2)). Converting a nullable to its value, or to an enum whose underlying type is no wider, truncates the int as the cast back would, so it now converts the int directly. A wider enum (CType(Not b, DayOfWeek)) still needs the cast back. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…o Long VB's Not converts a fractional operand to Long (rounding to even) first, C# has no ~ for it: Not d gave ~d and Not nd gave ~nd since 7f0284a (!nd before), neither compiles. The operand now gets its VB conversion, e.g. ~(long)Math.Round(d). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ger cast, and document named shift counts NeedsCastToVbType cached under the unparenthesized node but analyzed the node it was given; both give the same answer, now it's visibly the same node. The shift count docs say a named constant count out of range is folded to its masked value. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…onstants Merging every nested unchecked (7a93d4a) also unwrapped unchecked((int)0x80000010), whose cast nothing protected from the simplifier any more, so the literal became a uint and Not CByte((&H80000010 \ 3) And &HFF) gave 79 instead of 164. Only the unchecked contexts this conversion adds are merged now. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… to Boolean With Option Strict Off, rows.Where(Function(r) r = 5) gave r => Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(r, 5, false)) since 3f3e3e0, which LINQ providers can't translate. VB types an Object comparison (and Not, AndAlso, OrElse of one) as Object, but it converts to a C# expression that's already bool, in or out of an expression tree, so no conversion is added for it. And, Or and Xor of Objects still convert, since they become Operators.AndObject etc. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… integral type VB converts it at compile time, rounding to even, so Const L1 As Long = Not D, Optional x As Long = Not D and Case Not D are constants; (long)Math.Round(D) isn't (CS0133, CS1736, CS9135). A literal also came out with its fractional text and the target's suffix, e.g. Dim x As Long = 2.5 gave (long)Math.Round(2.5L), which doesn't compile (CS0121). Now ~2L and 2L. A calculated constant keeps its Math.Round form, so the calculation stays visible. Changed expectation: TestInferringImplicitGenericTypesAsync, CInt(1.0) etc. were (int)Math.Round(1.0d), now 1 (same value). System is no longer used there, so its unused Imports System is dropped from the input, since the comment checker can't find a home for its comment. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…left side with VB's conversion VB shifts Boolean as Short, and Single, Double, Decimal and String as Long (with Option Strict Off), but the compound shift took the left side's own type as the shift's, so bo <<= 1, d <<= 2 etc. stayed compound, which C# rejects (CS0019; 5347f29 gave d = (double)(d << 2), also CS0019). The left side is now converted to the type VB shifts it as, as for an enum before, and the count is masked for that type (bo <<= n masks with 15). Also, a constant shift of True counted True as 1 rather than VB's -1, so True << 3 got a needless unchecked. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…wider enum or switched on CType(b1 Or b2, ES) with a Short-based enum gave (ES)(byte)(b1 | b2), and Select Case b1 And b2 gave switch ((byte)(b1 & b2)) (5347f29: (ES)(b1 | b2), switch (b1 & b2)). An enum target now counts as its underlying numeric type, and each case compares with the value, which an in-range int has just the same. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…parison body check TypeOf is always Boolean in VB, so it never reaches the Object-typed body check. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… that constant 4e41f1d folded by the VB node's constant value, but a compound assignment converts all of `lhs op rhs` against its right operand, so i += 2.5 became i = 2 (VB 12), and Q(1) += 2.5 became set_Q(1, 2). The fold now also requires the C# node to be that literal or name. An array bound was converted after adding one, so the fold made Dim c(D) (D = 4.4) new int[4] rather than 5. VB converts the upper bound to Integer first, so that now happens before adding one; that also fixes Dim a(2.5), whose length was Round(3.5) = 4 rather than VB's 3, already at 5347f29. Changed expectation: ArgumentsAreTypeConvertedAsync, New Single(7 / someInt) {} was new float[(int)Math.Round(7d / someInt + 1)], now new float[(int)Math.Round(7d / someInt) + 1], which matches VB for a bound ending in .5. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…wn type For If(x, y), the If's type counted as the target, so for If(Not nb, CByte(0)) Byte? to Byte looked like a conversion that truncates, but C#'s ?? converts neither operand: ~nb ?? 0 gave -201 rather than 55, boxed an Int32, picked an Integer overload, and Dim v = If(nb And b2, CByte(0)) didn't compile (from 31a2517 and 8db00f9). A coalesced operand now only skips the cast where the If's type is another, wider type, e.g. If(nb And b2, 0) as Integer. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… late-bound Operators call VB binds such an operator at runtime, and C# has no compound operator for it: b <<= ob gave b <<= ob & 7 since 2e43dd0 (5347f29: b = Conversions.ToByte(b << ob)), o <<= 2 and o += 1 stayed as they were, and b += ob gave b = Conversions.ToByte(b + ob); none compiled. They now call Operators.LeftShiftObject, AddObject etc., as the plain binary operators already do, and convert the result back. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…ounds it to The count was folded to its rounded value, then masked again because a fractional constant wasn't recognised as already in range: b <<= 1.5 gave b <<= 2 & 7. b << 9.5 now masks VB's count of 10 to 2. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…type as constants VB converts them at compile time, but they were left unconverted, so Optional x As Integer = 1.5 gave int x = 1.5 and Optional y As Long = D gave long y = D (CS1750), Optional z As Short = True << 3 wasn't constant (CS1736), and an enum member A = 1.5 kept its fraction (all already at 5347f29). They now go through the same constant conversion as a Const declaration: 2, 2L, -8 and 2. A Nothing default stays C#'s default. Attribute arguments (<A(2.5, P:=3.5)>) still aren't converted at all; that's a separate conversion path. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… rewritten after conversion Is and IsNot are Boolean even on Objects, so the Object-typed body check never reaches them; the docs now say why AndAlso and OrElse are bool in C# whatever their operands. The unchecked merge and the narrowed simplifier guard rewrite generated C#, so their docs now say why that can't be done from the VB model, and what the guard protects. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…nt, so &= isn't an addition ad8024b chose it from the C# kind, which is += for both += and &=, so s &= o (Object o) became Operators.AddObject: "2" & 1 gave "3" instead of "21", and o &= "x" threw. &= keeps its conversion from 5347f29 again, as do /=, \= and ^=, whose C# kinds don't say which VB operator they were. The Mod arm is removed: VB has no Mod=. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…lue, leaving others as written 8a0d74a converted every default and enum member value as a Const initializer is, which folds a calculation or a reference to another member into a number: B = A + 1 became B = 2, Optional b As Byte = X + 1 became 6 (5347f29 kept them, and C# converts them implicitly). Only a fractional value converted to an integral type is converted now, since C# won't round it: Optional x As Integer = 1.5 gives 2, an enum member C = D (Const D As Double = 2.5) gives 2. So Optional z As Short = True << 3 is again not a C# constant (CS1736), as at 5347f29; the self-verifying default uses CB + 1 instead. The tests move to ParameterTests and NamespaceLevelTests, and pin that Nothing stays default and that a ByRef default goes through DefaultParameterValue. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… unchecked, instead of stripping nested ones afterwards An unchecked context covers everything inside it, so only the outermost promoted constant needs one. Asking the VB ancestors (which must themselves be constant) replaces annotating and rewriting already-built C#. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…bound right side Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…a parameterized property, to its Operators call With an Object operand, VB binds /=, \=, ^= and &= at runtime too: o &= 1, b &= o, e &= o and n &= o (Integer?) didn't compile, and dt &= "x" with an Object holding a Date gave dt += "x", which formats the whole DateTime. They now call DivideObject, IntDivideObject, ExponentObject (on the original right side, not the Math.Pow rewrite) and ConcatenateObject. A parameterized property's setter (c.set_Q(0, c.get_Q(0) + o), which didn't compile) now gets the converted late-bound result too. A self-verifying test runs every compound operator with an Object right side on Object, String, Byte, Short, Integer?, enum and Date left sides, comparing values and exceptions with VB's. The conversion test moves to CompoundAssignmentTests, and String &= Object is now ConcatenateObject rather than C#'s string + object, which formats e.g. a Date or Double as .NET does rather than as VB does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…e arguments to their declared type as C# constants VB converts these constants at compile time; C# needs a constant of the declared type and only converts implicitly. DeclaredConstantConverter keeps the value as written where C# converts it implicitly, casts it where C# has an explicit conversion (Optional a1 As Integer = L for a Long L -> (int)L, Optional n As Col = 1 -> (Col)1, enum K = L -> (int)L), and otherwise uses VB's converted value as a literal: a fractional value to an integral type (rounded to even, including for a nullable or enum target), a Boolean to a number, or a conversion that became a call (Optional z As Short = True << 3 -> -8, which was CS1736). Attribute arguments weren't converted at all (<A(2.5, P:=3.5)> -> [A(2, P = 4)]). [DefaultParameterValue] needs the parameter's exact type (Optional ByRef b As Short = 3 was CS1908, now (short)3). An Object parameter's non-Nothing default (CS1763) and a Date default use attributes, and since C# treats a parameter with them as required, the method's other defaults then do too (a Date default followed by other optionals was CS1737). Replaces RoundFractionalConstantIfNeeded. Nothing still becomes default, and a Char default for a String parameter and the DateTimeConstant path are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…heses around the bound go The upper bound plus one was built as a SubtractExpression node with a + token, so the simplifier, reading it as a subtraction, kept the parentheses around it: Dim a(bt + bt) gave new int[((byte)(bt + bt) + 1)]. It's an AddExpression now, with the bound parenthesized for the simplifier to unwrap where it can (which also covers the conditional expression the old code special-cased). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
…be redone with another left side Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
… once Where a compound assignment is split into lhs = lhs op rhs (a late-bound operator, a cast back, or a parameterized property's setter), C# evaluated the left side's receiver and arguments twice: arr(Idx()) += o called Idx() twice, GetH().F += 1 called GetH() twice, Q(Idx()) += 1 too (ins(Idx()) += 2.5 already at 5347f29). Any of them that may have side effects or be changed by the right side is now evaluated into a local first, in VB's order (receiver, arguments, then the right side); a structure variable receiver such as an array element is a ref local, so the assignment changes the original, as for With blocks. Left sides that evaluate the same twice (locals, parameters, Me, fields of those, constants and intrinsic operators on them) are unchanged, as are compound assignments C# keeps compound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes icsharpcode/CodeConverter#1211
There are two pieces of post-processing.
1. Merging nested
unchecked(new code)CodeConverter/CSharp/TypeConversionAnalyzer.cs:44-69:CastPromotedOperatorResultIfNeededandWithoutNestedPromotedConstantUnchecked.Why
uncheckedat all: C# constant-folds in checked mode. When a VB constant expression wraps around, the C# cast back to the small type is a compile error withoutunchecked. For example,Const B As Byte = Not Abecomes(byte)~A, which is CS0221.Why it rewrites C# already built: operators are converted innermost first, and the range decision is made per operator as each is converted. If two nested operators both need
unchecked, the inner one is already built when the outer one adds its own. The outer one then strips the inner wrapper, matching it by annotation so it only touches wrappers this code added. Without that you get output likeunchecked((byte)~unchecked((byte)(CB << 2))).Is it avoidable? Probably. The decision could be made from the VB model instead: skip
uncheckedon a node when an enclosing VB operator will add one. That is a check on the VB ancestors, which is exactly how the rest ofSmallIntegerOperatorPromotionalready decides where casts go. It would remove the annotation and the rewrite. I'd do this if you want it gone.2. Narrowing a simplifier guard (changed existing code)
CodeConverter/Common/DocumentExtensions.cs:56-62:CsWouldBeSimplifiedIncorrectly.What it was: Roslyn's simplifier turns
unchecked((int)0x80000010)intounchecked(0x80000010), which makes the literal auint(CS0266, or silently unsigned arithmetic). The guard stopped that by marking every cast directly insideunchecked, plus all its ancestors, as "do not simplify".Why it changed: the new code puts casts of whole expressions inside
unchecked. The broad guard then froze the cast and every ancestor, so nothing around it was simplified and redundant parentheses were left:(int)(((unchecked((byte)~CB))) % b). The guard now only protects a cast whose operand is a literal, which is the only shape the Roslyn bug affects.Risk: this was the source of review round 6's silent wrong-value bug. Fixing it (keeping
uncheckedwrappers this code didn't add) is part of why piece 1 matches by annotation. A self-verifying test now covers negative hex literals inside these constants.The simplifier pass itself predates this branch. The new code only changes which nodes it may touch.
Title: VB -> C#: Use explicit array element type where items need converting; keep Byte/Short operator results typed
Fixes #1211
Summary
The issue (first commit,
5347f29). VB converts each array initializer item to the target element type, but C#new[] { ... }infers its type from the items alone.MyMethod({"foo", "bar"})withMyMethod(keys As Key())and a widening operator fromStringtoKeyproduced astring[], which fails with CS1503.InitializerConverternow usesnew[]only when every item's own type equals the target element type, checking nested initializers recursively. Otherwise it emitsnew Key[] { "foo", "bar" }.This also fixes
Object()targets:{1, 2}gave anint[](CS0029).{1, "a"}gave CS0826.{"a", "b"}gave astring[]that throwsArrayTypeMismatchExceptionon writes.The check uses
GetTypeInfo, andCONTRIBUTING.mdnow says to prefer type and symbol APIs over the slowerGetOperation.Byte/Short operators (the rest of the branch). The rule above showed that VB keeps
Byte/SByte/Short/UShortas the result type of arithmetic, bitwise, shift and unary operators, while C# promotes them toint. So{b1 And b2}for aByte()target was a non-compilingint[].The new class
CodeConverter/CSharp/SmallIntegerOperatorPromotion.csdecides from the VB model where a result must be cast back to its VB type:Object, enums, lambda returns, nullable operands, and widening toInteger/Long/Stringwhen the int value would differ.CByte/CInt,Select Case, or an unformatted interpolation.Related fixes it needed:
Not: works on nullable operands, and onDouble/Single/Decimaloperands, which VB converts toLongfirst.uncheckedonly where needed. Fractional constants are folded to VB's banker's-rounded value in place ofMath.Roundcalls: in conversions, enum members, parameter defaults, shift counts and array bounds. A bound is rounded before+ 1.If(x, y): a coalesced small-type result is cast when the If's type is the small type.+=,-=,*=,<<=and>>=with anObjectoperand useOperators.*Object.For the reviewer
5347f29alone fixes VB -> C#: Collection Initializers/Collection Expressions #1211, and the Byte/Short work can be split into its own PR if you prefer.CONTRIBUTING.mdadvice (reasons in the XML docs):TypeConversionAnalyzer.WithoutNestedPromotedConstantUncheckedmerges nesteduncheckedwrappers that this code added. It could be replaced by deciding from the VB ancestors instead.DocumentExtensions.CsWouldBeSimplifiedIncorrectlynow protects only casts of literals insideunchecked. That is the shape of the Roslyn bug whereunchecked((int)0x80000010)loses its cast. The old, broader guard left redundant parentheses around the new casts.object[] o = new object[] { "a" }(ArrayStatementTests)Action[] actions = new Action[] { … }(ExpressionTests)new List<object>(new object[] { … })(ByRefTests)(int)(short)(s * s)in a ValueTuple testnew float[(int)Math.Round(7d / someInt) + 1](ArgumentsAreTypeConvertedAsync): it used to round after adding one, which differs from VB at .5.CInt(1.0)and similar are now1/1U/1L/1UL(TypeCastTests). That test's VB input dropped an unusedImports System, so the comment check still passes./=,\=and^=withObjectoperands, andObjectoperands on parameterized properties.arr(Idx()) += oevaluatesIdx()twice.Optional h As Integer? = 2.5,Optional ByRef b As Short = 3(CS1908), andOptional z As Short = True << 3.Optional a1 As Integer = Lwith aLongconstant, or enumK = L. A plain(int)Lcast would fix them.Optional ls As Long? = Dgives2.5dwhere it used to giveD.new int[((byte)(bt + bt) + 1)].Tests
SmallIntegerOperatorTests.cs, plus additions toExpressionTests,LambdaTests,ParameterTestsandNamespaceLevelTests885708d, where only three unreachable default switch arms were uncovered. I haven't measured it since.🤖 Generated with Claude Code
https://claude.ai/code/session_019FEr8GPdfYksbKK8p9JBrL