CSharpEditAndContinueAnalyzer.cs 139.5 KB
Newer Older
S
Sam Harwell 已提交
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.
2 3 4 5 6 7 8 9 10

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
11
using Microsoft.CodeAnalysis.CSharp.Symbols;
12 13 14 15
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Host.Mef;
16
using Microsoft.CodeAnalysis.Shared.Extensions;
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
    [ExportLanguageService(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared]
    internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer
    {
        #region Syntax Analysis

        private enum ConstructorPart
        {
            None = 0,
            DefaultBaseConstructorCall = 1,
        }

        private enum BlockPart
        {
            None = 0,
            OpenBrace = 1,
            CloseBrace = 2,
        }

        private enum ForEachPart
        {
            None = 0,
            ForEach = 1,
            VariableDeclaration = 2,
            In = 3,
            Expression = 4,
        }

        /// <returns>
        /// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors.
        /// <see cref="VariableDeclaratorSyntax"/> for field initializers.
        /// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies.
        /// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies.
        /// </returns>
55
        internal override SyntaxNode FindMemberDeclaration(SyntaxNode rootOpt, SyntaxNode node)
56
        {
57
            while (node != rootOpt)
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
            {
                switch (node.Kind())
                {
                    case SyntaxKind.MethodDeclaration:
                    case SyntaxKind.ConversionOperatorDeclaration:
                    case SyntaxKind.OperatorDeclaration:
                    case SyntaxKind.SetAccessorDeclaration:
                    case SyntaxKind.AddAccessorDeclaration:
                    case SyntaxKind.RemoveAccessorDeclaration:
                    case SyntaxKind.GetAccessorDeclaration:
                    case SyntaxKind.ConstructorDeclaration:
                    case SyntaxKind.DestructorDeclaration:
                        return node;

                    case SyntaxKind.PropertyDeclaration:
                        // int P { get; } = [|initializer|];
                        Debug.Assert(((PropertyDeclarationSyntax)node).Initializer != null);
                        return node;

                    case SyntaxKind.FieldDeclaration:
                    case SyntaxKind.EventFieldDeclaration:
                        // Active statements encompassing modifiers or type correspond to the first initialized field.
                        // [|public static int F = 1|], G = 2;
                        return ((BaseFieldDeclarationSyntax)node).Declaration.Variables.First();

                    case SyntaxKind.VariableDeclarator:
                        // public static int F = 1, [|G = 2|];
                        Debug.Assert(node.Parent.IsKind(SyntaxKind.VariableDeclaration));

                        switch (node.Parent.Parent.Kind())
                        {
                            case SyntaxKind.FieldDeclaration:
                            case SyntaxKind.EventFieldDeclaration:
                                return node;
                        }

                        node = node.Parent;
                        break;
                }

                node = node.Parent;
            }

            return null;
        }

        /// <returns>
        /// Given a node representing a declaration (<paramref name="isMember"/> = true) or a top-level match node (<paramref name="isMember"/> = false) returns:
        /// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors).
        /// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or 
        ///   for method-like member declarations with expression bodies (methods, properties, indexers, operators)
        /// 
        /// A null reference otherwise.
        /// </returns>
        internal override SyntaxNode TryGetDeclarationBody(SyntaxNode node, bool isMember)
        {
            if (node.IsKind(SyntaxKind.VariableDeclarator))
            {
                return (((VariableDeclaratorSyntax)node).Initializer)?.Value;
            }

            return SyntaxUtilities.TryGetMethodDeclarationBody(node);
        }

122
        protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody)
123
        {
124 125
            Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax);
            return model.AnalyzeDataFlow(memberBody).Captured;
126 127 128 129 130 131 132 133
        }

        internal override bool HasParameterClosureScope(ISymbol member)
        {
            // in instance constructor parameters are lifted to a closure different from method body
            return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor;
        }

134
        protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken)
135
        {
136
            Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol);
137 138 139 140 141

            // not supported (it's non trivial to find all places where "this" is used):
            Debug.Assert(!localOrParameter.IsThisParameter());

            return from root in roots
142
                   from node in root.DescendantNodesAndSelf()
143 144
                   where node.IsKind(SyntaxKind.IdentifierName)
                   let nameSyntax = (IdentifierNameSyntax)node
J
Jared Parsons 已提交
145
                   where (string)nameSyntax.Identifier.Value == localOrParameter.Name &&
146
                         (model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false)
147 148 149
                   select node;
        }

150 151
        /// <returns>
        /// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer,
152
        /// tokens of its block body, or tokens of the expression body.
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        /// 
        /// If <paramref name="node"/> is an indexer declaration the tokens of its expression body.
        /// 
        /// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer.
        ///   
        /// If <paramref name="node"/> is a constructor with an initializer, 
        /// tokens of the initializer concatenated with tokens of the constructor body.
        /// 
        /// If <paramref name="node"/> is a variable declarator of a field with an initializer,
        /// tokens of the field initializer.
        /// 
        /// Null reference otherwise.
        /// </returns>
        internal override IEnumerable<SyntaxToken> TryGetActiveTokens(SyntaxNode node)
        {
            if (node.IsKind(SyntaxKind.VariableDeclarator))
            {
                // TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it?

                var declarator = node;
                var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent.Parent;
                var variableDeclaration = fieldDeclaration.Declaration;

                if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
                {
                    return null;
                }

                if (variableDeclaration.Variables.Count == 1)
                {
                    if (variableDeclaration.Variables[0].Initializer == null)
                    {
                        return null;
                    }

                    return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken);
                }

                if (declarator == variableDeclaration.Variables[0])
                {
                    return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens());
                }

                return declarator.DescendantTokens();
            }

199 200
            var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens();

201 202 203 204 205
            if (node.IsKind(SyntaxKind.ConstructorDeclaration))
            {
                var ctor = (ConstructorDeclarationSyntax)node;
                if (ctor.Initializer != null)
                {
206
                    bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens);
207 208 209
                }
            }

210
            return bodyTokens;
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        }

        protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot)
        {
            // Constructor may contain active nodes outside of its body (constructor initializer),
            // but within the body of the member declaration (the parent).
            if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
            {
                return bodyOrMatchRoot.Parent;
            }

            // Field initializer match root -- an active statement may include the modifiers 
            // and type specification of the field declaration.
            if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) &&
                bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) &&
                bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
            {
                return bodyOrMatchRoot.Parent.Parent;
            }

            // Field initializer body -- an active statement may include the modifiers 
            // and type specification of the field declaration.
            if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
                bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) &&
                bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration))
            {
                return bodyOrMatchRoot.Parent.Parent.Parent;
            }

            // otherwise all active statements are covered by the body/match root itself:
            return bodyOrMatchRoot;
        }

        protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, int position, SyntaxNode partnerDeclarationBodyOpt, out SyntaxNode partnerOpt, out int statementPart)
        {
            SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false);

            if (position < declarationBody.SpanStart)
            {
                // Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>.
                // Constructor:                          [|public C()|] <<{ }>>
                // Constructor initializer:              public C() : [|base(expr)|] <<{ }>>
                // Constructor initializer with lambda:  public C() : base(() => { [|...|] }) <<{ }>>
                // Field initializers:                   [|public int a = <<expr>>|], [|b = <<expr>>|];

C
Charles Stoner 已提交
256
                // No need to special case property initializers here, the active statement always spans the initializer expression.
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272

                if (declarationBody.Parent.Kind() == SyntaxKind.ConstructorDeclaration)
                {
                    var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent;
                    var partnerConstructor = (ConstructorDeclarationSyntax)partnerDeclarationBodyOpt?.Parent;

                    if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart)
                    {
                        statementPart = (int)ConstructorPart.DefaultBaseConstructorCall;
                        partnerOpt = partnerConstructor;
                        return constructor;
                    }

                    declarationBody = constructor.Initializer;
                    partnerDeclarationBodyOpt = partnerConstructor?.Initializer;
                }
T
Tomas Matousek 已提交
273
            }
274

T
Tomas Matousek 已提交
275 276 277 278
            if (!declarationBody.FullSpan.Contains(position))
            {
                // invalid position, let's find a labeled node that encompasses the body:
                position = declarationBody.SpanStart;
279 280 281 282 283 284 285
            }

            SyntaxNode node;
            if (partnerDeclarationBodyOpt != null)
            {
                SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBodyOpt, out node, out partnerOpt);
            }
286
            else
287 288 289 290 291
            {
                node = declarationBody.FindToken(position).Parent;
                partnerOpt = null;
            }

292
            while (node != declarationBody && !StatementSyntaxComparer.HasLabel(node) && !LambdaUtilities.IsLambdaBodyStatementOrExpression(node))
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
            {
                node = node.Parent;
                if (partnerOpt != null)
                {
                    partnerOpt = partnerOpt.Parent;
                }
            }

            switch (node.Kind())
            {
                case SyntaxKind.Block:
                    statementPart = (int)GetStatementPart((BlockSyntax)node, position);
                    break;

                case SyntaxKind.ForEachStatement:
308 309
                case SyntaxKind.ForEachVariableStatement:
                    statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position);
310 311 312 313 314 315 316 317 318 319 320 321 322 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
                    break;

                case SyntaxKind.VariableDeclaration:
                    // VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator)
                    // 
                    // The compiler places sequence points after each local variable initialization.
                    // The TypeSyntax is considered to be part of the first sequence span.
                    node = ((VariableDeclarationSyntax)node).Variables.First();

                    if (partnerOpt != null)
                    {
                        partnerOpt = ((VariableDeclarationSyntax)partnerOpt).Variables.First();
                    }

                    statementPart = 0;
                    break;

                default:
                    statementPart = 0;
                    break;
            }

            return node;
        }

        private static BlockPart GetStatementPart(BlockSyntax node, int position)
        {
            return position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace;
        }

        private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part)
        {
            switch (part)
            {
                case BlockPart.OpenBrace:
                    return node.OpenBraceToken.Span;

                case BlockPart.CloseBrace:
                    return node.CloseBraceToken.Span;

                default:
                    throw ExceptionUtilities.UnexpectedValue(part);
            }
        }

355
        private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position)
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        {
            return position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach :
                   position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration :
                   position < node.Expression.SpanStart ? ForEachPart.In :
                   ForEachPart.Expression;
        }

        private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part)
        {
            switch (part)
            {
                case ForEachPart.ForEach:
                    return node.ForEachKeyword.Span;

                case ForEachPart.VariableDeclaration:
                    return TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End);

                case ForEachPart.In:
                    return node.InKeyword.Span;

                case ForEachPart.Expression:
                    return node.Expression.Span;

                default:
                    throw ExceptionUtilities.UnexpectedValue(part);
            }
        }

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part)
        {
            switch (part)
            {
                case ForEachPart.ForEach:
                    return node.ForEachKeyword.Span;

                case ForEachPart.VariableDeclaration:
                    return TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End);

                case ForEachPart.In:
                    return node.InKeyword.Span;

                case ForEachPart.Expression:
                    return node.Expression.Span;

                default:
                    throw ExceptionUtilities.UnexpectedValue(part);
            }
        }

405 406 407 408 409
        protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right)
        {
            return SyntaxFactory.AreEquivalent(left, right);
        }

410 411 412 413 414 415 416 417 418 419 420
        private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right)
        {
            // usual case:
            if (SyntaxFactory.AreEquivalent(left, right))
            {
                return true;
            }

            return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right);
        }

421
        internal override SyntaxNode FindPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode)
422
        {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
            return SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode);
        }

        internal override SyntaxNode FindPartnerInMemberInitializer(SemanticModel leftModel, INamedTypeSymbol leftType, SyntaxNode leftNode, INamedTypeSymbol rightType, CancellationToken cancellationToken)
        {
            var leftEqualsClause = leftNode.FirstAncestorOrSelf<EqualsValueClauseSyntax>(
                node => node.Parent.IsKind(SyntaxKind.PropertyDeclaration) || node.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration));

            if (leftEqualsClause == null)
            {
                return null;
            }

            SyntaxNode rightEqualsClause;
            if (leftEqualsClause.Parent.IsKind(SyntaxKind.PropertyDeclaration))
            {
                var leftDeclaration = (PropertyDeclarationSyntax)leftEqualsClause.Parent;
                var leftSymbol = leftModel.GetDeclaredSymbol(leftDeclaration, cancellationToken);
                Debug.Assert(leftSymbol != null);

                var rightProperty = rightType.GetMembers(leftSymbol.Name).Single();
                var rightDeclaration = (PropertyDeclarationSyntax)GetSymbolSyntax(rightProperty, cancellationToken);

                rightEqualsClause = rightDeclaration.Initializer;
            }
            else
            {
                var leftDeclarator = (VariableDeclaratorSyntax)leftEqualsClause.Parent;
                var leftSymbol = leftModel.GetDeclaredSymbol(leftDeclarator, cancellationToken);
                Debug.Assert(leftSymbol != null);

                var rightField = rightType.GetMembers(leftSymbol.Name).Single();
                var rightDeclarator = (VariableDeclaratorSyntax)GetSymbolSyntax(rightField, cancellationToken);

                rightEqualsClause = rightDeclarator.Initializer;
            }

            if (rightEqualsClause == null)
            {
                return null;
            }

            return FindPartner(leftEqualsClause, rightEqualsClause, leftNode);
