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

Relax conversion requirements for pattern-matching involving type parameters. #18784

Merged
merged 13 commits into from
May 8, 2017
Merged
Show file tree
Hide file tree
Changes from 5 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
22 changes: 20 additions & 2 deletions src/Compilers/CSharp/Portable/Binder/Binder_Patterns.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,26 @@ private bool CheckValidPatternType(
//case ConversionKind.ImplicitConstant:
//case ConversionKind.ImplicitNumeric:
default:
Error(diagnostics, ErrorCode.ERR_PatternWrongType, typeSyntax, operandType, patternType);
return true;
if (operandType.ContainsTypeParameter() || patternType.ContainsTypeParameter())
{
LanguageVersion requiredVersion = MessageID.IDS_FeatureGenericPatternMatching.RequiredVersion();
if (requiredVersion > Compilation.LanguageVersion)
{
Error(diagnostics, ErrorCode.ERR_PatternWrongGenericTypeInVersion, typeSyntax,
operandType, patternType,
Compilation.LanguageVersion.ToDisplayString(),
new CSharpRequiredLanguageVersion(requiredVersion));
return true;
}

// permit pattern-matching when one of the types is an open type in C# 7.1.
break;
}
else
{
Error(diagnostics, ErrorCode.ERR_PatternWrongType, typeSyntax, operandType, patternType);
return true;
}
}
}

Expand Down
11 changes: 10 additions & 1 deletion src/Compilers/CSharp/Portable/CSharpResources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion src/Compilers/CSharp/Portable/CSharpResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -4892,7 +4892,7 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ
<value>The switch case has already been handled by a previous case.</value>
</data>
<data name="ERR_PatternWrongType" xml:space="preserve">
<value>An expression of type {0} cannot be handled by a pattern of type {1}.</value>
<value>An expression of type '{0}' cannot be handled by a pattern of type '{1}'.</value>
</data>
<data name="WRN_AttributeIgnoredWhenPublicSigning" xml:space="preserve">
<value>Attribute '{0}' is ignored when public signing is specified.</value>
Expand Down Expand Up @@ -5071,4 +5071,7 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ
<data name="ERR_VoidInTuple" xml:space="preserve">
<value>A tuple may not contain a value of type 'void'.</value>
</data>
<data name="ERR_PatternWrongGenericTypeInVersion" xml:space="preserve">
<value>An expression of type '{0}' cannot be handled by a pattern of type '{1}' in C# {2}. Please use language version {3} or greater.</value>
</data>
</root>
5 changes: 5 additions & 0 deletions src/Compilers/CSharp/Portable/Errors/ErrorCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1476,8 +1476,13 @@ internal enum ErrorCode
WRN_Experimental = 8305,
ERR_TupleInferredNamesNotAvailable = 8306,

#region diagnostics for C# 7.1

ERR_BadDynamicMethodArgDefaultLiteral = 9000,
ERR_DefaultLiteralNotValid = 9001,
WRN_DefaultInSwitch = 9002,
ERR_PatternWrongGenericTypeInVersion = 9003,

#endregion diagnostics for C# 7.1
}
}
2 changes: 2 additions & 0 deletions src/Compilers/CSharp/Portable/Errors/MessageID.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ internal enum MessageID
IDS_ThrowExpression = MessageBase + 12717,
IDS_FeatureDefaultLiteral = MessageBase + 12718,
IDS_FeatureInferredTupleNames = MessageBase + 12719,
IDS_FeatureGenericPatternMatching = MessageBase + 12720,
}

// Message IDs may refer to strings that need to be localized.
Expand Down Expand Up @@ -188,6 +189,7 @@ internal static LanguageVersion RequiredVersion(this MessageID feature)
// C# 7.1 features.
case MessageID.IDS_FeatureDefaultLiteral:
case MessageID.IDS_FeatureInferredTupleNames:
case MessageID.IDS_FeatureGenericPatternMatching:
return LanguageVersion.CSharp7_1;

