SyntaxGeneratorExtensions_CreateEqualsMethod.cs 17.5 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2

3
using System;
4
using System.Collections.Immutable;
P
Pilchie 已提交
5 6 7 8
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
9
using Microsoft.CodeAnalysis.Editing;
T
Tomas Matousek 已提交
10
using Microsoft.CodeAnalysis.PooledObjects;
P
Pilchie 已提交
11 12 13 14 15
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
16
    internal static partial class SyntaxGeneratorExtensions
P
Pilchie 已提交
17 18 19 20
    {
        private const string EqualsName = "Equals";
        private const string DefaultName = "Default";
        private const string ObjName = "obj";
21
        public const string OtherName = "other";
P
Pilchie 已提交
22 23

        public static IMethodSymbol CreateEqualsMethod(
24
            this SyntaxGenerator factory,
P
Pilchie 已提交
25
            Compilation compilation,
26
            ParseOptions parseOptions,
P
Pilchie 已提交
27
            INamedTypeSymbol containingType,
D
dotnet-bot 已提交
28
            ImmutableArray<ISymbol> symbols,
29
            string localNameOpt,
30
            SyntaxAnnotation statementAnnotation,
P
Pilchie 已提交
31 32
            CancellationToken cancellationToken)
        {
33
            var statements = CreateEqualsMethodStatements(
34
                factory, compilation, parseOptions, containingType, symbols, localNameOpt, cancellationToken);
35
            statements = statements.SelectAsArray(s => s.WithAdditionalAnnotations(statementAnnotation));
P
Pilchie 已提交
36

37 38 39 40 41
            return CreateEqualsMethod(compilation, statements);
        }

        public static IMethodSymbol CreateEqualsMethod(this Compilation compilation, ImmutableArray<SyntaxNode> statements)
        {
P
Pilchie 已提交
42
            return CodeGenerationSymbolFactory.CreateMethodSymbol(
C
CyrusNajmabadi 已提交
43
                attributes: default,
P
Pilchie 已提交
44
                accessibility: Accessibility.Public,
45
                modifiers: new DeclarationModifiers(isOverride: true),
P
Pilchie 已提交
46
                returnType: compilation.GetSpecialType(SpecialType.System_Boolean),
47
                refKind: RefKind.None,
48
                explicitInterfaceImplementations: default,
P
Pilchie 已提交
49
                name: EqualsName,
C
CyrusNajmabadi 已提交
50
                typeParameters: default,
C
CyrusNajmabadi 已提交
51
                parameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(compilation.GetSpecialType(SpecialType.System_Object), ObjName)),
P
Pilchie 已提交
52 53 54
                statements: statements);
        }

55 56 57 58 59 60 61 62 63 64 65 66
        public static IMethodSymbol CreateIEqutableEqualsMethod(
            this SyntaxGenerator factory,
            Compilation compilation,
            INamedTypeSymbol containingType,
            ImmutableArray<ISymbol> symbols,
            SyntaxAnnotation statementAnnotation,
            CancellationToken cancellationToken)
        {
            var statements = CreateIEquatableEqualsMethodStatements(
                factory, compilation, containingType, symbols, cancellationToken);
            statements = statements.SelectAsArray(s => s.WithAdditionalAnnotations(statementAnnotation));

67 68 69 70 71 72 73 74 75 76 77
            var equatableType = compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName);
            var constructed = equatableType.Construct(containingType);
            var methodSymbol = constructed.GetMembers(EqualsName)
                                          .OfType<IMethodSymbol>()
                                          .Single(m => containingType.Equals(m.Parameters.FirstOrDefault()?.Type));

            if (factory.RequiresExplicitImplementationForInterfaceMembers)
            {
                return CodeGenerationSymbolFactory.CreateMethodSymbol(
                    methodSymbol,
                    modifiers: new DeclarationModifiers(),
78
                    explicitInterfaceImplementations: ImmutableArray.Create(methodSymbol),
79 80 81 82 83 84 85 86 87
                    statements: statements);
            }
            else
            {
                return CodeGenerationSymbolFactory.CreateMethodSymbol(
                    methodSymbol,
                    modifiers: new DeclarationModifiers(),
                    statements: statements);
            }
88 89
        }

