Roslyn-analyzers: New rule: Interpolated strings that are missing the $ special character

Created on 15 Aug 2019  路  6Comments  路  Source: dotnet/roslyn-analyzers

It'd be great if the correctness analyzers included a rule that analyzed strings to detect cases where an interpolated string was intended but the $ character was erroneously left off. You can see some examples of this in corefx here:
https://github.com/dotnet/corefx/pull/40322

There are probably a wide variety of heuristics that could be used, but I'm imagining something like looking at strings in a context where interpolation could be used, and if it contains matching and non-nested {,} pairs, then if it could be compiles successfully with $ (or maybe if everything inside the {,} is a valid expression and can be bound), the rule triggers.

Approved-Rule Area-Microsoft.CodeQuality.Analyzers Feature Request help wanted

Most helpful comment

Tagging @dotnet/roslyn-analysis. Looks like a good rule to me.

One possible analyzer implementation would try to find string literals with at least one { and '}' characters within it, then create a speculative semantic model with a $ character appended to it and check if it leads to an interpolated string with at least one non-literal part AND each of the expressions within all non-literal parts bind correctly.

All 6 comments

Tagging @dotnet/roslyn-analysis. Looks like a good rule to me.

One possible analyzer implementation would try to find string literals with at least one { and '}' characters within it, then create a speculative semantic model with a $ character appended to it and check if it leads to an interpolated string with at least one non-literal part AND each of the expressions within all non-literal parts bind correctly.

Although I would love having such an analyzer, it might cause issues with Serilog which can鈥檛 use interpolated strings, but use the same syntax...

Need to be careful _not_ to fire this rule for arguments to string.Format. @stephentoub I'm concerned that the potential rate of false positives for format strings may change how we approach this. My initial suggestion is exclude cases where all of the interpolation expressions are non-negative integer literals.

@stephentoub @sharwell Should the analyzer trigger for the following?

private string M(int x)
{
    return "X: {y}";
}

Or only for something like:

private string M(int x)
{
    return "X: {x}";
}

I assume it should be the second to reduce false positives.

My initial suggestion is exclude cases where all of the interpolation expressions are non-negative integer literals

Makes sense to me. That is very unlikely to create false negatives for common cases.

Should the analyzer trigger for the following?

Assuming there's no field or property named y, I'd expect it to only fire for the second case.

I'll give a try to implement this soon.

Was this page helpful?
0 / 5 - 0 ratings