// C# 7 features.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,6 @@ BoundExpression MakeIsDeclarationPattern(SyntaxNode syntax, BoundExpression lowe
{
var type = loweredTarget.Type;

// The type here is not a Nullable<T> instance type, as that would have led to the semantic error:
// ERR_PatternNullableType: It is not legal to use nullable type '{0}' in a pattern; use the underlying type '{1}' instead.
Debug.Assert(!type.IsNullableType());

// a pattern match of the form "expression is Type identifier" is equivalent to
// an invocation of one of these helpers:
if (type.IsReferenceType)
Expand All @@ -175,8 +171,13 @@ BoundExpression MakeIsDeclarationPattern(SyntaxNode syntax, BoundExpression lowe
}
else if (type.IsValueType)
{
// The type here is not a Nullable<T> instance type, as that would have led to the semantic error:
// ERR_PatternNullableType: It is not legal to use nullable type '{0}' in a pattern; use the underlying type '{1}' instead.
Debug.Assert(!type.IsNullableType());

// It is possible that the input value is already of the correct type, in which case the pattern
// is irrefutable, and we can just do the assignment and return true.
// is irrefutable (there is no way for a non-nullable value type to be null), and we can just do
// the assignment and return true.
if (loweredInput.Type == type)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This type comparison should ignore dynamic/tuple/modopt differences

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Essentially if there is an identity conversion, then match is irrefutable.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That may be true (the suggested change would be a code improvement), but it is not relevant to the change in the PR.

{
return _factory.MakeSequence(
Expand Down Expand Up @@ -207,18 +208,26 @@ BoundExpression MakeIsDeclarationPattern(SyntaxNode syntax, BoundExpression lowe
Debug.Assert(type.IsTypeParameter());
// bool Is<T>(this object i, out T o)
// {
// // inefficient because it performs the type test twice.
// // inefficient because it performs the type test twice, and also because it boxes the input.
// bool s = i is T;
// if (s) o = (T)i;
// o = s ? (T)i : default(T);
// return s;
// }
return _factory.Conditional(_factory.Is(loweredInput, type),
_factory.MakeSequence(_factory.AssignmentExpression(
loweredTarget,
_factory.Convert(type, loweredInput)),
_factory.Literal(true)),
_factory.Literal(false),
_factory.SpecialType(SpecialType.System_Boolean));

// Because a cast involving a type parameter is not necessarily a valid conversion (or, if it is, it might not
// be of a kind appropriate for pattern-matching), we use `object` as an intermediate type for the input expression.
var tmpType = _factory.SpecialType(SpecialType.System_Object);
var s = _factory.SynthesizedLocal(_factory.SpecialType(SpecialType.System_Boolean), syntax);
var i = _factory.SynthesizedLocal(tmpType, syntax); // we copy the input to avoid double evaluation
return _factory.Sequence(
ImmutableArray.Create(s, i),
ImmutableArray.Create<BoundExpression>(
_factory.AssignmentExpression(_factory.Local(i), _factory.Convert(tmpType, loweredInput)),
_factory.AssignmentExpression(_factory.Local(s), _factory.Is(_factory.Local(i), type)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should have some tests that validate IL, just to be sure how this is emitted.

_factory.AssignmentExpression(loweredTarget, _factory.Conditional(_factory.Local(s), _factory.Convert(type, _factory.Local(i)), _factory.Default(type), type))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_factory.Local(s) [](start = 90, length = 17)

Can we inline the assignment to s here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. But it made no difference in any generated code.

),
_factory.Local(s)
);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1104,6 +1104,7 @@ public BoundExpression Convert(TypeSymbol type, BoundExpression arg)
{
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion c = Compilation.Conversions.ClassifyConversionFromExpression(arg, type, ref useSiteDiagnostics);
Debug.Assert(c.Exists);
Debug.Assert(useSiteDiagnostics.IsNullOrEmpty());

// If this happens, we should probably check if the method has ObsoleteAttribute.
Expand Down
Loading