466 467
        }

468 469
        internal override bool IsClosureScope(SyntaxNode node)
        {
470
            return LambdaUtilities.IsClosureScope(node);
471 472
        }

473 474 475 476
        protected override SyntaxNode FindEnclosingLambdaBody(SyntaxNode containerOpt, SyntaxNode node)
        {
            SyntaxNode root = GetEncompassingAncestor(containerOpt);

T
Tomas Matousek 已提交
477
            while (node != root && node != null)
478
            {
C
CyrusNajmabadi 已提交
479
                if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node, out var body))
480
                {
481
                    return body;
482 483 484 485 486 487 488 489
                }

                node = node.Parent;
            }

            return null;
        }

490
        protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody)
491
        {
492
            return SpecializedCollections.SingletonEnumerable(lambdaBody);
493 494
        }

495
        protected override SyntaxNode TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda)
496
        {
497
            return LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda);
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        }

        protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit)
        {
            return TopSyntaxComparer.Instance.ComputeMatch(oldCompilationUnit, newCompilationUnit);
        }

        protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> knownMatches)
        {
            SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true);
            SyntaxUtilities.AssertIsBody(newBody, allowLambda: true);

            if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax)
            {
                Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax);
                Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax);

                // The matching algorithm requires the roots to match each other.
                // Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions.
                // Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then 
                // the algorithm would match 'x => x' to 'F(x => x + 1)' instead of 
                // matching 'x => x' to 'x => x + 1'.

                // We use the parent node as a root:
                // - for field/property initializers the root is EqualsValueClause. 
                // - for expression-bodies the root is ArrowExpressionClauseSyntax. 
                // - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body)
                // - for lambdas the root is a LambdaExpression.
                // - for query lambdas the root is the query clause containing the lambda (e.g. where).

                return new StatementSyntaxComparer(oldBody, newBody).ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches);
            }

531 532
            if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration))
            {
533
                // We need to include constructor initializer in the match, since it may contain lambdas.
534 535 536 537 538 539 540 541
                // Use the constructor declaration as a root.
                Debug.Assert(oldBody.IsKind(SyntaxKind.Block));
                Debug.Assert(newBody.IsKind(SyntaxKind.Block));
                Debug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration));

                return StatementSyntaxComparer.Default.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches);
            }

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
            return StatementSyntaxComparer.Default.ComputeMatch(oldBody, newBody, knownMatches);
        }

        protected override bool TryMatchActiveStatement(
            SyntaxNode oldStatement,
            int statementPart,
            SyntaxNode oldBody,
            SyntaxNode newBody,
            out SyntaxNode newStatement)
        {
            SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true);
            SyntaxUtilities.AssertIsBody(newBody, allowLambda: true);

            switch (oldStatement.Kind())
            {
                case SyntaxKind.ThisConstructorInitializer:
                case SyntaxKind.BaseConstructorInitializer:
                case SyntaxKind.ConstructorDeclaration:
                    var newConstructor = (ConstructorDeclarationSyntax)newBody.Parent;
                    newStatement = (SyntaxNode)newConstructor.Initializer ?? newConstructor;
                    return true;

                default:
                    // TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa.
                    // It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties.

                    // field initializer, lambda and query expressions:
                    if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block))
                    {
                        newStatement = newBody;
                        return true;
                    }

                    newStatement = null;
                    return false;
            }
        }

        #endregion

        #region Syntax and Semantic Utils

        protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes)
        {
            return SyntaxComparer.GetSequenceEdits(oldNodes, newNodes);
        }

        internal override SyntaxNode EmptyCompilationUnit
        {
            get
            {
                return SyntaxFactory.CompilationUnit();
            }
        }

        internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree)
        {
            // there are no experimental features at this time.
            return false;
        }

        protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2)
        {
            return StatementSyntaxComparer.GetLabelImpl(node1) == StatementSyntaxComparer.GetLabelImpl(node2);
        }

        protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span)
        {
610
            return BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span);
611 612 613 614 615 616 617 618 619 620 621 622 623 624
        }

        protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, out TextSpan span)
        {
            switch (node.Kind())
            {
                case SyntaxKind.Block:
                    span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart);
                    return true;

                case SyntaxKind.ForEachStatement:
                    span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart);
                    return true;

625 626 627 628
                case SyntaxKind.ForEachVariableStatement:
                    span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart);
                    return true;

629 630 631 632 633
                case SyntaxKind.DoStatement:
                    // The active statement of DoStatement node is the while condition,
                    // which is lexically not the closest breakpoint span (the body is).
                    // do { ... } [|while (condition);|]
                    var doStatement = (DoStatementSyntax)node;
634
                    return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span);
635 636 637

                case SyntaxKind.PropertyDeclaration:
                    // The active span corresponding to a property declaration is the span corresponding to its initializer (if any),
638
                    // not the span corresponding to the accessor.
639 640 641 642
                    // int P { [|get;|] } = [|<initializer>|];
                    var propertyDeclaration = (PropertyDeclarationSyntax)node;

                    if (propertyDeclaration.Initializer != null &&
643
                        BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span))
644 645 646 647 648 649 650 651 652 653
                    {
                        return true;
                    }
                    else
                    {
                        span = default(TextSpan);
                        return false;
                    }

                default:
654
                    return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span);
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
            }
        }

        protected override IEnumerable<KeyValuePair<SyntaxNode, int>> EnumerateNearStatements(SyntaxNode statement)
        {
            int direction = +1;
            SyntaxNodeOrToken nodeOrToken = statement;
            var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement);

            while (true)
            {
                nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling();

                if (nodeOrToken.RawKind == 0)
                {
                    var parent = statement.Parent;
                    if (parent == null)
                    {
                        yield break;
                    }

                    if (parent.IsKind(SyntaxKind.Block))
                    {
                        yield return KeyValuePair.Create(parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace));
                    }
                    else if (parent.IsKind(SyntaxKind.ForEachStatement))
                    {
                        yield return KeyValuePair.Create(parent, (int)ForEachPart.ForEach);
                    }

                    if (direction > 0)
                    {
                        nodeOrToken = statement;
                        direction = -1;
                        continue;
                    }

                    if (fieldOrPropertyModifiers.HasValue)
                    {
                        // We enumerated all members and none of them has an initializer.
                        // We don't have any better place where to place the span than the initial field.
696
                        // Consider: in non-partial classes we could find a single constructor. 
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
                        // Otherwise, it would be confusing to select one arbitrarily.
                        yield return KeyValuePair.Create(statement, -1);
                    }

                    nodeOrToken = statement = parent;
                    fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement);
                    direction = +1;

                    yield return KeyValuePair.Create(nodeOrToken.AsNode(), 0);
                }
                else
                {
                    var node = nodeOrToken.AsNode();
                    if (node == null)
                    {
                        continue;
                    }

                    if (fieldOrPropertyModifiers.HasValue)
                    {
                        var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node);

                        if (!nodeModifiers.HasValue ||
                            nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword))
                        {
                            continue;
                        }
                    }

                    if (node.IsKind(SyntaxKind.Block))
                    {
                        yield return KeyValuePair.Create(node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace));
                    }
                    else if (node.IsKind(SyntaxKind.ForEachStatement))
                    {
                        yield return KeyValuePair.Create(node, (int)ForEachPart.ForEach);
                    }

                    yield return KeyValuePair.Create(node, 0);
                }
            }
        }

        protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart)
        {
            if (oldStatement.Kind() != newStatement.Kind())
            {
                return false;
            }

            switch (oldStatement.Kind())
            {
                case SyntaxKind.Block:
                    Debug.Assert(statementPart != 0);
                    return true;

                case SyntaxKind.ConstructorDeclaration:
                    Debug.Assert(statementPart != 0);

                    // The call could only change if the base type of the containing class changed.
                    return true;

                case SyntaxKind.ForEachStatement:
760
                case SyntaxKind.ForEachVariableStatement:
761 762 763
                    Debug.Assert(statementPart != 0);

                    // only check the expression, edits in the body and the variable declaration are allowed:
764
                    return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement);
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

                case SyntaxKind.IfStatement:
                    // only check the condition, edits in the body are allowed:
                    return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement);

                case SyntaxKind.WhileStatement:
                    // only check the condition, edits in the body are allowed:
                    return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement);

                case SyntaxKind.DoStatement:
                    // only check the condition, edits in the body are allowed:
                    return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement);

                case SyntaxKind.SwitchStatement:
                    return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement);

                case SyntaxKind.LockStatement:
                    return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement);

                case SyntaxKind.UsingStatement:
                    return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement);

                // fixed and for statements don't need special handling since the active statement is a variable declaration
                default:
789
                    return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement);
790 791 792 793 794 795
            }
        }

        private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode)
        {
            // only check the condition, edits in the body are allowed:
796
            return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition);
797 798 799 800 801
        }

        private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode)
        {
            // only check the condition, edits in the body are allowed:
802
            return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition);
803 804 805 806 807
        }

        private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode)
        {
            // only check the condition, edits in the body are allowed:
808
            return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition);
809 810 811 812 813
        }

        private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode)
        {
            // only check the expression, edits in the body are allowed:
814
            return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression);
815 816 817 818 819
        }

        private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode)
        {
            // only check the expression, edits in the body are allowed:
820
            return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression);
821 822 823 824
        }

        private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode)
        {
825
            return AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration);
826 827 828 829 830
        }

        private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode)
        {
            // only check the expression/declaration, edits in the body are allowed:
831
            return AreEquivalentIgnoringLambdaBodies(
832 833 834 835
                (SyntaxNode)oldNode.Declaration ?? oldNode.Expression,
                (SyntaxNode)newNode.Declaration ?? newNode.Expression);
        }

836
        private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode)
837
        {
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
            if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression))
            {
                return false;
            }

            switch (oldNode.Kind())
            {
                case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type);
                case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable);
                default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind());
            }
        }

        private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode)
        {
            List<SyntaxToken> oldTokens = null;
            List<SyntaxToken> newTokens = null;

            StatementSyntaxComparer.GetLocalNames(oldNode, ref oldTokens);
            StatementSyntaxComparer.GetLocalNames(newNode, ref newTokens);

            return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray());
860 861 862 863 864 865 866 867 868 869 870 871
        }

        internal override bool IsMethod(SyntaxNode declaration)
        {
            return SyntaxUtilities.IsMethod(declaration);
        }

        internal override SyntaxNode TryGetContainingTypeDeclaration(SyntaxNode memberDeclaration)
        {
            return memberDeclaration.Parent.FirstAncestorOrSelf<TypeDeclarationSyntax>();
        }

872
        internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration)
873
        {
J
Jared Parsons 已提交
874
            return propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration) &&
875
                   SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)propertyOrIndexerDeclaration);
876 877
        }

878
        internal override bool IsDeclarationWithInitializer(SyntaxNode declaration)
879 880 881 882
        {
            switch (declaration.Kind())
            {
                case SyntaxKind.VariableDeclarator:
883
                    return ((VariableDeclaratorSyntax)declaration).Initializer != null;
884 885

                case SyntaxKind.PropertyDeclaration:
886
                    return ((PropertyDeclarationSyntax)declaration).Initializer != null;
887 888 889 890 891 892

                default:
                    return false;
            }
        }

893
        internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration)
894
        {
895 896
            var ctor = constructorDeclaration as ConstructorDeclarationSyntax;
            return ctor != null && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer));