90
        private static ImmutableArray<SyntaxNode> CreateEqualsMethodStatements(
91
            SyntaxGenerator factory,
P
Pilchie 已提交
92
            Compilation compilation,
93
            ParseOptions parseOptions,
P
Pilchie 已提交
94
            INamedTypeSymbol containingType,
95
            ImmutableArray<ISymbol> members,
96
            string localNameOpt,
P
Pilchie 已提交
97 98
            CancellationToken cancellationToken)
        {
99
            var statements = ArrayBuilder<SyntaxNode>.GetInstance();
P
Pilchie 已提交
100

C
CyrusNajmabadi 已提交
101 102 103 104 105
            // Come up with a good name for the local variable we're going to compare against.
            // For example, if the class name is "CustomerOrder" then we'll generate:
            //
            //      var order = obj as CustomerOrder;

106
            var localName = localNameOpt ?? GetLocalName(containingType);
P
Pilchie 已提交
107

108 109
            var localNameExpression = factory.IdentifierName(localName);
            var objNameExpression = factory.IdentifierName(ObjName);
P
Pilchie 已提交
110

C
CyrusNajmabadi 已提交
111 112
            // These will be all the expressions that we'll '&&' together inside the final
            // return statement of 'Equals'.
113
            var expressions = ArrayBuilder<SyntaxNode>.GetInstance();
P
Pilchie 已提交
114

115 116 117 118 119 120 121 122
            if (factory.SupportsPatterns(parseOptions))
            {
                // If we support patterns then we can do "return obj is MyType myType && ..."
                expressions.Add(
                    factory.IsPatternExpression(objNameExpression,
                        factory.DeclarationPattern(containingType, localName)));
            }
            else if (containingType.IsValueType)
P
Pilchie 已提交
123
            {
C
CyrusNajmabadi 已提交
124 125 126 127 128 129 130
                // If we're a value type, then we need an is-check first to make sure
                // the object is our type:
                //
                //      if (!(obj is MyType))
                //      {
                //          return false;
                //      }
131 132
                var ifStatement = factory.IfStatement(
                    factory.LogicalNotExpression(
M
mattwar 已提交
133
                        factory.IsTypeExpression(
P
Pilchie 已提交
134 135
                            objNameExpression,
                            containingType)),
136
                    new[] { factory.ReturnStatement(factory.FalseLiteralExpression()) });
P
Pilchie 已提交
137

C
CyrusNajmabadi 已提交
138 139 140 141
                // Next, we cast the argument to our type:
                //
                //      var myType = (MyType)obj;

142
                var localDeclaration = factory.LocalDeclarationStatement(localName, factory.CastExpression(containingType, objNameExpression));
P
Pilchie 已提交
143 144 145 146 147 148

                statements.Add(ifStatement);
                statements.Add(localDeclaration);
            }
            else
            {
C
CyrusNajmabadi 已提交
149 150 151 152
                // It's not a value type, we can just use "as" to test the parameter is the right type:
                //
                //      var myType = obj as MyType;

M
mattwar 已提交
153
                var localDeclaration = factory.LocalDeclarationStatement(localName, factory.TryCastExpression(objNameExpression, containingType));
P
Pilchie 已提交
154 155 156

                statements.Add(localDeclaration);

C
CyrusNajmabadi 已提交
157 158 159 160
                // Ensure that the parameter we got was not null (which also ensures the 'as' test
                // succeeded):
                //
                //      myType != null
161
                expressions.Add(factory.ReferenceNotEqualsExpression(localNameExpression, factory.NullLiteralExpression()));
C
Cyrus Najmabadi 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174
            }

            if (!containingType.IsValueType && HasExistingBaseEqualsMethod(containingType, cancellationToken))
            {
                // If we're overriding something that also provided an overridden 'Equals',
                // then ensure the base type thinks it is equals as well.
                //
                //      base.Equals(obj)
                expressions.Add(factory.InvocationExpression(
                    factory.MemberAccessExpression(
                        factory.BaseExpression(),
                        factory.IdentifierName(EqualsName)),
                    objNameExpression));
P
Pilchie 已提交
175 176
            }

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
            AddMemberChecks(factory, compilation, members, localNameExpression, expressions);

            // Now combine all the comparison expressions together into one final statement like:
            //
            //      return myType != null &&
            //             base.Equals(obj) &&
            //             this.S1 == myType.S1;
            statements.Add(factory.ReturnStatement(
                expressions.Aggregate(factory.LogicalAndExpression)));

            expressions.Free();
            return statements.ToImmutableAndFree();
        }

        private static void AddMemberChecks(
            SyntaxGenerator factory, Compilation compilation,
            ImmutableArray<ISymbol> members, SyntaxNode localNameExpression,
            ArrayBuilder<SyntaxNode> expressions)
        {
            var iequatableType = compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName);

