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 9 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
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ internal bool AddLabel(BoundPatternSwitchLabel label, DiagnosticBag diagnostics,
// For purposes of subsumption, we do not take into consideration the value
// of the input expression. Therefore we consider null possible if the type permits.
Syntax = label.Syntax;
var subsumedErrorCode = CheckSubsumed(label.Pattern, _subsumptionTree, inputCouldBeNull: true);
var inputCouldBeNull = _subsumptionTree.Type.CanContainNull();
var subsumedErrorCode = CheckSubsumed(label.Pattern, _subsumptionTree, inputCouldBeNull: inputCouldBeNull);
if (subsumedErrorCode != 0 && subsumedErrorCode != ErrorCode.ERR_NoImplicitConvCast)
{
if (!label.HasErrors)
Expand Down
4 changes: 1 addition & 3 deletions src/Compilers/CSharp/Portable/BoundTree/DecisionTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public static DecisionTree Create(BoundExpression expression, TypeSymbol type, S
expression = new BoundLocal(expression.Syntax, temp, null, type);
}

if (expression.Type.CanContainNull())
if (type.CanContainNull() || type.SpecialType == SpecialType.None)
{
// We need the ByType decision tree to separate null from non-null values.
// Note that, for the purpose of the decision tree (and subsumption), we
Expand All @@ -104,8 +104,6 @@ public static DecisionTree Create(BoundExpression expression, TypeSymbol type, S
else
{
// If it is a (e.g. builtin) value type, we can switch on its (constant) values.
// If it isn't a builtin, in practice we will only use the Default part of the
// ByValue.
return new ByValue(expression, type, temp);
}
}
Expand Down
31 changes: 20 additions & 11 deletions src/Compilers/CSharp/Portable/BoundTree/DecisionTreeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ private DecisionTree AddByValue(DecisionTree.Guarded guarded, BoundConstantPatte

private DecisionTree AddByValue(DecisionTree.ByValue byValue, BoundConstantPattern value, DecisionMaker makeDecision)
{
Debug.Assert(value.Value.Type == byValue.Type);
Debug.Assert(value.Value.Type.Equals(byValue.Type, TypeCompareKind.IgnoreDynamicAndTupleNames));
if (byValue.Default != null)
{
return AddByValue(byValue.Default, value, makeDecision);
Expand Down Expand Up @@ -221,7 +221,7 @@ private DecisionTree AddByValue(DecisionTree.ByType byType, BoundConstantPattern
var kvp = byType.TypeAndDecision[i];
var matchedType = kvp.Key;
var decision = kvp.Value;
if (matchedType.TupleUnderlyingTypeOrSelf() == value.Value.Type.TupleUnderlyingTypeOrSelf())
if (matchedType.Equals(value.Value.Type, TypeCompareKind.IgnoreDynamicAndTupleNames))
Copy link
Member

Choose a reason for hiding this comment

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

Please add tests that ignore dynamic.

Copy link
Member Author

Choose a reason for hiding this comment

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

I can't think of a way to make that happen. The is no constant pattern whose type is generic. This could probably be simplified to (matchedType == value.Value.Type).

Copy link
Member Author

Choose a reason for hiding this comment

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

Oh, I know a way to make it happen. An enum type nested in a generic class.

{
forType = decision;
break;
Expand Down Expand Up @@ -260,21 +260,30 @@ private DecisionTree AddByType(DecisionTree decision, TypeSymbol type, DecisionM
case DecisionTree.DecisionKind.ByValue:
{
var byValue = (DecisionTree.ByValue)decision;
DecisionTree result;
if (byValue.Default == null)
{
byValue.Default = makeDecision(byValue.Expression, byValue.Type);
if (byValue.Default.MatchIsComplete)
if (byValue.Type.Equals(type, TypeCompareKind.IgnoreDynamicAndTupleNames))
{
byValue.MatchIsComplete = true;
result = byValue.Default = makeDecision(byValue.Expression, byValue.Type);
}
else
{
byValue.Default = new DecisionTree.ByType(byValue.Expression, byValue.Type, null);
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a bug fix to insert a needed conversion.

result = AddByType(byValue.Default, type, makeDecision);
}

return byValue.Default;
}
else
{
Debug.Assert(byValue.Default.Type == type);
return Add(byValue.Default, makeDecision);
result = AddByType(byValue.Default, type, makeDecision);
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a bug fix to insert a needed conversion.

}

if (byValue.Default.MatchIsComplete)
{
byValue.MatchIsComplete = true;
}

return result;
}
case DecisionTree.DecisionKind.Guarded:
return AddByType((DecisionTree.Guarded)decision, type, makeDecision);
Expand Down Expand Up @@ -321,7 +330,7 @@ private DecisionTree AddByType(DecisionTree.ByType byType, TypeSymbol type, Deci
if (byType.TypeAndDecision.Count != 0)
{
var lastTypeAndDecision = byType.TypeAndDecision.Last();
if (lastTypeAndDecision.Key.TupleUnderlyingTypeOrSelf() == type.TupleUnderlyingTypeOrSelf())
if (lastTypeAndDecision.Key.Equals(type, TypeCompareKind.IgnoreDynamicAndTupleNames))
{
result = Add(lastTypeAndDecision.Value, makeDecision);
}
Expand Down Expand Up @@ -533,7 +542,7 @@ private DecisionTree Add(DecisionTree.ByType byType, DecisionMaker makeDecision)
TypeSymbol patternType,
ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
if (expressionType == patternType)
if ((object)expressionType == (object)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 @@ -4891,7 +4891,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 @@ -5070,4 +5070,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 @@ -177,7 +177,7 @@ private DecisionTree LowerToDecisionTree(
}
}

if (defaultLabel != null)
if (defaultLabel != null && !loweredDecisionTree.MatchIsComplete)
{
Add(loweredDecisionTree, (e, t) => new DecisionTree.Guarded(loweredExpression, loweredExpression.Type, default(ImmutableArray<KeyValuePair<BoundExpression, BoundExpression>>), defaultSection, null, defaultLabel));
}
Expand Down Expand Up @@ -219,7 +219,8 @@ private void LowerDecisionTree(BoundExpression expression, DecisionTree decision
// Store the input expression into a temp
if (decisionTree.Expression != expression)
{
_loweredDecisionTree.Add(_factory.Assignment(decisionTree.Expression, expression));
var convertedExpression = _factory.Convert(decisionTree.Expression.Type, expression);
_loweredDecisionTree.Add(_factory.Assignment(decisionTree.Expression, convertedExpression));
}

if (_declaredTempSet.Add(decisionTree.Temp))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
using System.Collections.Immutable;
using System.Collections.Generic;

namespace Microsoft.CodeAnalysis.CSharp
{
Expand Down Expand Up @@ -80,7 +81,7 @@ private BoundExpression MakeIsDeclarationPattern(BoundDeclarationPattern lowered
return result;
}

Debug.Assert((object)loweredPattern.Variable != null && loweredInput.Type == loweredPattern.Variable.GetTypeOrReturnType());
Debug.Assert((object)loweredPattern.Variable != null && loweredInput.Type.Equals(loweredPattern.Variable.GetTypeOrReturnType(), TypeCompareKind.IgnoreDynamicAndTupleNames));

var assignment = _factory.AssignmentExpression(loweredPattern.VariableAccess, loweredInput);
return _factory.MakeSequence(assignment, result);
Expand All @@ -93,10 +94,10 @@ private BoundExpression MakeIsDeclarationPattern(BoundDeclarationPattern lowered

return _factory.Sequence(ImmutableArray.Create(temp),
sideEffects: ImmutableArray<BoundExpression>.Empty,
result: MakeIsDeclarationPattern(loweredPattern.Syntax, loweredInput, discard, requiresNullTest: true));
result: MakeIsDeclarationPattern(loweredPattern.Syntax, loweredInput, discard, requiresNullTest: loweredInput.Type.CanContainNull()));
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a bug fix to remove an unneeded null check.

}

return MakeIsDeclarationPattern(loweredPattern.Syntax, loweredInput, loweredPattern.VariableAccess, requiresNullTest: true);
return MakeIsDeclarationPattern(loweredPattern.Syntax, loweredInput, loweredPattern.VariableAccess, requiresNullTest: loweredInput.Type.CanContainNull());
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a bug fix to remove an unneeded null check.

}

/// <summary>
Expand Down Expand Up @@ -141,13 +142,36 @@ private BoundExpression CompareWithConstant(BoundExpression input, BoundExpressi
);
}

private bool MatchIsIrrefutable(TypeSymbol sourceType, TypeSymbol targetType, bool requiredNullTest)
{
// use site diagnostics will already have been reported during binding.
HashSet<DiagnosticInfo> ignoredDiagnostics = null;
switch (_compilation.Conversions.ClassifyBuiltInConversion(sourceType, targetType, ref ignoredDiagnostics).Kind)
{
case ConversionKind.Boxing:
case ConversionKind.ImplicitReference:
case ConversionKind.Identity:
return true;
default:
return false;
}
}

BoundExpression MakeIsDeclarationPattern(SyntaxNode syntax, BoundExpression loweredInput, BoundExpression loweredTarget, bool requiresNullTest)
{
var type = loweredTarget.Type;
requiresNullTest = requiresNullTest && !loweredInput.Type.CanContainNull();

// 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 (or perform the null test).
if (MatchIsIrrefutable(loweredInput.Type, loweredTarget.Type, requiresNullTest))
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a bug fix to remove an unneeded type test.

{
var convertedInput = _factory.Convert(loweredTarget.Type, loweredInput);
var assignment = _factory.AssignmentExpression(loweredTarget, convertedInput);
return requiresNullTest
? _factory.ObjectNotEqual(assignment, _factory.Null(type))
: _factory.MakeSequence(assignment, _factory.Literal(true));
}

// a pattern match of the form "expression is Type identifier" is equivalent to
// an invocation of one of these helpers:
Expand All @@ -158,31 +182,15 @@ BoundExpression MakeIsDeclarationPattern(SyntaxNode syntax, BoundExpression lowe
// t = e as T;
// return t != null;
// }
if (loweredInput.Type == type)
{
// CONSIDER: this can be done whenever input.Type is a subtype of type for improved code
var assignment = _factory.AssignmentExpression(loweredTarget, loweredInput);
return requiresNullTest
? _factory.ObjectNotEqual(assignment, _factory.Null(type))
: _factory.MakeSequence(assignment, _factory.Literal(true));
}
else
{
return _factory.ObjectNotEqual(
_factory.AssignmentExpression(loweredTarget, _factory.As(loweredInput, type)),
_factory.Null(type));
}
return _factory.ObjectNotEqual(
_factory.AssignmentExpression(loweredTarget, _factory.As(loweredInput, type)),
_factory.Null(type));
}
else if (type.IsValueType)
{
// 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.
if (loweredInput.Type == type)
{
return _factory.MakeSequence(
_factory.AssignmentExpression(loweredTarget, loweredInput),
_factory.Literal(true));
}
// 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 may be possible to improve this code by only assigning t when returning
// true (avoid returning a new default value)
Expand All @@ -207,18 +215,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
Loading