897 898 899 900 901 902 903 904 905 906 907
        }

        internal override bool IsPartial(INamedTypeSymbol type)
        {
            var syntaxRefs = type.DeclaringSyntaxReferences;
            return syntaxRefs.Length > 1
                || ((TypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword);
        }

        protected override ISymbol GetSymbolForEdit(SemanticModel model, SyntaxNode node, EditKind editKind, Dictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken)
        {
908 909 910 911 912
            if (node.IsKind(SyntaxKind.Parameter))
            {
                return null;
            }

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
            if (editKind == EditKind.Update)
            {
                if (node.IsKind(SyntaxKind.EnumDeclaration))
                {
                    // Enum declaration update that removes/adds a trailing comma.
                    return null;
                }

                if (node.IsKind(SyntaxKind.IndexerDeclaration) || node.IsKind(SyntaxKind.PropertyDeclaration))
                {
                    // The only legitimate update of an indexer/property declaration is an update of its expression body.
                    // The expression body itself may have been updated, replaced with an explicit getter, or added to replace an explicit getter.
                    // In any case, the update is to the property getter symbol.
                    var propertyOrIndexer = model.GetDeclaredSymbol(node, cancellationToken);
                    return ((IPropertySymbol)propertyOrIndexer).GetMethod;
                }
            }

            if (IsGetterToExpressionBodyTransformation(editKind, node, editMap))
            {
                return null;
            }

            return model.GetDeclaredSymbol(node, cancellationToken);
        }

        protected override bool TryGetDeclarationBodyEdit(Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap, out SyntaxNode oldBody, out SyntaxNode newBody)
        {
            // Detect a transition between a property/indexer with an expression body and with an explicit getter.
            // int P => old_body;              <->      int P { get { new_body } } 
            // int this[args] => old_body;     <->      int this[args] { get { new_body } }     

            // First, return getter or expression body for property/indexer update:
            if (edit.Kind == EditKind.Update && (edit.OldNode.IsKind(SyntaxKind.PropertyDeclaration) || edit.OldNode.IsKind(SyntaxKind.IndexerDeclaration)))
            {
                oldBody = SyntaxUtilities.TryGetEffectiveGetterBody(edit.OldNode);
                newBody = SyntaxUtilities.TryGetEffectiveGetterBody(edit.NewNode);

                if (oldBody != null && newBody != null)
                {
                    return true;
                }
            }

            // Second, ignore deletion of a getter body:
            if (IsGetterToExpressionBodyTransformation(edit.Kind, edit.OldNode ?? edit.NewNode, editMap))
            {
                oldBody = newBody = null;
                return false;
            }

            return base.TryGetDeclarationBodyEdit(edit, editMap, out oldBody, out newBody);
        }

        private static bool IsGetterToExpressionBodyTransformation(EditKind editKind, SyntaxNode node, Dictionary<SyntaxNode, EditKind> editMap)
        {
            if ((editKind == EditKind.Insert || editKind == EditKind.Delete) && node.IsKind(SyntaxKind.GetAccessorDeclaration))
            {
                Debug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList));
                Debug.Assert(node.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration) || node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration));
C
CyrusNajmabadi 已提交
973
                return editMap.TryGetValue(node.Parent, out var parentEdit) && parentEdit == editKind &&
974 975 976 977 978 979
                       editMap.TryGetValue(node.Parent.Parent, out parentEdit) && parentEdit == EditKind.Update;
            }

            return false;
        }

980 981
        internal override bool ContainsLambda(SyntaxNode declaration)
        {
982
            return declaration.DescendantNodes().Any(LambdaUtilities.IsLambda);
983 984 985 986
        }

        internal override bool IsLambda(SyntaxNode node)
        {
987
            return LambdaUtilities.IsLambda(node);
988 989
        }

990 991 992 993 994
        internal override bool IsLambdaExpression(SyntaxNode node)
        {
            return node is LambdaExpressionSyntax;
        }

995 996
        internal override bool TryGetLambdaBodies(SyntaxNode node, out SyntaxNode body1, out SyntaxNode body2)
        {
997
            return LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2);
998 999 1000 1001
        }

        internal override SyntaxNode GetLambda(SyntaxNode lambdaBody)
        {
1002
            return LambdaUtilities.GetLambda(lambdaBody);
1003 1004
        }

1005 1006
        internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken)
        {
1007
            return (IMethodSymbol)model.GetEnclosingSymbol(((AnonymousFunctionExpressionSyntax)lambdaExpression).Body.SpanStart, cancellationToken);
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
        }

        internal override SyntaxNode GetContainingQueryExpression(SyntaxNode node)
        {
            return node.FirstAncestorOrSelf<QueryExpressionSyntax>();
        }

        internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken)
        {
            switch (oldNode.Kind())
            {
                case SyntaxKind.FromClause:
                case SyntaxKind.LetClause:
                case SyntaxKind.WhereClause:
                case SyntaxKind.OrderByClause:
                case SyntaxKind.JoinClause:
                    var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken);
                    var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken);

                    return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) &&
                           MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol);

                case SyntaxKind.AscendingOrdering:
                case SyntaxKind.DescendingOrdering:
1032 1033 1034 1035 1036
                    var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken);
                    var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken);

                    return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol);

1037
                case SyntaxKind.SelectClause:
1038 1039
                    var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken);
                    var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken);
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
                    // Changing reduced select clause to a non-reduced form or vice versa
                    // adds/removes a call to Select method, which is a supported change.

                    return oldSelectInfo.Symbol == null ||
                           newSelectInfo.Symbol == null ||
                           MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol);

                case SyntaxKind.GroupClause:
                    var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken);
                    var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken);
                    return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer);
1052 1053 1054 1055 1056 1057

                default:
                    return true;
            }
        }

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
        private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType)
        {
            // C# spec paragraph 7.16.2.6 "Groupby clauses":
            //
            // A query expression of the form
            //   from x in e group v by k
            // is translated into
            //   (e).GroupBy(x => k, x => v)
            // except when v is the identifier x, the translation is
            //   (e).GroupBy(x => k)
            //
            // Possible signatures:
            //   C<G<K, T>> GroupBy<K>(Func<T, K> keySelector);
            //   C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector);

            if (!s_assemblyEqualityComparer.Equals(oldReturnType, newReturnType))
            {
                return false;
            }

            Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2);
            Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2);

            // The types of the lambdas have to be the same if present.
            // The element selector may be added/removed.

            if (!s_assemblyEqualityComparer.ParameterEquivalenceComparer.Equals(oldParameters[0], newParameters[0]))
            {
                return false;
            }

            if (oldParameters.Length == newParameters.Length && newParameters.Length == 2)
            {
                return s_assemblyEqualityComparer.ParameterEquivalenceComparer.Equals(oldParameters[1], newParameters[1]);
            }

            return true;
        }

1097 1098 1099 1100
        #endregion

        #region Diagnostic Info

1101 1102
        protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat;

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
        protected override TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind)
        {
            return GetDiagnosticSpanImpl(node, editKind);
        }

        private static TextSpan GetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind)
        {
            return GetDiagnosticSpanImpl(node.Kind(), node, editKind);
        }

        // internal for testing; kind is passed explicitly for testing as well
        internal static TextSpan GetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind)
        {
            switch (kind)
            {
                case SyntaxKind.CompilationUnit:
                    return default(TextSpan);

                case SyntaxKind.GlobalStatement:
                    // TODO:
                    return default(TextSpan);

                case SyntaxKind.ExternAliasDirective:
                case SyntaxKind.UsingDirective:
                    return node.Span;

                case SyntaxKind.NamespaceDeclaration:
                    var ns = (NamespaceDeclarationSyntax)node;
                    return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End);

                case SyntaxKind.ClassDeclaration:
                case SyntaxKind.StructDeclaration:
                case SyntaxKind.InterfaceDeclaration:
                    var typeDeclaration = (TypeDeclarationSyntax)node;
                    return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword,
                        typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier);

                case SyntaxKind.EnumDeclaration:
                    var enumDeclaration = (EnumDeclarationSyntax)node;
                    return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier);

                case SyntaxKind.DelegateDeclaration:
                    var delegateDeclaration = (DelegateDeclarationSyntax)node;
                    return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList);

                case SyntaxKind.FieldDeclaration:
                    var fieldDeclaration = (BaseFieldDeclarationSyntax)node;
                    return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration);

                case SyntaxKind.EventFieldDeclaration:
                    var eventFieldDeclaration = (EventFieldDeclarationSyntax)node;
                    return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration);

                case SyntaxKind.VariableDeclaration:
                    return GetDiagnosticSpanImpl(node.Parent, editKind);

                case SyntaxKind.VariableDeclarator:
                    return node.Span;

                case SyntaxKind.MethodDeclaration:
                    var methodDeclaration = (MethodDeclarationSyntax)node;
                    return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList);

                case SyntaxKind.ConversionOperatorDeclaration:
                    var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node;
                    return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList);

                case SyntaxKind.OperatorDeclaration:
                    var operatorDeclaration = (OperatorDeclarationSyntax)node;
                    return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList);

                case SyntaxKind.ConstructorDeclaration:
                    var constructorDeclaration = (ConstructorDeclarationSyntax)node;
                    return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList);

                case SyntaxKind.DestructorDeclaration:
                    var destructorDeclaration = (DestructorDeclarationSyntax)node;
                    return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList);

                case SyntaxKind.PropertyDeclaration:
                    var propertyDeclaration = (PropertyDeclarationSyntax)node;
                    return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier);

                case SyntaxKind.IndexerDeclaration:
                    var indexerDeclaration = (IndexerDeclarationSyntax)node;
                    return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList);

                case SyntaxKind.EventDeclaration:
                    var eventDeclaration = (EventDeclarationSyntax)node;
                    return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier);

                case SyntaxKind.EnumMemberDeclaration:
                    return node.Span;

                case SyntaxKind.GetAccessorDeclaration:
                case SyntaxKind.SetAccessorDeclaration:
                case SyntaxKind.AddAccessorDeclaration:
                case SyntaxKind.RemoveAccessorDeclaration:
                case SyntaxKind.UnknownAccessorDeclaration:
                    var accessorDeclaration = (AccessorDeclarationSyntax)node;
                    return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword);

                case SyntaxKind.TypeParameterConstraintClause:
                    var constraint = (TypeParameterConstraintClauseSyntax)node;
                    return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End);

                case SyntaxKind.TypeParameter:
                    var typeParameter = (TypeParameterSyntax)node;
                    return typeParameter.Identifier.Span;

                case SyntaxKind.AccessorList:
                case SyntaxKind.TypeParameterList:
                case SyntaxKind.ParameterList:
                case SyntaxKind.BracketedParameterList:
                    if (editKind == EditKind.Delete)
                    {
                        return GetDiagnosticSpanImpl(node.Parent, editKind);
                    }
                    else
                    {
                        return node.Span;
                    }

                case SyntaxKind.Parameter:
                    // We ignore anonymous methods and lambdas, 
                    // we only care about parameters of member declarations.
                    var parameter = (ParameterSyntax)node;
                    return GetDiagnosticSpan(parameter.Modifiers, parameter.Type, parameter);

                case SyntaxKind.AttributeList:
                    var attributeList = (AttributeListSyntax)node;
                    if (editKind == EditKind.Update)
                    {
                        return (attributeList.Target != null) ? attributeList.Target.Span : attributeList.Span;
                    }
                    else
                    {
                        return attributeList.Span;
                    }

                case SyntaxKind.Attribute:
                case SyntaxKind.ArrowExpressionClause:
                    return node.Span;

                // We only need a diagnostic span if reporting an error for a child statement.
                // The following statements may have child statements.

                case SyntaxKind.Block:
                    return ((BlockSyntax)node).OpenBraceToken.Span;

                case SyntaxKind.UsingStatement:
                    var usingStatement = (UsingStatementSyntax)node;
                    return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End);

                case SyntaxKind.FixedStatement:
                    var fixedStatement = (FixedStatementSyntax)node;
                    return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End);

                case SyntaxKind.LockStatement:
                    var lockStatement = (LockStatementSyntax)node;
                    return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End);

                case SyntaxKind.StackAllocArrayCreationExpression:
                    return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span;

                case SyntaxKind.TryStatement:
                    return ((TryStatementSyntax)node).TryKeyword.Span;

                case SyntaxKind.CatchClause:
                    return ((CatchClauseSyntax)node).CatchKeyword.Span;