C
CyrusNajmabadi 已提交
198 199 200 201
            // Now, iterate over all the supplied members and ensure that our instance
            // and the parameter think they are equals.  Specialize how we do this for
            // common types.  Fall-back to EqualityComparer<SType>.Default.Equals for
            // everything else.
P
Pilchie 已提交
202 203
            foreach (var member in members)
            {
204
                var symbolNameExpression = factory.IdentifierName(member.Name);
205 206
                var thisSymbol = factory.MemberAccessExpression(factory.ThisExpression(), symbolNameExpression)
                                        .WithAdditionalAnnotations(Simplification.Simplifier.Annotation);
207
                var otherSymbol = factory.MemberAccessExpression(localNameExpression, symbolNameExpression);
P
Pilchie 已提交
208

209
                var memberType = member.GetSymbolType();
P
Pilchie 已提交
210

211 212
                if (IsPrimitiveValueType(memberType))
                {
C
CyrusNajmabadi 已提交
213 214 215 216
                    // If we have one of the well known primitive types, then just use '==' to compare
                    // the values.
                    //
                    //      this.a == other.a
217 218
                    expressions.Add(factory.ValueEqualsExpression(thisSymbol, otherSymbol));
                    continue;
219
                }
220 221 222

                var valueIEquatable = memberType?.IsValueType == true && ImplementsIEquatable(memberType, iequatableType);
                if (valueIEquatable || memberType?.IsTupleType == true)
223
                {
224 225 226
                    // If it's a value type and implements IEquatable<T>, Or if it's a tuple, then 
                    // just call directly into .Equals. This keeps the code simple and avoids an 
                    // unnecessary null check.
C
CyrusNajmabadi 已提交
227 228
                    //
                    //      this.a.Equals(other.a)
229
                    expressions.Add(factory.InvocationExpression(
230
                        factory.MemberAccessExpression(thisSymbol, nameof(object.Equals)),
231 232
                        otherSymbol));
                    continue;
233
                }
234 235 236 237 238 239 240

                // Otherwise call EqualityComparer<SType>.Default.Equals(this.a, other.a).
                // This will do the appropriate null checks as well as calling directly
                // into IEquatable<T>.Equals implementations if available.

                expressions.Add(factory.InvocationExpression(
                        factory.MemberAccessExpression(
241
                            GetDefaultEqualityComparer(factory, compilation, GetType(compilation, member)),
242 243 244
                            factory.IdentifierName(EqualsName)),
                        thisSymbol,
                        otherSymbol));
P
Pilchie 已提交
245
            }
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        }

        private static ImmutableArray<SyntaxNode> CreateIEquatableEqualsMethodStatements(
            SyntaxGenerator factory,
            Compilation compilation,
            INamedTypeSymbol containingType,
            ImmutableArray<ISymbol> members,
            CancellationToken cancellationToken)
        {
            var statements = ArrayBuilder<SyntaxNode>.GetInstance();

            var otherNameExpression = factory.IdentifierName(OtherName);

            // These will be all the expressions that we'll '&&' together inside the final
            // return statement of 'Equals'.
            var expressions = ArrayBuilder<SyntaxNode>.GetInstance();

            if (!containingType.IsValueType)
            {
                // It's not a value type. Ensure that the parameter we got was not null.
                //
                //      other != null
                expressions.Add(factory.ReferenceNotEqualsExpression(otherNameExpression, factory.NullLiteralExpression()));
                if (HasExistingBaseEqualsMethod(containingType, cancellationToken))
                {
                    // If we're overriding something that also provided an overridden 'Equals',
                    // then ensure the base type thinks it is equals as well.
                    //
                    //      base.Equals(obj)
                    expressions.Add(factory.InvocationExpression(
                        factory.MemberAccessExpression(
                            factory.BaseExpression(),
                            factory.IdentifierName(EqualsName)),
                        otherNameExpression));
                }
            }

            AddMemberChecks(factory, compilation, members, otherNameExpression, expressions);
P
Pilchie 已提交
284

C
CyrusNajmabadi 已提交
285 286
            // Now combine all the comparison expressions together into one final statement like:
            //
287 288 289
            //      return other != null &&
            //             base.Equals(other) &&
            //             this.S1 == other.S1;
290 291
            statements.Add(factory.ReturnStatement(
                expressions.Aggregate(factory.LogicalAndExpression)));
P
Pilchie 已提交
292

293
            expressions.Free();
294
            return statements.ToImmutableAndFree();
P
Pilchie 已提交
295 296
        }

