Roslyn: Parser Bug

Created on 8 Mar 2017  路  6Comments  路  Source: dotnet/roslyn

Version Used:

Steps to Reproduce:

After upgrading to VS 2017 I got the following error from this code (which has always been working perfectly)

byte[] HexStringToByteArray(string hex)
{
if (hex.Length % 2 == 1)
throw new Exception("The binary key cannot have an odd number of digits");

    byte[] arr = new byte[hex.Length >> 1];

    for (int i = 0; i < hex.Length >> 1; ++i) // Error in this line
    {
        arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
    }

    return arr;
}

Exception:

Error 1: The variable 'i' cannot be used with type arguments
Error 2: 'hex' is a variable but is used like a type
the solution was to surround the expression by parentheses.

for (int i = 0; i < (hex.Length >> 1); ++i)

Expected Behavior:

Actual Behavior:

Area-Compilers Resolution-Fixed

Most helpful comment

Pasting that code into VS2017 gives a clue as to what's going on. It reformats the "error" line to:

for (int i = 0; i<hex.Length> > 1; ++i)

in other words, Roslyn v2 is parsing i<hex.Length>>1 as a generic type being tested as greater than 1.

All 6 comments

Pasting that code into VS2017 gives a clue as to what's going on. It reformats the "error" line to:

for (int i = 0; i<hex.Length> > 1; ++i)

in other words, Roslyn v2 is parsing i<hex.Length>>1 as a generic type being tested as greater than 1.

This works on master: http://tryroslyn.azurewebsites.net/#b:master/K4Zwlgdg5gBAygTxAFwKYFsDcBYAUAB2ACMAbMAYxnJIEMQQYBhGAbzxg5gDcB7MAExgBZABSRkAbQC6MABaoAHgEpWedpwBmPAE4wxEZDDAwAvDAAMmIzAA8cxQDoAMqmjJZMAHyeYARisA1AFgKgD0oTAAotraOkYQMO5gDGQQqOocbLicMAC+MBl5ari5QA==

This was probably fixed by #16834

(for those following along at home, this originated from a StackOverflow question)

This is fixed by #16834.

See also #17135, #17296

Was this page helpful?
0 / 5 - 0 ratings