1274
                case SyntaxKind.CatchDeclaration:
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
                case SyntaxKind.CatchFilterClause:
                    return node.Span;

                case SyntaxKind.FinallyClause:
                    return ((FinallyClauseSyntax)node).FinallyKeyword.Span;

                case SyntaxKind.IfStatement:
                    var ifStatement = (IfStatementSyntax)node;
                    return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End);

                case SyntaxKind.ElseClause:
                    return ((ElseClauseSyntax)node).ElseKeyword.Span;

                case SyntaxKind.SwitchStatement:
                    var switchStatement = (SwitchStatementSyntax)node;
                    return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart, switchStatement.CloseParenToken.Span.End);

                case SyntaxKind.SwitchSection:
                    return ((SwitchSectionSyntax)node).Labels.Last().Span;

                case SyntaxKind.WhileStatement:
                    var whileStatement = (WhileStatementSyntax)node;
                    return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End);

                case SyntaxKind.DoStatement:
                    return ((DoStatementSyntax)node).DoKeyword.Span;

                case SyntaxKind.ForStatement:
                    var forStatement = (ForStatementSyntax)node;
                    return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End);

                case SyntaxKind.ForEachStatement:
1307 1308 1309
                case SyntaxKind.ForEachVariableStatement:
                    var commonForEachStatement = (CommonForEachStatementSyntax)node;
                    return TextSpan.FromBounds(commonForEachStatement.ForEachKeyword.SpanStart, commonForEachStatement.CloseParenToken.Span.End);
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

                case SyntaxKind.LabeledStatement:
                    return ((LabeledStatementSyntax)node).Identifier.Span;

                case SyntaxKind.CheckedStatement:
                case SyntaxKind.UncheckedStatement:
                    return ((CheckedStatementSyntax)node).Keyword.Span;

                case SyntaxKind.UnsafeStatement:
                    return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span;

N
Neal Gafter 已提交
1321 1322 1323 1324
                case SyntaxKind.LocalFunctionStatement:
                    var lfd = (LocalFunctionStatementSyntax)node;
                    return lfd.Identifier.Span;

1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
                case SyntaxKind.YieldBreakStatement:
                case SyntaxKind.YieldReturnStatement:
                case SyntaxKind.ReturnStatement:
                case SyntaxKind.ThrowStatement:
                case SyntaxKind.ExpressionStatement:
                case SyntaxKind.LocalDeclarationStatement:
                case SyntaxKind.GotoStatement:
                case SyntaxKind.GotoCaseStatement:
                case SyntaxKind.GotoDefaultStatement:
                case SyntaxKind.BreakStatement:
                case SyntaxKind.ContinueStatement:
                    return node.Span;

                case SyntaxKind.AwaitExpression:
                    return ((AwaitExpressionSyntax)node).AwaitKeyword.Span;

                case SyntaxKind.AnonymousObjectCreationExpression:
                    return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span;

                case SyntaxKind.ParenthesizedLambdaExpression:
                    return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span;

                case SyntaxKind.SimpleLambdaExpression:
                    return ((SimpleLambdaExpressionSyntax)node).Parameter.Span;

                case SyntaxKind.AnonymousMethodExpression:
                    return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span;

                case SyntaxKind.QueryExpression:
                    return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span;

1356 1357 1358 1359 1360 1361 1362
                case SyntaxKind.QueryBody:
                    var queryBody = (QueryBodySyntax)node;
                    return GetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent, editKind);

                case SyntaxKind.QueryContinuation:
                    return ((QueryContinuationSyntax)node).IntoKeyword.Span;

1363 1364 1365 1366 1367 1368
                case SyntaxKind.FromClause:
                    return ((FromClauseSyntax)node).FromKeyword.Span;

                case SyntaxKind.JoinClause:
                    return ((JoinClauseSyntax)node).JoinKeyword.Span;

1369 1370 1371
                case SyntaxKind.JoinIntoClause:
                    return ((JoinIntoClauseSyntax)node).IntoKeyword.Span;

1372 1373 1374 1375 1376 1377
                case SyntaxKind.LetClause:
                    return ((LetClauseSyntax)node).LetKeyword.Span;

                case SyntaxKind.WhereClause:
                    return ((WhereClauseSyntax)node).WhereKeyword.Span;

1378 1379 1380
                case SyntaxKind.OrderByClause:
                    return ((OrderByClauseSyntax)node).OrderByKeyword.Span;

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
                case SyntaxKind.AscendingOrdering:
                case SyntaxKind.DescendingOrdering:
                    return node.Span;

                case SyntaxKind.SelectClause:
                    return ((SelectClauseSyntax)node).SelectKeyword.Span;

                case SyntaxKind.GroupClause:
                    return ((GroupClauseSyntax)node).GroupKeyword.Span;

1391 1392 1393 1394 1395 1396 1397
                case SyntaxKind.IsPatternExpression:
                case SyntaxKind.TupleType:
                case SyntaxKind.TupleExpression:
                case SyntaxKind.DeclarationExpression:
                case SyntaxKind.RefType:
                case SyntaxKind.RefExpression:
                case SyntaxKind.DeclarationPattern:
1398
                case SyntaxKind.SimpleAssignmentExpression:
1399 1400 1401
                case SyntaxKind.WhenClause:
                case SyntaxKind.SingleVariableDesignation:
                case SyntaxKind.CasePatternSwitchLabel:
1402 1403
                    return node.Span;

1404
                default:
1405
                    throw ExceptionUtilities.UnexpectedValue(kind);
1406 1407 1408 1409 1410 1411 1412 1413
            }
        }

        private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end)
        {
            return TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End);
        }

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal)
        {
            switch (lambda.Kind())
            {
                case SyntaxKind.ParenthesizedLambdaExpression:
                    return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span;

                case SyntaxKind.SimpleLambdaExpression:
                    Debug.Assert(ordinal == 0);
                    return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span;

                case SyntaxKind.AnonymousMethodExpression:
                    return ((AnonymousMethodExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span;

                default:
                    return lambda.Span;
            }
        }

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
        protected override string GetTopLevelDisplayName(SyntaxNode node, EditKind editKind)
        {
            return GetTopLevelDisplayNameImpl(node, editKind);
        }

        protected override string GetStatementDisplayName(SyntaxNode node, EditKind editKind)
        {
            return GetStatementDisplayNameImpl(node);
        }

        protected override string GetLambdaDisplayName(SyntaxNode lambda)
        {
            return GetStatementDisplayNameImpl(lambda);
        }

        // internal for testing
        internal static string GetTopLevelDisplayNameImpl(SyntaxNode node, EditKind editKind)
        {
            switch (node.Kind())
            {
                case SyntaxKind.GlobalStatement:
1454
                    return CSharpFeaturesResources.global_statement;
1455 1456

                case SyntaxKind.ExternAliasDirective:
1457
                    return CSharpFeaturesResources.using_namespace;
1458 1459 1460 1461

                case SyntaxKind.UsingDirective:
                    // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias.
                    // None of these changes are allowed anyways, so let's keep it simple.
1462
                    return CSharpFeaturesResources.using_directive;
1463 1464

                case SyntaxKind.NamespaceDeclaration:
1465
                    return FeaturesResources.namespace_;
1466 1467

                case SyntaxKind.ClassDeclaration:
1468
                    return FeaturesResources.class_;
1469 1470

                case SyntaxKind.StructDeclaration:
1471
                    return CSharpFeaturesResources.struct_;
1472 1473

                case SyntaxKind.InterfaceDeclaration:
1474
                    return FeaturesResources.interface_;
1475 1476

                case SyntaxKind.EnumDeclaration:
1477
                    return FeaturesResources.enum_;
1478 1479

                case SyntaxKind.DelegateDeclaration:
1480
                    return FeaturesResources.delegate_;
1481 1482

                case SyntaxKind.FieldDeclaration:
1483
                    var declaration = (FieldDeclarationSyntax)node;
1484
                    return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field;
1485 1486

                case SyntaxKind.EventFieldDeclaration:
1487
                    return CSharpFeaturesResources.event_field;
1488 1489 1490 1491 1492 1493

                case SyntaxKind.VariableDeclaration:
                case SyntaxKind.VariableDeclarator:
                    return GetTopLevelDisplayNameImpl(node.Parent, editKind);

                case SyntaxKind.MethodDeclaration:
1494
                    return FeaturesResources.method;
1495 1496

                case SyntaxKind.ConversionOperatorDeclaration:
1497
                    return CSharpFeaturesResources.conversion_operator;
1498 1499

                case SyntaxKind.OperatorDeclaration:
1500
                    return FeaturesResources.operator_;
1501 1502

                case SyntaxKind.ConstructorDeclaration:
1503
                    return FeaturesResources.constructor;
1504 1505

                case SyntaxKind.DestructorDeclaration:
1506
                    return CSharpFeaturesResources.destructor;
1507 1508

                case SyntaxKind.PropertyDeclaration:
1509
                    return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_;
1510 1511

                case SyntaxKind.IndexerDeclaration:
1512
                    return CSharpFeaturesResources.indexer;
1513 1514

                case SyntaxKind.EventDeclaration:
1515
                    return FeaturesResources.event_;
1516 1517

                case SyntaxKind.EnumMemberDeclaration:
1518
                    return FeaturesResources.enum_value;
1519 1520 1521 1522

                case SyntaxKind.GetAccessorDeclaration:
                    if (node.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration))
                    {
1523
                        return CSharpFeaturesResources.property_getter;
1524 1525 1526 1527
                    }
                    else
                    {
                        Debug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration));
1528
                        return CSharpFeaturesResources.indexer_getter;
1529 1530 1531 1532 1533
                    }

                case SyntaxKind.SetAccessorDeclaration:
                    if (node.Parent.Parent.IsKind(SyntaxKind.PropertyDeclaration))
                    {
1534
                        return CSharpFeaturesResources.property_setter;
1535 1536 1537 1538
                    }
                    else
                    {
                        Debug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration));
1539
                        return CSharpFeaturesResources.indexer_setter;
1540 1541 1542 1543
                    }

                case SyntaxKind.AddAccessorDeclaration:
                case SyntaxKind.RemoveAccessorDeclaration:
1544
                    return FeaturesResources.event_accessor;
1545 1546

                case SyntaxKind.TypeParameterConstraintClause:
1547
                    return FeaturesResources.type_constraint;
1548 1549 1550

                case SyntaxKind.TypeParameterList:
                case SyntaxKind.TypeParameter:
1551
                    return FeaturesResources.type_parameter;
1552 1553

                case SyntaxKind.Parameter:
1554
                    return FeaturesResources.parameter;
1555 1556

                case SyntaxKind.AttributeList:
1557
                    return (editKind == EditKind.Update) ? CSharpFeaturesResources.attribute_target : FeaturesResources.attribute;
1558 1559

                case SyntaxKind.Attribute:
1560
                    return FeaturesResources.attribute;
1561 1562

                default:
1563
                    throw ExceptionUtilities.UnexpectedValue(node.Kind());