297
        public static string GetLocalName(this ITypeSymbol containingType)
298
        {
299 300
            var name = containingType.Name;
            if (name.Length > 0)
301
            {
302 303
                var parts = StringBreaker.GetWordParts(name);
                for (var i = parts.Count - 1; i >= 0; i--)
304
                {
305 306 307 308 309
                    var p = parts[i];
                    if (p.Length > 0 && char.IsLetter(name[p.Start]))
                    {
                        return name.Substring(p.Start, p.Length).ToCamelCase();
                    }
310 311 312 313 314 315
                }
            }

            return "v";
        }

316 317
        private static bool ImplementsIEquatable(ITypeSymbol memberType, INamedTypeSymbol iequatableType)
        {
C
CyrusNajmabadi 已提交
318 319
            if (iequatableType != null)
            {
320
                // TODO: pass the nullability to Construct once https://github.com/dotnet/roslyn/issues/36046 is fixed
321
                var constructed = iequatableType.Construct(memberType.WithoutNullability());
C
CyrusNajmabadi 已提交
322
                return memberType.AllInterfaces.Contains(constructed);
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
            }

            return false;
        }

        private static bool IsPrimitiveValueType(ITypeSymbol typeSymbol)
        {
            if (typeSymbol != null)
            {
                if (typeSymbol.IsEnumType())
                {
                    return true;
                }

                switch (typeSymbol.SpecialType)
                {
                    case SpecialType.System_Boolean:
                    case SpecialType.System_Char:
                    case SpecialType.System_SByte:
                    case SpecialType.System_Byte:
                    case SpecialType.System_Int16:
                    case SpecialType.System_UInt16:
                    case SpecialType.System_Int32:
                    case SpecialType.System_UInt32:
                    case SpecialType.System_Int64:
                    case SpecialType.System_UInt64:
                    case SpecialType.System_Decimal:
                    case SpecialType.System_Single:
                    case SpecialType.System_Double:
                    case SpecialType.System_String:
                    case SpecialType.System_Nullable_T:
                    case SpecialType.System_DateTime:
                        return true;
                }
            }

            return false;
        }

362 363
        public static SyntaxNode GetDefaultEqualityComparer(
            this SyntaxGenerator factory,
P
Pilchie 已提交
364
            Compilation compilation,
365
            ITypeSymbol type)
P
Pilchie 已提交
366 367
        {
            var equalityComparerType = compilation.EqualityComparerOfTType();
368
            var constructedType = equalityComparerType.Construct(type);
369
            return factory.MemberAccessExpression(
370
                factory.TypeExpression(constructedType),
371
                factory.IdentifierName(DefaultName));
P
Pilchie 已提交
372 373 374 375
        }

        private static ITypeSymbol GetType(Compilation compilation, ISymbol symbol)
        {
C
CyrusNajmabadi 已提交
376 377 378 379 380 381
            switch (symbol)
            {
                case IFieldSymbol field: return field.Type;
                case IPropertySymbol property: return property.Type;
                default: return compilation.GetSpecialType(SpecialType.System_Object);
            }
P
Pilchie 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
        }

        private static bool HasExistingBaseEqualsMethod(INamedTypeSymbol containingType, CancellationToken cancellationToken)
        {
            // Check if any of our base types override Equals.  If so, first check with them.
            var existingMethods =
                from baseType in containingType.GetBaseTypes()
                from method in baseType.GetMembers(EqualsName).OfType<IMethodSymbol>()
                where method.IsOverride &&
                      method.DeclaredAccessibility == Accessibility.Public &&
                      !method.IsStatic &&
                      method.Parameters.Length == 1 &&
                      method.ReturnType.SpecialType == SpecialType.System_Boolean &&
                      method.Parameters[0].Type.SpecialType == SpecialType.System_Object
                select method;

            return existingMethods.Any();
        }
    }
401
}