1564 1565 1566 1567 1568 1569 1570 1571 1572
            }
        }

        // internal for testing
        internal static string GetStatementDisplayNameImpl(SyntaxNode node)
        {
            switch (node.Kind())
            {
                case SyntaxKind.TryStatement:
1573
                    return CSharpFeaturesResources.try_block;
1574 1575

                case SyntaxKind.CatchClause:
1576
                case SyntaxKind.CatchDeclaration:
1577
                    return CSharpFeaturesResources.catch_clause;
1578 1579

                case SyntaxKind.CatchFilterClause:
1580
                    return CSharpFeaturesResources.filter_clause;
1581 1582

                case SyntaxKind.FinallyClause:
1583
                    return CSharpFeaturesResources.finally_clause;
1584 1585

                case SyntaxKind.FixedStatement:
1586
                    return CSharpFeaturesResources.fixed_statement;
1587 1588

                case SyntaxKind.UsingStatement:
1589
                    return CSharpFeaturesResources.using_statement;
1590 1591

                case SyntaxKind.LockStatement:
1592
                    return CSharpFeaturesResources.lock_statement;
1593 1594

                case SyntaxKind.ForEachStatement:
1595
                case SyntaxKind.ForEachVariableStatement:
1596
                    return CSharpFeaturesResources.foreach_statement;
1597 1598

                case SyntaxKind.CheckedStatement:
1599
                    return CSharpFeaturesResources.checked_statement;
1600 1601

                case SyntaxKind.UncheckedStatement:
1602
                    return CSharpFeaturesResources.unchecked_statement;
1603 1604 1605

                case SyntaxKind.YieldBreakStatement:
                case SyntaxKind.YieldReturnStatement:
1606
                    return CSharpFeaturesResources.yield_statement;
1607 1608

                case SyntaxKind.AwaitExpression:
1609
                    return CSharpFeaturesResources.await_expression;
1610 1611 1612

                case SyntaxKind.ParenthesizedLambdaExpression:
                case SyntaxKind.SimpleLambdaExpression:
1613
                    return CSharpFeaturesResources.lambda;
1614 1615

                case SyntaxKind.AnonymousMethodExpression:
1616
                    return CSharpFeaturesResources.anonymous_method;
1617 1618

                case SyntaxKind.FromClause:
1619
                    return CSharpFeaturesResources.from_clause;
1620 1621

                case SyntaxKind.JoinClause:
1622
                case SyntaxKind.JoinIntoClause:
1623
                    return CSharpFeaturesResources.join_clause;
1624 1625

                case SyntaxKind.LetClause:
1626
                    return CSharpFeaturesResources.let_clause;
1627 1628

                case SyntaxKind.WhereClause:
1629
                    return CSharpFeaturesResources.where_clause;
1630

1631
                case SyntaxKind.OrderByClause:
1632 1633
                case SyntaxKind.AscendingOrdering:
                case SyntaxKind.DescendingOrdering:
1634
                    return CSharpFeaturesResources.orderby_clause;
1635 1636

                case SyntaxKind.SelectClause:
1637
                    return CSharpFeaturesResources.select_clause;
1638 1639

                case SyntaxKind.GroupClause:
1640
                    return CSharpFeaturesResources.groupby_clause;
1641 1642

                case SyntaxKind.QueryBody:
1643
                    return CSharpFeaturesResources.query_body;
1644 1645

                case SyntaxKind.QueryContinuation:
1646
                    return CSharpFeaturesResources.into_clause;
1647

1648 1649 1650
                case SyntaxKind.IsPatternExpression:
                    return CSharpFeaturesResources.is_pattern;

1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
                case SyntaxKind.SimpleAssignmentExpression:
                    if (((AssignmentExpressionSyntax)node).IsDeconstruction())
                    {
                        return CSharpFeaturesResources.deconstruction;
                    }
                    else
                    {
                        throw ExceptionUtilities.UnexpectedValue(node.Kind());
                    }

1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
                case SyntaxKind.TupleType:
                case SyntaxKind.TupleExpression:
                    return CSharpFeaturesResources.tuple;

                case SyntaxKind.LocalFunctionStatement:
                    return CSharpFeaturesResources.local_function;

                case SyntaxKind.DeclarationExpression:
                    return CSharpFeaturesResources.out_var;

                case SyntaxKind.RefType:
                case SyntaxKind.RefExpression:
                    return CSharpFeaturesResources.ref_local_or_expression;

                case SyntaxKind.SwitchStatement:
                case SyntaxKind.DeclarationPattern:
                    return CSharpFeaturesResources.v7_switch;

1679
                default:
1680
                    throw ExceptionUtilities.UnexpectedValue(node.Kind());
1681 1682 1683 1684 1685 1686 1687 1688 1689
            }
        }

        #endregion

        #region Top-Level Syntactic Rude Edits

        private struct EditClassifier
        {
1690 1691 1692 1693 1694 1695 1696
            private readonly CSharpEditAndContinueAnalyzer _analyzer;
            private readonly List<RudeEditDiagnostic> _diagnostics;
            private readonly Match<SyntaxNode> _match;
            private readonly SyntaxNode _oldNode;
            private readonly SyntaxNode _newNode;
            private readonly EditKind _kind;
            private readonly TextSpan? _span;
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706

            public EditClassifier(
                CSharpEditAndContinueAnalyzer analyzer,
                List<RudeEditDiagnostic> diagnostics,
                SyntaxNode oldNode,
                SyntaxNode newNode,
                EditKind kind,
                Match<SyntaxNode> match = null,
                TextSpan? span = null)
            {
1707 1708 1709 1710 1711 1712 1713
                _analyzer = analyzer;
                _diagnostics = diagnostics;
                _oldNode = oldNode;
                _newNode = newNode;
                _kind = kind;
                _span = span;
                _match = match;
1714 1715 1716 1717
            }

            private void ReportError(RudeEditKind kind, SyntaxNode spanNode = null, SyntaxNode displayNode = null)
            {
1718 1719 1720
                var span = (spanNode != null) ? GetDiagnosticSpanImpl(spanNode, _kind) : GetSpan();
                var node = displayNode ?? _newNode ?? _oldNode;
                var displayName = (displayNode != null) ? GetTopLevelDisplayNameImpl(displayNode, _kind) : GetDisplayName();
1721

1722
                _diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName }));
1723 1724 1725 1726
            }

            private string GetDisplayName()
            {
1727
                return GetTopLevelDisplayNameImpl(_newNode ?? _oldNode, _kind);
1728 1729 1730 1731
            }

            private TextSpan GetSpan()
            {
1732
                if (_span.HasValue)
1733
                {
1734
                    return _span.Value;
1735 1736
                }

1737
                if (_newNode == null)
1738
                {
1739
                    return _analyzer.GetDeletedNodeDiagnosticSpan(_match.Matches, _oldNode);
1740 1741 1742
                }
                else
                {
1743
                    return GetDiagnosticSpanImpl(_newNode, _kind);
1744 1745 1746 1747 1748
                }
            }

            public void ClassifyEdit()
            {
1749
                switch (_kind)
1750 1751
                {
                    case EditKind.Delete:
1752
                        ClassifyDelete(_oldNode);
1753 1754 1755
                        return;

                    case EditKind.Update:
1756
                        ClassifyUpdate(_oldNode, _newNode);
1757 1758 1759
                        return;

                    case EditKind.Move:
1760
                        ClassifyMove(_oldNode, _newNode);
1761 1762 1763
                        return;

                    case EditKind.Insert:
1764
                        ClassifyInsert(_newNode);
1765 1766 1767
                        return;

                    case EditKind.Reorder:
1768
                        ClassifyReorder(_oldNode, _newNode);
1769 1770 1771
                        return;

                    default:
1772
                        throw ExceptionUtilities.UnexpectedValue(_kind);
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
                }
            }

            #region Move and Reorder

            private void ClassifyMove(SyntaxNode oldNode, SyntaxNode newNode)
            {
                // We could perhaps allow moving a type declaration to a different namespace syntax node
                // as long as it represents semantically the same namespace as the one of the original type declaration.
                ReportError(RudeEditKind.Move);
            }

            private void ClassifyReorder(SyntaxNode oldNode, SyntaxNode newNode)
            {
                switch (newNode.Kind())
                {
                    case SyntaxKind.GlobalStatement:
                        // TODO:
                        ReportError(RudeEditKind.Move);
                        return;

                    case SyntaxKind.ExternAliasDirective:
                    case SyntaxKind.UsingDirective:
                    case SyntaxKind.NamespaceDeclaration:
                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.StructDeclaration:
                    case SyntaxKind.InterfaceDeclaration:
                    case SyntaxKind.EnumDeclaration:
                    case SyntaxKind.DelegateDeclaration:
                    case SyntaxKind.VariableDeclaration:
                    case SyntaxKind.MethodDeclaration:
                    case SyntaxKind.ConversionOperatorDeclaration:
                    case SyntaxKind.OperatorDeclaration:
                    case SyntaxKind.ConstructorDeclaration:
                    case SyntaxKind.DestructorDeclaration:
                    case SyntaxKind.IndexerDeclaration:
                    case SyntaxKind.EventDeclaration:
                    case SyntaxKind.GetAccessorDeclaration:
                    case SyntaxKind.SetAccessorDeclaration:
                    case SyntaxKind.AddAccessorDeclaration:
                    case SyntaxKind.RemoveAccessorDeclaration:
                    case SyntaxKind.TypeParameterConstraintClause:
                    case SyntaxKind.AttributeList:
                    case SyntaxKind.Attribute:
                        // We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection.
                        return;

                    case SyntaxKind.PropertyDeclaration:
                    case SyntaxKind.FieldDeclaration:
                    case SyntaxKind.EventFieldDeclaration:
                    case SyntaxKind.VariableDeclarator:
                        // Maybe we could allow changing order of field declarations unless the containing type layout is sequential.
                        ReportError(RudeEditKind.Move);
                        return;

                    case SyntaxKind.EnumMemberDeclaration:
                        // To allow this change we would need to check that values of all fields of the enum 
                        // are preserved, or make sure we can update all method bodies that accessed those that changed.
                        ReportError(RudeEditKind.Move);
                        return;

                    case SyntaxKind.TypeParameter:
                    case SyntaxKind.Parameter:
                        ReportError(RudeEditKind.Move);
                        return;

                    default:
1840
                        throw ExceptionUtilities.UnexpectedValue(newNode.Kind());
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
                }
            }

            #endregion

            #region Insert

            private void ClassifyInsert(SyntaxNode node)
            {
                switch (node.Kind())
                {
                    case SyntaxKind.GlobalStatement:
                        // TODO:
                        ReportError(RudeEditKind.Insert);
                        return;

                    case SyntaxKind.ExternAliasDirective:
                    case SyntaxKind.UsingDirective:
                    case SyntaxKind.NamespaceDeclaration:
                    case SyntaxKind.DestructorDeclaration:
                        ReportError(RudeEditKind.Insert);
                        return;

                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.StructDeclaration:
                        ClassifyTypeWithPossibleExternMembersInsert((TypeDeclarationSyntax)node);
                        return;

                    case SyntaxKind.InterfaceDeclaration:
                    case SyntaxKind.EnumDeclaration:
                    case SyntaxKind.DelegateDeclaration:
                        return;

                    case SyntaxKind.PropertyDeclaration:
                    case SyntaxKind.IndexerDeclaration:
                    case SyntaxKind.EventDeclaration:
                        ClassifyModifiedMemberInsert(((BasePropertyDeclarationSyntax)node).Modifiers);
                        return;

                    case SyntaxKind.ConversionOperatorDeclaration:
                    case SyntaxKind.OperatorDeclaration:
                        ReportError(RudeEditKind.InsertOperator);
                        return;

                    case SyntaxKind.MethodDeclaration:
                        ClassifyMethodInsert((MethodDeclarationSyntax)node);
                        return;

                    case SyntaxKind.ConstructorDeclaration:
                        // Allow adding parameterless constructor.
                        // Semantic analysis will determine if it's an actual addition or 
                        // just an update of an existing implicit constructor.
1893
                        var modifiers = ((BaseMethodDeclarationSyntax)node).Modifiers;
1894 1895
                        if (SyntaxUtilities.IsParameterlessConstructor(node))
                        {
1896 1897 1898 1899 1900 1901
                            // Disallow adding an extern constructor
                            if (modifiers.Any(SyntaxKind.ExternKeyword))
                            {
                                ReportError(RudeEditKind.InsertExtern);
                            }

1902 1903 1904
                            return;
                        }

1905
                        ClassifyModifiedMemberInsert(modifiers);
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
                        return;

                    case SyntaxKind.GetAccessorDeclaration:
                    case SyntaxKind.SetAccessorDeclaration:
                    case SyntaxKind.AddAccessorDeclaration:
                    case SyntaxKind.RemoveAccessorDeclaration:
                        ClassifyAccessorInsert((AccessorDeclarationSyntax)node);
                        return;

                    case SyntaxKind.AccessorList:
                        // an error will be reported for each accessor
                        return;

                    case SyntaxKind.FieldDeclaration:
                    case SyntaxKind.EventFieldDeclaration:
                        // allowed: private fields in classes
                        ClassifyFieldInsert((BaseFieldDeclarationSyntax)node);
                        return;

                    case SyntaxKind.VariableDeclarator:
                        // allowed: private fields in classes
                        ClassifyFieldInsert((VariableDeclaratorSyntax)node);
                        return;

                    case SyntaxKind.VariableDeclaration:
                        // allowed: private fields in classes
                        ClassifyFieldInsert((VariableDeclarationSyntax)node);
                        return;

                    case SyntaxKind.EnumMemberDeclaration:
                    case SyntaxKind.TypeParameter:
                    case SyntaxKind.TypeParameterConstraintClause:
                    case SyntaxKind.TypeParameterList:
                    case SyntaxKind.Parameter:
                    case SyntaxKind.Attribute:
                    case SyntaxKind.AttributeList:
                        ReportError(RudeEditKind.Insert);
                        return;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(node.Kind());
                }
            }

            private bool ClassifyModifiedMemberInsert(SyntaxTokenList modifiers)
            {
                if (modifiers.Any(SyntaxKind.ExternKeyword))
                {
                    ReportError(RudeEditKind.InsertExtern);
                    return false;
                }

                if (modifiers.Any(SyntaxKind.VirtualKeyword) || modifiers.Any(SyntaxKind.AbstractKeyword) || modifiers.Any(SyntaxKind.OverrideKeyword))
                {
                    ReportError(RudeEditKind.InsertVirtual);
                    return false;
                }

                return true;
            }

            private void ClassifyTypeWithPossibleExternMembersInsert(TypeDeclarationSyntax type)
            {
                // extern members are not allowed, even in a new type
                foreach (var member in type.Members)
                {
                    var modifiers = default(SyntaxTokenList);

                    switch (member.Kind())
                    {
                        case SyntaxKind.PropertyDeclaration:
                        case SyntaxKind.IndexerDeclaration:
                        case SyntaxKind.EventDeclaration:
                            modifiers = ((BasePropertyDeclarationSyntax)member).Modifiers;
                            break;

                        case SyntaxKind.ConversionOperatorDeclaration:
                        case SyntaxKind.OperatorDeclaration:
                        case SyntaxKind.MethodDeclaration:
                        case SyntaxKind.ConstructorDeclaration:
                            modifiers = ((BaseMethodDeclarationSyntax)member).Modifiers;
                            break;
                    }

                    if (modifiers.Any(SyntaxKind.ExternKeyword))
                    {
                        ReportError(RudeEditKind.InsertExtern, member, member);
                    }
                }
            }

            private void ClassifyMethodInsert(MethodDeclarationSyntax method)
            {
                ClassifyModifiedMemberInsert(method.Modifiers);

                if (method.Arity > 0)
                {
                    ReportError(RudeEditKind.InsertGenericMethod);
                }
            }

            private void ClassifyAccessorInsert(AccessorDeclarationSyntax accessor)
            {
                var baseProperty = (BasePropertyDeclarationSyntax)accessor.Parent.Parent;
                ClassifyModifiedMemberInsert(baseProperty.Modifiers);
            }

            private void ClassifyFieldInsert(BaseFieldDeclarationSyntax field)
            {
                ClassifyModifiedMemberInsert(field.Modifiers);
            }

            private void ClassifyFieldInsert(VariableDeclaratorSyntax fieldVariable)
            {
                ClassifyFieldInsert((VariableDeclarationSyntax)fieldVariable.Parent);
            }

            private void ClassifyFieldInsert(VariableDeclarationSyntax fieldVariable)
            {
                ClassifyFieldInsert((BaseFieldDeclarationSyntax)fieldVariable.Parent);
            }

            #endregion

            #region Delete

            private void ClassifyDelete(SyntaxNode oldNode)
            {
                switch (oldNode.Kind())
                {
                    case SyntaxKind.GlobalStatement:
                        // TODO:
                        ReportError(RudeEditKind.Delete);
                        return;

                    case SyntaxKind.ExternAliasDirective:
                    case SyntaxKind.UsingDirective:
                    case SyntaxKind.NamespaceDeclaration:
                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.StructDeclaration:
                    case SyntaxKind.InterfaceDeclaration:
                    case SyntaxKind.EnumDeclaration:
                    case SyntaxKind.DelegateDeclaration:
                    case SyntaxKind.MethodDeclaration:
                    case SyntaxKind.ConversionOperatorDeclaration:
                    case SyntaxKind.OperatorDeclaration:
                    case SyntaxKind.DestructorDeclaration:
                    case SyntaxKind.PropertyDeclaration:
                    case SyntaxKind.IndexerDeclaration:
                    case SyntaxKind.EventDeclaration:
                    case SyntaxKind.FieldDeclaration:
                    case SyntaxKind.EventFieldDeclaration:
                    case SyntaxKind.VariableDeclarator:
                    case SyntaxKind.VariableDeclaration:
                        // To allow removal of declarations we would need to update method bodies that 
                        // were previously binding to them but now are binding to another symbol that was previously hidden.
                        ReportError(RudeEditKind.Delete);
                        return;

                    case SyntaxKind.ConstructorDeclaration:
                        // Allow deletion of a parameterless constructor.
                        // Semantic analysis reports an error if the parameterless ctor isn't replaced by a default ctor.
                        if (!SyntaxUtilities.IsParameterlessConstructor(oldNode))
                        {
                            ReportError(RudeEditKind.Delete);
                        }

                        return;

                    case SyntaxKind.GetAccessorDeclaration:
                    case SyntaxKind.SetAccessorDeclaration:
                    case SyntaxKind.AddAccessorDeclaration:
                    case SyntaxKind.RemoveAccessorDeclaration:
                        // An accessor can be removed. Accessors are not hiding other symbols.
                        // If the new compilation still uses the removed accessor a semantic error will be reported.
                        // For simplicity though we disallow deletion of accessors for now. 
                        // The compiler would need to remember that the accessor has been deleted,
                        // so that its addition back is interpreted as an update. 
                        // Additional issues might involve changing accessibility of the accessor.
                        ReportError(RudeEditKind.Delete);
                        return;

                    case SyntaxKind.AccessorList:
                        Debug.Assert(
                            oldNode.Parent.IsKind(SyntaxKind.PropertyDeclaration) ||
                            oldNode.Parent.IsKind(SyntaxKind.IndexerDeclaration));

                        var accessorList = (AccessorListSyntax)oldNode;
                        var setter = accessorList.Accessors.FirstOrDefault(a => a.IsKind(SyntaxKind.SetAccessorDeclaration));
                        if (setter != null)
                        {
                            ReportError(RudeEditKind.Delete, accessorList.Parent, setter);
                        }

                        return;

                    case SyntaxKind.AttributeList:
                    case SyntaxKind.Attribute:
                        // To allow removal of attributes we would need to check if the removed attribute
                        // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute
                        // that affects the generated IL.
                        ReportError(RudeEditKind.Delete);
                        return;

                    case SyntaxKind.EnumMemberDeclaration:
                        // We could allow removing enum member if it didn't affect the values of other enum members.
                        // If the updated compilation binds without errors it means that the enum value wasn't used.
                        ReportError(RudeEditKind.Delete);
                        return;

                    case SyntaxKind.TypeParameter:
                    case SyntaxKind.TypeParameterList:
                    case SyntaxKind.Parameter:
                    case SyntaxKind.ParameterList:
                    case SyntaxKind.TypeParameterConstraintClause:
                        ReportError(RudeEditKind.Delete);
                        return;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(oldNode.Kind());
                }
            }

            #endregion

            #region Update

            private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode)
            {
                switch (newNode.Kind())
                {
                    case SyntaxKind.GlobalStatement:
                        ReportError(RudeEditKind.Update);
                        return;

                    case SyntaxKind.ExternAliasDirective:
                        ReportError(RudeEditKind.Update);
                        return;

                    case SyntaxKind.UsingDirective:
                        // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias.
                        // None of these changes are allowed anyways, so let's keep it simple.
                        ReportError(RudeEditKind.Update);
                        return;

                    case SyntaxKind.NamespaceDeclaration:
                        ClassifyUpdate((NamespaceDeclarationSyntax)oldNode, (NamespaceDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.StructDeclaration:
                    case SyntaxKind.InterfaceDeclaration:
                        ClassifyUpdate((TypeDeclarationSyntax)oldNode, (TypeDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.EnumDeclaration:
                        ClassifyUpdate((EnumDeclarationSyntax)oldNode, (EnumDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.DelegateDeclaration:
                        ClassifyUpdate((DelegateDeclarationSyntax)oldNode, (DelegateDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.FieldDeclaration:
                        ClassifyUpdate((BaseFieldDeclarationSyntax)oldNode, (BaseFieldDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.EventFieldDeclaration:
                        ClassifyUpdate((BaseFieldDeclarationSyntax)oldNode, (BaseFieldDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.VariableDeclaration:
                        ClassifyUpdate((VariableDeclarationSyntax)oldNode, (VariableDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.VariableDeclarator:
                        ClassifyUpdate((VariableDeclaratorSyntax)oldNode, (VariableDeclaratorSyntax)newNode);
                        return;

                    case SyntaxKind.MethodDeclaration:
                        ClassifyUpdate((MethodDeclarationSyntax)oldNode, (MethodDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.ConversionOperatorDeclaration:
                        ClassifyUpdate((ConversionOperatorDeclarationSyntax)oldNode, (ConversionOperatorDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.OperatorDeclaration:
                        ClassifyUpdate((OperatorDeclarationSyntax)oldNode, (OperatorDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.ConstructorDeclaration:
                        ClassifyUpdate((ConstructorDeclarationSyntax)oldNode, (ConstructorDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.DestructorDeclaration:
                        ClassifyUpdate((DestructorDeclarationSyntax)oldNode, (DestructorDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.PropertyDeclaration:
                        ClassifyUpdate((PropertyDeclarationSyntax)oldNode, (PropertyDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.IndexerDeclaration:
                        ClassifyUpdate((IndexerDeclarationSyntax)oldNode, (IndexerDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.EventDeclaration:
                        return;

                    case SyntaxKind.EnumMemberDeclaration:
                        ClassifyUpdate((EnumMemberDeclarationSyntax)oldNode, (EnumMemberDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.GetAccessorDeclaration:
                    case SyntaxKind.SetAccessorDeclaration:
                    case SyntaxKind.AddAccessorDeclaration:
                    case SyntaxKind.RemoveAccessorDeclaration:
                        ClassifyUpdate((AccessorDeclarationSyntax)oldNode, (AccessorDeclarationSyntax)newNode);
                        return;

                    case SyntaxKind.TypeParameterConstraintClause:
                        ClassifyUpdate((TypeParameterConstraintClauseSyntax)oldNode, (TypeParameterConstraintClauseSyntax)newNode);
                        return;

                    case SyntaxKind.TypeParameter:
                        ClassifyUpdate((TypeParameterSyntax)oldNode, (TypeParameterSyntax)newNode);
                        return;

                    case SyntaxKind.Parameter:
                        ClassifyUpdate((ParameterSyntax)oldNode, (ParameterSyntax)newNode);
                        return;

                    case SyntaxKind.AttributeList:
                        ClassifyUpdate((AttributeListSyntax)oldNode, (AttributeListSyntax)newNode);
                        return;

                    case SyntaxKind.Attribute:
                        // Dev12 reports "Rename" if the attribute type name is changed. 
                        // But such update is actually not renaming the attribute, it's changing what attribute is applied.
                        ReportError(RudeEditKind.Update);
                        return;

                    case SyntaxKind.TypeParameterList:
                    case SyntaxKind.ParameterList:
                    case SyntaxKind.BracketedParameterList:
                    case SyntaxKind.AccessorList:
                        return;

                    default:
2256
                        throw ExceptionUtilities.UnexpectedValue(newNode.Kind());
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
                }
            }

            private void ClassifyUpdate(NamespaceDeclarationSyntax oldNode, NamespaceDeclarationSyntax newNode)
            {
                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name));
                ReportError(RudeEditKind.Renamed);
            }

            private void ClassifyUpdate(TypeDeclarationSyntax oldNode, TypeDeclarationSyntax newNode)
            {
                if (oldNode.Kind() != newNode.Kind())
                {
                    ReportError(RudeEditKind.TypeKindUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.BaseList, newNode.BaseList));
                ReportError(RudeEditKind.BaseTypeOrInterfaceUpdate);
            }

            private void ClassifyUpdate(EnumDeclarationSyntax oldNode, EnumDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.BaseList, newNode.BaseList))
                {
                    ReportError(RudeEditKind.EnumUnderlyingTypeUpdate);
                    return;
                }

                // The list of members has been updated (separators added).
                // We report a Rude Edit for each updated member.
            }

            private void ClassifyUpdate(DelegateDeclarationSyntax oldNode, DelegateDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.ReturnType, newNode.ReturnType))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier));
                ReportError(RudeEditKind.Renamed);
            }

            private void ClassifyUpdate(BaseFieldDeclarationSyntax oldNode, BaseFieldDeclarationSyntax newNode)
            {
                if (oldNode.Kind() != newNode.Kind())
                {
                    ReportError(RudeEditKind.FieldKindUpdate);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers));
                ReportError(RudeEditKind.ModifiersUpdate);
                return;
            }

            private void ClassifyUpdate(VariableDeclarationSyntax oldNode, VariableDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                // separators may be added/removed:
            }

            private void ClassifyUpdate(VariableDeclaratorSyntax oldNode, VariableDeclaratorSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                // If the argument lists are mismatched the field must have mismatched "fixed" modifier, 
                // which is reported by the field declaration.
                if ((oldNode.ArgumentList == null) == (newNode.ArgumentList == null))
                {
                    if (!SyntaxFactory.AreEquivalent(oldNode.ArgumentList, newNode.ArgumentList))
                    {
                        ReportError(RudeEditKind.FixedSizeFieldUpdate);
                        return;
                    }
                }

                var typeDeclaration = (TypeDeclarationSyntax)oldNode.Parent.Parent.Parent;
                if (typeDeclaration.Arity > 0)
                {
                    ReportError(RudeEditKind.GenericTypeInitializerUpdate);
                    return;
                }

2382
                // Check if a constant field is updated:
2383 2384
                var fieldDeclaration = (FieldDeclarationSyntax)oldNode.Parent.Parent;
                if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword))
2385 2386 2387 2388 2389
                {
                    ReportError(RudeEditKind.Update);
                    return;
                }

2390
                ClassifyDeclarationBodyRudeUpdates(newNode);
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
            }

            private void ClassifyUpdate(MethodDeclarationSyntax oldNode, MethodDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                if (!ClassifyMethodModifierUpdate(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.ReturnType, newNode.ReturnType))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.ExplicitInterfaceSpecifier, newNode.ExplicitInterfaceSpecifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                ClassifyMethodBodyRudeUpdate(
                    (SyntaxNode)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
                    (SyntaxNode)newNode.Body ?? newNode.ExpressionBody?.Expression,
                    containingMethodOpt: newNode,
2423
                    containingType: (TypeDeclarationSyntax)newNode.Parent);
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
            }

            private bool ClassifyMethodModifierUpdate(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers)
            {
                var oldAsyncIndex = oldModifiers.IndexOf(SyntaxKind.AsyncKeyword);
                var newAsyncIndex = newModifiers.IndexOf(SyntaxKind.AsyncKeyword);

                if (oldAsyncIndex >= 0)
                {
                    oldModifiers = oldModifiers.RemoveAt(oldAsyncIndex);
                }

                if (newAsyncIndex >= 0)
                {
                    newModifiers = newModifiers.RemoveAt(newAsyncIndex);
                }

2441 2442 2443 2444 2445 2446
                // 'async' keyword is allowed to add, but not to remove.
                if (oldAsyncIndex >= 0 && newAsyncIndex < 0)
                {
                    return false;
                }

2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
                return SyntaxFactory.AreEquivalent(oldModifiers, newModifiers);
            }

            private void ClassifyUpdate(ConversionOperatorDeclarationSyntax oldNode, ConversionOperatorDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.ImplicitOrExplicitKeyword, newNode.ImplicitOrExplicitKeyword))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                ClassifyMethodBodyRudeUpdate(
                    (SyntaxNode)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
                    (SyntaxNode)newNode.Body ?? newNode.ExpressionBody?.Expression,
                    containingMethodOpt: null,
2474
                    containingType: (TypeDeclarationSyntax)newNode.Parent);
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
            }

            private void ClassifyUpdate(OperatorDeclarationSyntax oldNode, OperatorDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.OperatorToken, newNode.OperatorToken))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.ReturnType, newNode.ReturnType))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                ClassifyMethodBodyRudeUpdate(
                    (SyntaxNode)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
                    (SyntaxNode)newNode.Body ?? newNode.ExpressionBody?.Expression,
                    containingMethodOpt: null,
2501
                    containingType: (TypeDeclarationSyntax)newNode.Parent);
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
            }

            private void ClassifyUpdate(AccessorDeclarationSyntax oldNode, AccessorDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (oldNode.Kind() != newNode.Kind())
                {
                    ReportError(RudeEditKind.AccessorKindUpdate);
                    return;
                }

                Debug.Assert(newNode.Parent is AccessorListSyntax);
                Debug.Assert(newNode.Parent.Parent is BasePropertyDeclarationSyntax);

                ClassifyMethodBodyRudeUpdate(
2522 2523
                    (SyntaxNode)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
                    (SyntaxNode)newNode.Body ?? newNode.ExpressionBody?.Expression,
2524
                    containingMethodOpt: null,
2525
                    containingType: (TypeDeclarationSyntax)newNode.Parent.Parent.Parent);
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548
            }

            private void ClassifyUpdate(EnumMemberDeclarationSyntax oldNode, EnumMemberDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.EqualsValue, newNode.EqualsValue));
                ReportError(RudeEditKind.InitializerUpdate);
            }

            private void ClassifyUpdate(ConstructorDeclarationSyntax oldNode, ConstructorDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                ClassifyMethodBodyRudeUpdate(
2549 2550
                    (SyntaxNode)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
                    (SyntaxNode)newNode.Body ?? newNode.ExpressionBody?.Expression,
2551
                    containingMethodOpt: null,
2552
                    containingType: (TypeDeclarationSyntax)newNode.Parent);
2553 2554 2555 2556 2557
            }

            private void ClassifyUpdate(DestructorDeclarationSyntax oldNode, DestructorDeclarationSyntax newNode)
            {
                ClassifyMethodBodyRudeUpdate(
2558 2559
                    (SyntaxNode)oldNode.Body ?? oldNode.ExpressionBody?.Expression,
                    (SyntaxNode)newNode.Body ?? newNode.ExpressionBody?.Expression,
2560
                    containingMethodOpt: null,
2561
                    containingType: (TypeDeclarationSyntax)newNode.Parent);
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
            }

            private void ClassifyUpdate(PropertyDeclarationSyntax oldNode, PropertyDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.ExplicitInterfaceSpecifier, newNode.ExplicitInterfaceSpecifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                var containingType = (TypeDeclarationSyntax)newNode.Parent;

                // TODO: We currently don't support switching from auto-props to properties with accessors and vice versa.
                // If we do we should also allow it for expression bodies.

                if (!SyntaxFactory.AreEquivalent(oldNode.ExpressionBody, newNode.ExpressionBody))
                {
                    var oldBody = SyntaxUtilities.TryGetEffectiveGetterBody(oldNode.ExpressionBody, oldNode.AccessorList);
                    var newBody = SyntaxUtilities.TryGetEffectiveGetterBody(newNode.ExpressionBody, newNode.AccessorList);

                    ClassifyMethodBodyRudeUpdate(
2601 2602 2603
                        oldBody,
                        newBody,
                        containingMethodOpt: null,
2604
                        containingType: containingType);
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618

                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Initializer, newNode.Initializer));

                if (containingType.Arity > 0)
                {
                    ReportError(RudeEditKind.GenericTypeInitializerUpdate);
                    return;
                }

                if (newNode.Initializer != null)
                {
2619
                    ClassifyDeclarationBodyRudeUpdates(newNode.Initializer);
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
                }
            }

            private void ClassifyUpdate(IndexerDeclarationSyntax oldNode, IndexerDeclarationSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.ExplicitInterfaceSpecifier, newNode.ExplicitInterfaceSpecifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.ExpressionBody, newNode.ExpressionBody));

                var oldBody = SyntaxUtilities.TryGetEffectiveGetterBody(oldNode.ExpressionBody, oldNode.AccessorList);
                var newBody = SyntaxUtilities.TryGetEffectiveGetterBody(newNode.ExpressionBody, newNode.AccessorList);

                ClassifyMethodBodyRudeUpdate(
2649 2650 2651
                    oldBody,
                    newBody,
                    containingMethodOpt: null,
2652
                    containingType: (TypeDeclarationSyntax)newNode.Parent);
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
            }

            private void ClassifyUpdate(TypeParameterSyntax oldNode, TypeParameterSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.VarianceKeyword, newNode.VarianceKeyword));
                ReportError(RudeEditKind.VarianceUpdate);
            }

            private void ClassifyUpdate(TypeParameterConstraintClauseSyntax oldNode, TypeParameterConstraintClauseSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Constraints, newNode.Constraints));
                ReportError(RudeEditKind.TypeUpdate);
            }

            private void ClassifyUpdate(ParameterSyntax oldNode, ParameterSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Identifier, newNode.Identifier))
                {
                    ReportError(RudeEditKind.Renamed);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Modifiers, newNode.Modifiers))
                {
                    ReportError(RudeEditKind.ModifiersUpdate);
                    return;
                }

                if (!SyntaxFactory.AreEquivalent(oldNode.Type, newNode.Type))
                {
                    ReportError(RudeEditKind.TypeUpdate);
                    return;
                }

                Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Default, newNode.Default));
                ReportError(RudeEditKind.InitializerUpdate);
            }

            private void ClassifyUpdate(AttributeListSyntax oldNode, AttributeListSyntax newNode)
            {
                if (!SyntaxFactory.AreEquivalent(oldNode.Target, newNode.Target))
                {
                    ReportError(RudeEditKind.Update);
                    return;
                }

                // changes in attribute separators are not interesting:
            }

            private void ClassifyMethodBodyRudeUpdate(
                SyntaxNode oldBody,
                SyntaxNode newBody,
                MethodDeclarationSyntax containingMethodOpt,
2718
                TypeDeclarationSyntax containingType)
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
            {
                Debug.Assert(oldBody is BlockSyntax || oldBody is ExpressionSyntax || oldBody == null);
                Debug.Assert(newBody is BlockSyntax || newBody is ExpressionSyntax || newBody == null);

                if ((oldBody == null) != (newBody == null))
                {
                    if (oldBody == null)
                    {
                        ReportError(RudeEditKind.MethodBodyAdd);
                        return;
                    }
                    else
                    {
                        ReportError(RudeEditKind.MethodBodyDelete);
                        return;
                    }
                }

                ClassifyMemberBodyRudeUpdate(containingMethodOpt, containingType, isTriviaUpdate: false);

                if (newBody != null)
                {
2741
                    ClassifyDeclarationBodyRudeUpdates(newBody);
2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
                }
            }

            public void ClassifyMemberBodyRudeUpdate(
                MethodDeclarationSyntax containingMethodOpt,
                TypeDeclarationSyntax containingTypeOpt,
                bool isTriviaUpdate)
            {
                if (SyntaxUtilities.Any(containingMethodOpt?.TypeParameterList))
                {
                    ReportError(isTriviaUpdate ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericMethodUpdate);
                    return;
                }

                if (SyntaxUtilities.Any(containingTypeOpt?.TypeParameterList))
                {
                    ReportError(isTriviaUpdate ? RudeEditKind.GenericTypeTriviaUpdate : RudeEditKind.GenericTypeUpdate);
                    return;
                }
            }

2763
            public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody)
2764 2765 2766 2767 2768 2769
            {
                foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(ChildrenCompiledInBody))
                {
                    switch (node.Kind())
                    {
                        case SyntaxKind.StackAllocArrayCreationExpression:
2770
                            ReportError(RudeEditKind.StackAllocUpdate, node, _newNode);
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
                            return;
                    }
                }
            }

            private static bool ChildrenCompiledInBody(SyntaxNode node)
            {
                return node.Kind() != SyntaxKind.ParenthesizedLambdaExpression
                    && node.Kind() != SyntaxKind.SimpleLambdaExpression;
            }

            #endregion
        }

        internal override void ReportSyntacticRudeEdits(
            List<RudeEditDiagnostic> diagnostics,
            Match<SyntaxNode> match,
            Edit<SyntaxNode> edit,
            Dictionary<SyntaxNode, EditKind> editMap)
        {
            if (HasParentEdit(editMap, edit))
            {
                return;
            }

            var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match);
            classifier.ClassifyEdit();
        }

        internal override void ReportMemberUpdateRudeEdits(List<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span)
        {
            var classifier = new EditClassifier(this, diagnostics, null, newMember, EditKind.Update, span: span);

            classifier.ClassifyMemberBodyRudeUpdate(
                newMember as MethodDeclarationSyntax,
                newMember.FirstAncestorOrSelf<TypeDeclarationSyntax>(),
                isTriviaUpdate: true);

2809
            classifier.ClassifyDeclarationBodyRudeUpdates(newMember);
2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
        }

        #endregion

        #region Semantic Rude Edits

        internal override void ReportInsertedMemberSymbolRudeEdits(List<RudeEditDiagnostic> diagnostics, ISymbol newSymbol)
        {
            // We rejected all exported methods during syntax analysis, so no additional work is needed here.
        }

        #endregion

        #region Exception Handling Rude Edits

        protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isLeaf)
        {
            var result = new List<SyntaxNode>();

            while (node != null)
            {
                var kind = node.Kind();

                switch (kind)
                {
                    case SyntaxKind.TryStatement:
                        if (!isLeaf)
                        {
                            result.Add(node);
                        }

                        break;

                    case SyntaxKind.CatchClause:
                    case SyntaxKind.FinallyClause:
                        result.Add(node);

                        // skip try:
                        Debug.Assert(node.Parent.Kind() == SyntaxKind.TryStatement);
                        node = node.Parent;

                        break;

                    // stop at type declaration:
                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.StructDeclaration:
                        return result;
                }

                // stop at lambda:
2860
                if (LambdaUtilities.IsLambda(node))
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
                {
                    return result;
                }

                node = node.Parent;
            }

            return result;
        }

        internal override void ReportEnclosingExceptionHandlingRudeEdits(
            List<RudeEditDiagnostic> diagnostics,
            IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits,
            SyntaxNode oldStatement,
2875
            TextSpan newStatementSpan)
2876 2877 2878 2879 2880 2881 2882 2883
        {
            foreach (var edit in exceptionHandlingEdits)
            {
                // try/catch/finally have distinct labels so only the nodes of the same kind may match:
                Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind);

                if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode))
                {
2884
                    AddRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan);
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951
                }
            }
        }

        private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode)
        {
            switch (oldNode.Kind())
            {
                case SyntaxKind.TryStatement:
                    var oldTryStatement = (TryStatementSyntax)oldNode;
                    var newTryStatement = (TryStatementSyntax)newNode;
                    return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally)
                        && SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches);

                case SyntaxKind.CatchClause:
                case SyntaxKind.FinallyClause:
                    return SyntaxFactory.AreEquivalent(oldNode, newNode);

                default:
                    throw ExceptionUtilities.UnexpectedValue(oldNode.Kind());
            }
        }

        /// <summary>
        /// An active statement (leaf or not) inside a "catch" makes the catch block read-only.
        /// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only.
        /// An active statement (non leaf)    inside a "try" makes the catch/finally block read-only.
        /// </summary>
        protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren)
        {
            TryStatementSyntax tryStatement;
            switch (node.Kind())
            {
                case SyntaxKind.TryStatement:
                    tryStatement = (TryStatementSyntax)node;
                    coversAllChildren = false;

                    if (tryStatement.Catches.Count == 0)
                    {
                        Debug.Assert(tryStatement.Finally != null);
                        return tryStatement.Finally.Span;
                    }

                    return TextSpan.FromBounds(
                        tryStatement.Catches.First().SpanStart,
                        (tryStatement.Finally != null) ?
                            tryStatement.Finally.Span.End :
                            tryStatement.Catches.Last().Span.End);

                case SyntaxKind.CatchClause:
                    coversAllChildren = true;
                    return node.Span;

                case SyntaxKind.FinallyClause:
                    coversAllChildren = true;
                    tryStatement = (TryStatementSyntax)node.Parent;
                    return tryStatement.Span;

                default:
                    throw ExceptionUtilities.UnexpectedValue(node.Kind());
            }
        }

        #endregion

        #region State Machines

2952 2953 2954 2955 2956 2957
        internal override bool IsStateMachineMethod(SyntaxNode declaration)
        {
            return SyntaxUtilities.IsAsyncMethodOrLambda(declaration) ||
                   SyntaxUtilities.IsIteratorMethod(declaration);
        }

2958
        protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKind kind)
2959 2960 2961
        {
            if (SyntaxUtilities.IsAsyncMethodOrLambda(body.Parent))
            {
2962 2963
                suspensionPoints = SyntaxUtilities.GetAwaitExpressions(body);
                kind = StateMachineKind.Async;
2964
            }
2965 2966 2967 2968 2969
            else
            {
                suspensionPoints = SyntaxUtilities.GetYieldStatements(body);
                kind = suspensionPoints.IsEmpty ? StateMachineKind.None : StateMachineKind.Iterator;
            }
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
        }

        internal override void ReportStateMachineSuspensionPointRudeEdits(List<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode)
        {
            // TODO: changes around suspension points (foreach, lock, using, etc.)

            if (oldNode.RawKind != newNode.RawKind)
            {
                Debug.Assert(oldNode is YieldStatementSyntax && newNode is YieldStatementSyntax);

                // changing yield return to yield break
                diagnostics.Add(new RudeEditDiagnostic(
                    RudeEditKind.Update,
                    newNode.Span,
                    newNode,
                    new[] { GetStatementDisplayName(newNode, EditKind.Update) }));
            }
            else if (newNode.IsKind(SyntaxKind.AwaitExpression))
            {
                var oldContainingStatementPart = FindContainingStatementPart(oldNode);
                var newContainingStatementPart = FindContainingStatementPart(newNode);

C
Charles Stoner 已提交
2992
                // If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state.
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
                if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) &&
                    !HasNoSpilledState(newNode, newContainingStatementPart))
                {
                    diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span));
                }
            }
        }

        private static SyntaxNode FindContainingStatementPart(SyntaxNode node)
        {
            while (true)
            {
                var statement = node as StatementSyntax;
                if (statement != null)
                {
                    return statement;
                }

                switch (node.Parent.Kind())
                {
                    case SyntaxKind.ForStatement:
                    case SyntaxKind.ForEachStatement:
                    case SyntaxKind.IfStatement:
                    case SyntaxKind.WhileStatement:
                    case SyntaxKind.DoStatement:
                    case SyntaxKind.SwitchStatement:
                    case SyntaxKind.LockStatement:
                    case SyntaxKind.UsingStatement:
                    case SyntaxKind.ArrowExpressionClause:
                        return node;
                }

3025
                if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node))
3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
                {
                    return node;
                }

                node = node.Parent;
            }
        }

        private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart)
        {
            Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression));

            // There is nothing within the statement part surrounding the await expression.
            if (containingStatementPart == awaitExpression)
            {
                return true;
            }

            switch (containingStatementPart.Kind())
            {
                case SyntaxKind.ExpressionStatement:
                case SyntaxKind.ReturnStatement:
                    var expression = GetExpressionFromStatementPart(containingStatementPart);

                    // await expr;
                    // return await expr;
                    if (expression == awaitExpression)
                    {
                        return true;
                    }

                    // identifier = await expr; 
                    // return identifier = await expr; 
                    return IsSimpleAwaitAssignment(expression, awaitExpression);

                case SyntaxKind.VariableDeclaration:
                    // var idf = await expr in using, for, etc.
                    // EqualsValueClause -> VariableDeclarator -> VariableDeclaration
                    return awaitExpression.Parent.Parent.Parent == containingStatementPart;

                case SyntaxKind.LocalDeclarationStatement:
                    // var idf = await expr;
                    // EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement
                    return awaitExpression.Parent.Parent.Parent.Parent == containingStatementPart;
            }

            return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression);
        }

        private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement)
        {
            switch (statement.Kind())
            {
                case SyntaxKind.ExpressionStatement:
                    return ((ExpressionStatementSyntax)statement).Expression;

                case SyntaxKind.ReturnStatement:
                    return ((ReturnStatementSyntax)statement).Expression;

                default:
3086
                    throw ExceptionUtilities.UnexpectedValue(statement.Kind());
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111
            }
        }

        private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression)
        {
            if (node.IsKind(SyntaxKind.SimpleAssignmentExpression))
            {
                var assignment = (AssignmentExpressionSyntax)node;
                return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression;
            }

            return false;
        }

        #endregion

        #region Rude Edits around Active Statement

        internal override void ReportOtherRudeEditsAroundActiveStatement(
            List<RudeEditDiagnostic> diagnostics,
            Match<SyntaxNode> match,
            SyntaxNode oldActiveStatement,
            SyntaxNode newActiveStatement,
            bool isLeaf)
        {
3112
            ReportRudeEditsForUnsupportedCSharp7EnC(diagnostics, match);
3113 3114 3115 3116
            ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement, isLeaf);
            ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isLeaf);
        }

3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
        /// <summary>
        /// If either trees (after or before the edit) contain unsupported C# 7 features around the active statement, report it.
        /// </summary>
        private void ReportRudeEditsForUnsupportedCSharp7EnC(List<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match)
        {
            SyntaxNode foundCSharp7Syntax = match.NewRoot.DescendantNodesAndSelf().FirstOrDefault(n => IsUnsupportedCSharp7EnCNode(n));
            if (foundCSharp7Syntax != null)
            {
                AddRudeUpdateAroundActiveStatement(diagnostics, foundCSharp7Syntax);
                return;
            }

            foundCSharp7Syntax = match.OldRoot.DescendantNodesAndSelf().FirstOrDefault(n => IsUnsupportedCSharp7EnCNode(n));
            if (foundCSharp7Syntax != null)
            {
                AddRudeUpdateInCSharp7Method(diagnostics, foundCSharp7Syntax);
            }
        }

        /// <summary>
        /// If the active method used unsupported C# 7 features before the edit, it needs to be reported.
        /// </summary>
        private void AddRudeUpdateInCSharp7Method(List<RudeEditDiagnostic> diagnostics, SyntaxNode oldCSharp7Syntax)
        {
            diagnostics.Add(new RudeEditDiagnostic(
                RudeEditKind.UpdateAroundActiveStatement,
                default(TextSpan), // no span since the offending node is in the old syntax
                oldCSharp7Syntax,
                new[] { GetStatementDisplayName(oldCSharp7Syntax, EditKind.Update) }));
        }

        private static bool IsUnsupportedCSharp7EnCNode(SyntaxNode n)
        {
            switch (n.Kind())
            {
                case SyntaxKind.LocalFunctionStatement:
                    return true;
                default:
                    return false;
            }
        }

3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190
        private void ReportRudeEditsForCheckedStatements(
            List<RudeEditDiagnostic> diagnostics,
            SyntaxNode oldActiveStatement,
            SyntaxNode newActiveStatement,
            bool isLeaf)
        {
            // checked context can be changed around leaf active statement:
            if (isLeaf)
            {
                return;
            }

            // Changing checked context around an internal active statement may change the instructions
            // executed after method calls in the active statement but before the next sequence point.
            // Since the debugger remaps the IP at the first sequence point following a call instruction
            // allowing overflow context to be changed may lead to execution of code with old semantics.

            var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement);
            var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement);

            bool isRude;
            if (oldCheckedStatement == null || newCheckedStatement == null)
            {
                isRude = oldCheckedStatement != newCheckedStatement;
            }
            else
            {
                isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind();
            }

            if (isRude)
            {
3191
                AddRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span);
3192 3193 3194 3195 3196
            }
        }

        private static CheckedStatementSyntax TryGetCheckedStatementAncestor(SyntaxNode node)
        {
3197
            // Ignoring lambda boundaries since checked context flows through.
3198 3199 3200 3201 3202 3203 3204 3205 3206

            while (node != null)
            {
                switch (node.Kind())
                {
                    case SyntaxKind.CheckedStatement:
                    case SyntaxKind.UncheckedStatement:
                        return (CheckedStatementSyntax)node;
                }
3207

3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
                node = node.Parent;
            }

            return null;
        }

        private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps(
            List<RudeEditDiagnostic> diagnostics,
            Match<SyntaxNode> match,
            SyntaxNode oldActiveStatement,
            SyntaxNode newActiveStatement,
            bool isLeaf)
        {
            // Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement.
            // Although such changes are technically possible, they might lead to confusion since 
            // the temporary variables these statements generate won't be properly initialized.
            //
            // We use a simple algorithm to match each new node with its old counterpart.
            // If all nodes match this algorithm is linear, otherwise it's quadratic.
            // 
            // Unlike exception regions matching where we use LCS, we allow reordering of the statements.

3230
            ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, new[] { (int)SyntaxKind.LockStatement }, oldActiveStatement, newActiveStatement,
3231 3232 3233
                areEquivalent: AreEquivalentActiveStatements,
                areSimilar: null);

3234
            ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, new[] { (int)SyntaxKind.FixedStatement }, oldActiveStatement, newActiveStatement,
3235 3236 3237
                areEquivalent: AreEquivalentActiveStatements,
                areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables));

3238
            ReportUnmatchedStatements<UsingStatementSyntax>(diagnostics, match, new[] { (int)SyntaxKind.UsingStatement }, oldActiveStatement, newActiveStatement,
3239 3240 3241 3242 3243 3244 3245
                areEquivalent: AreEquivalentActiveStatements,
                areSimilar: (using1, using2) =>
                {
                    return using1.Declaration != null && using2.Declaration != null &&
                        DeclareSameIdentifiers(using1.Declaration.Variables, using2.Declaration.Variables);
                });

3246
            ReportUnmatchedStatements<CommonForEachStatementSyntax>(diagnostics, match, new[] { (int)SyntaxKind.ForEachStatement, (int)SyntaxKind.ForEachVariableStatement }, oldActiveStatement, newActiveStatement,
3247
                areEquivalent: AreEquivalentActiveStatements,
3248
                areSimilar: AreSimilarActiveStatements);
3249 3250 3251 3252
        }

        private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables)
        {
3253 3254 3255 3256 3257 3258
            return DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray());
        }

        private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables)
        {
            if (oldVariables.Length != newVariables.Length)
3259 3260 3261 3262
            {
                return false;
            }

3263
            for (int i = 0; i < oldVariables.Length; i++)
3264
            {
3265
                if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i]))
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276
                {
                    return false;
                }
            }

            return true;
        }

        #endregion
    }
}