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

3
using System;
P
Pilchie 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
    internal static class SyntaxTreeExtensions
    {
        public static bool IsAttributeNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

            // cases:
            //   [ |
25
            if (token.IsKind(SyntaxKind.OpenBracketToken) &&
J
jasonmalinowski 已提交
26
                token.Parent.IsKind(SyntaxKind.AttributeList))
P
Pilchie 已提交
27 28 29 30 31
            {
                return true;
            }

            // cases:
32
            //   [Goo(1), |
33
            if (token.IsKind(SyntaxKind.CommaToken) &&
J
jasonmalinowski 已提交
34
                token.Parent.IsKind(SyntaxKind.AttributeList))
P
Pilchie 已提交
35 36 37 38 39 40
            {
                return true;
            }

            // cases:
            //   [specifier: |
41
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
42
                token.Parent.IsKind(SyntaxKind.AttributeTargetSpecifier))
P
Pilchie 已提交
43 44 45 46 47 48
            {
                return true;
            }

            // cases:
            //   [Namespace.|
J
jasonmalinowski 已提交
49
            if (token.Parent.IsKind(SyntaxKind.QualifiedName) &&
P
Pilchie 已提交
50 51 52 53 54 55 56
                token.Parent.IsParentKind(SyntaxKind.Attribute))
            {
                return true;
            }

            // cases:
            //   [global::|
J
jasonmalinowski 已提交
57
            if (token.Parent.IsKind(SyntaxKind.AliasQualifiedName) &&
P
Pilchie 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71
                token.Parent.IsParentKind(SyntaxKind.Attribute))
            {
                return true;
            }

            return false;
        }

        public static bool IsGlobalMemberDeclarationContext(
            this SyntaxTree syntaxTree,
            int position,
            ISet<SyntaxKind> validModifiers,
            CancellationToken cancellationToken)
        {
A
Artur Spychaj 已提交
72
            if (!syntaxTree.IsScript())
P
Pilchie 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
            {
                return false;
            }

            var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

            var modifierTokens = syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition, cancellationToken);
            if (modifierTokens.IsEmpty())
            {
                return false;
            }

            if (modifierTokens.IsSubsetOf(validModifiers))
            {
                // the parent is the member
                // the grandparent is the container of the member
                // in interactive, it's possible that there might be an intervening "incomplete" member for partially
                // typed declarations that parse ambiguously. For example, "internal e".
J
jasonmalinowski 已提交
92 93
                if (token.Parent.IsKind(SyntaxKind.CompilationUnit) ||
                   (token.Parent.IsKind(SyntaxKind.IncompleteMember) && token.Parent.IsParentKind(SyntaxKind.CompilationUnit)))
P
Pilchie 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsMemberDeclarationContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            // class C {
            //   |

            // class C {
110
            //   void Goo() {
P
Pilchie 已提交
111 112 113 114 115 116 117 118 119 120 121
            //   }
            //   |

            // class C {
            //   int i;
            //   |

            // class C {
            //   public |

            // class C {
122
            //   [Goo]
P
Pilchie 已提交
123 124 125 126 127 128 129 130 131
            //   |

            var originalToken = tokenOnLeftOfPosition;
            var token = originalToken;

            // If we're touching the right of an identifier, move back to
            // previous token.
            token = token.GetPreviousTokenIfTouchingWord(position);

132
            if (token.IsKind(SyntaxKind.OpenBraceToken))
P
Pilchie 已提交
133 134 135 136 137 138 139 140 141 142
            {
                if (token.Parent is BaseTypeDeclarationSyntax)
                {
                    return true;
                }
            }

            // class C {
            //   int i;
            //   |
143
            if (token.IsKind(SyntaxKind.SemicolonToken))
P
Pilchie 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156
            {
                if (token.Parent is MemberDeclarationSyntax &&
                    token.Parent.GetParent() is BaseTypeDeclarationSyntax)
                {
                    return true;
                }
            }

            // class A {
            //   class C {}
            //   |

            // class C {
157
            //    void Goo() {
P
Pilchie 已提交
158 159
            //    }
            //    |
160
            if (token.IsKind(SyntaxKind.CloseBraceToken))
P
Pilchie 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173
            {
                if (token.Parent is BaseTypeDeclarationSyntax &&
                    token.Parent.GetParent() is BaseTypeDeclarationSyntax)
                {
                    // after a nested type
                    return true;
                }
                else if (token.Parent is AccessorListSyntax)
                {
                    // after a property
                    return true;
                }
                else if (
J
jasonmalinowski 已提交
174
                    token.Parent.IsKind(SyntaxKind.Block) &&
P
Pilchie 已提交
175 176 177 178 179 180 181
                    token.Parent.GetParent() is MemberDeclarationSyntax)
                {
                    // after a method/operator/etc.
                    return true;
                }
            }

182
            // namespace Goo {
P
Pilchie 已提交
183 184 185
            //   [Bar]
            //   |

186
            if (token.IsKind(SyntaxKind.CloseBracketToken) &&
J
jasonmalinowski 已提交
187
                token.Parent.IsKind(SyntaxKind.AttributeList))
P
Pilchie 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
            {
                // attributes belong to a member which itself is in a
                // container.

                // the parent is the attribute
                // the grandparent is the owner of the attribute
                // the great-grandparent is the container that the owner is in
                var container = token.Parent.GetParent().GetParent();
                if (container is BaseTypeDeclarationSyntax)
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsMemberDeclarationContext(
            this SyntaxTree syntaxTree,
            int position,
            CSharpSyntaxContext contextOpt,
            ISet<SyntaxKind> validModifiers,
            ISet<SyntaxKind> validTypeDeclarations,
            bool canBePartial,
            CancellationToken cancellationToken)
        {
            var typeDecl = contextOpt != null
                ? contextOpt.ContainingTypeOrEnumDeclaration
                : syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken);

            if (typeDecl == null)
            {
                return false;
            }

223
            if (!validTypeDeclarations.Contains(typeDecl.Kind()))
P
Pilchie 已提交
224 225 226 227 228 229 230 231 232 233 234
            {
                return false;
            }

            validTypeDeclarations = validTypeDeclarations ?? SpecializedCollections.EmptySet<SyntaxKind>();

            // Check many of the simple cases first.
            var leftToken = contextOpt != null
                ? contextOpt.LeftToken
                : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);

235 236 237 238 239 240 241 242 243
            var token = contextOpt != null
                ? contextOpt.TargetToken
                : leftToken.GetPreviousTokenIfTouchingWord(position);

            if (token.IsAnyAccessorDeclarationContext(position))
            {
                return false;
            }

P
Pilchie 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
            if (syntaxTree.IsMemberDeclarationContext(position, leftToken, cancellationToken))
            {
                return true;
            }

            // A member can also show up after certain types of modifiers
            if (canBePartial &&
                token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
            {
                return true;
            }

            var modifierTokens = contextOpt != null
                ? contextOpt.PrecedingModifiers
                : syntaxTree.GetPrecedingModifiers(position, leftToken, cancellationToken);

            if (modifierTokens.IsEmpty())
            {
                return false;
            }

            validModifiers = validModifiers ?? SpecializedCollections.EmptySet<SyntaxKind>();

            if (modifierTokens.IsSubsetOf(validModifiers))
            {
                var member = token.Parent;
                if (token.HasMatchingText(SyntaxKind.AsyncKeyword))
                {
                    // second appearance of "async", not followed by modifier: treat it as type
                    if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token, cancellationToken).Any(x => x == SyntaxKind.AsyncKeyword))
                    {
                        return false;
                    }

                    // rule out async lambdas inside a method
                    if (token.GetAncestor<StatementSyntax>() == null)
                    {
                        member = token.GetAncestor<MemberDeclarationSyntax>();
                    }
                }

                // cases:
                // public |
                // async |
                // public async |
                return member != null &&
                    member.Parent is BaseTypeDeclarationSyntax;
            }

            return false;
        }

296 297 298 299 300 301 302 303 304 305 306 307 308 309 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
        public static bool IsLocalFunctionDeclarationContext(
            this SyntaxTree syntaxTree,
            int position,
            CancellationToken cancellationToken)
        {
            var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            var token = leftToken.GetPreviousTokenIfTouchingWord(position);

            // Local functions are always valid in a statement context
            if (syntaxTree.IsStatementContext(position, leftToken, cancellationToken))
            {
                return true;
            }

            // Also valid after certain modifiers
            var validModifiers = SyntaxKindSet.LocalFunctionModifiers;

            var modifierTokens = syntaxTree.GetPrecedingModifiers(
                position, token, out int beforeModifiersPosition);

            if (modifierTokens.IsSubsetOf(validModifiers))
            {
                if (token.HasMatchingText(SyntaxKind.AsyncKeyword))
                {
                    // second appearance of "async" not followed by modifier: treat as type
                    if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token, cancellationToken)
                        .Contains(SyntaxKind.AsyncKeyword))
                    {
                        return false;
                    }
                }

                leftToken = syntaxTree.FindTokenOnLeftOfPosition(beforeModifiersPosition, cancellationToken);
                token = leftToken.GetPreviousTokenIfTouchingWord(beforeModifiersPosition);
                return syntaxTree.IsStatementContext(beforeModifiersPosition, token, cancellationToken);
            }

            return false;
        }

P
Pilchie 已提交
336 337 338 339 340 341 342 343 344
        public static bool IsTypeDeclarationContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            // root: |

            // extern alias a;
            // |

345
            // using Goo;
P
Pilchie 已提交
346 347
            // |

348
            // using Goo = Bar;
P
Pilchie 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
            // |

            // namespace N {}
            // |

            // namespace N {
            // |

            // class C {}
            // |

            // class C {
            // |

            // class C {
364
            //   void Goo() {
P
Pilchie 已提交
365 366 367 368 369 370 371 372 373 374 375
            //   }
            //   |

            // class C {
            //   int i;
            //   |

            // class C {
            //   public |

            // class C {
376
            //   [Goo]
P
Pilchie 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
            //   |

            var originalToken = tokenOnLeftOfPosition;
            var token = originalToken;

            // If we're touching the right of an identifier, move back to
            // previous token.
            token = token.GetPreviousTokenIfTouchingWord(position);

            // a type decl can't come before usings/externs
            if (originalToken.GetNextToken(includeSkipped: true).IsUsingOrExternKeyword())
            {
                return false;
            }

            // root: |
393
            if (token.IsKind(SyntaxKind.None))
P
Pilchie 已提交
394 395 396 397
            {
                // root namespace

                // a type decl can't come before usings/externs
C
CyrusNajmabadi 已提交
398
                if (syntaxTree.GetRoot(cancellationToken) is CompilationUnitSyntax compilationUnit &&
P
Pilchie 已提交
399 400 401 402 403 404 405 406 407
                    (compilationUnit.Externs.Count > 0 ||
                    compilationUnit.Usings.Count > 0))
                {
                    return false;
                }

                return true;
            }

408
            if (token.IsKind(SyntaxKind.OpenBraceToken))
P
Pilchie 已提交
409
            {
J
jasonmalinowski 已提交
410
                if (token.Parent.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
P
Pilchie 已提交
411 412 413
                {
                    return true;
                }
J
jasonmalinowski 已提交
414
                else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
P
Pilchie 已提交
415 416 417 418 419 420 421 422
                {
                    return true;
                }
            }

            // extern alias a;
            // |

423
            // using Goo;
P
Pilchie 已提交
424 425 426 427 428
            // |

            // class C {
            //   int i;
            //   |
429
            if (token.IsKind(SyntaxKind.SemicolonToken))
P
Pilchie 已提交
430
            {
J
jasonmalinowski 已提交
431
                if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective, SyntaxKind.UsingDirective))
P
Pilchie 已提交
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
                {
                    return true;
                }
                else if (token.Parent is MemberDeclarationSyntax)
                {
                    return true;
                }
            }

            // class C {}
            // |

            // namespace N {}
            // |

            // class C {
448
            //    void Goo() {
P
Pilchie 已提交
449 450
            //    }
            //    |
451
            if (token.IsKind(SyntaxKind.CloseBraceToken))
P
Pilchie 已提交
452 453 454 455 456
            {
                if (token.Parent is BaseTypeDeclarationSyntax)
                {
                    return true;
                }
J
jasonmalinowski 已提交
457
                else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration))
P
Pilchie 已提交
458 459 460 461 462 463 464 465
                {
                    return true;
                }
                else if (token.Parent is AccessorListSyntax)
                {
                    return true;
                }
                else if (
J
jasonmalinowski 已提交
466
                    token.Parent.IsKind(SyntaxKind.Block) &&
P
Pilchie 已提交
467 468 469 470 471 472
                    token.Parent.GetParent() is MemberDeclarationSyntax)
                {
                    return true;
                }
            }

473
            // namespace Goo {
P
Pilchie 已提交
474 475 476
            //   [Bar]
            //   |

477
            if (token.IsKind(SyntaxKind.CloseBracketToken) &&
J
jasonmalinowski 已提交
478
                token.Parent.IsKind(SyntaxKind.AttributeList))
P
Pilchie 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 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
            {
                // assembly attributes belong to the containing compilation unit
                if (token.Parent.IsParentKind(SyntaxKind.CompilationUnit))
                {
                    return true;
                }

                // other attributes belong to a member which itself is in a
                // container.

                // the parent is the attribute
                // the grandparent is the owner of the attribute
                // the great-grandparent is the container that the owner is in
                var container = token.Parent.GetParent().GetParent();
                if (container.IsKind(SyntaxKind.CompilationUnit) ||
                    container.IsKind(SyntaxKind.NamespaceDeclaration) ||
                    container.IsKind(SyntaxKind.ClassDeclaration) ||
                    container.IsKind(SyntaxKind.StructDeclaration))
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsTypeDeclarationContext(
            this SyntaxTree syntaxTree,
            int position,
            CSharpSyntaxContext contextOpt,
            ISet<SyntaxKind> validModifiers,
            ISet<SyntaxKind> validTypeDeclarations,
            bool canBePartial,
            CancellationToken cancellationToken)
        {
            // We only allow nested types inside a class or struct, not inside a
            // an interface or enum.
            var typeDecl = contextOpt != null
                ? contextOpt.ContainingTypeDeclaration
                : syntaxTree.GetContainingTypeDeclaration(position, cancellationToken);

            validTypeDeclarations = validTypeDeclarations ?? SpecializedCollections.EmptySet<SyntaxKind>();

            if (typeDecl != null)
            {
524
                if (!validTypeDeclarations.Contains(typeDecl.Kind()))
P
Pilchie 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
                {
                    return false;
                }
            }

            // Check many of the simple cases first.
            var leftToken = contextOpt != null
                ? contextOpt.LeftToken
                : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);

            // If we're touching the right of an identifier, move back to
            // previous token.
            var token = contextOpt != null
                ? contextOpt.TargetToken
                : leftToken.GetPreviousTokenIfTouchingWord(position);

541 542 543 544 545 546 547 548 549 550
            if (token.IsAnyAccessorDeclarationContext(position))
            {
                return false;
            }

            if (syntaxTree.IsTypeDeclarationContext(position, leftToken, cancellationToken))
            {
                return true;
            }

P
Pilchie 已提交
551 552 553 554 555 556 557
            // A type can also show up after certain types of modifiers
            if (canBePartial &&
                token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
            {
                return true;
            }

558 559 560 561 562 563
            // using static | is never a type declaration context
            if (token.IsStaticKeywordInUsingDirective())
            {
                return false;
            }

P
Pilchie 已提交
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
            var modifierTokens = contextOpt != null
                ? contextOpt.PrecedingModifiers
                : syntaxTree.GetPrecedingModifiers(position, leftToken, cancellationToken);

            if (modifierTokens.IsEmpty())
            {
                return false;
            }

            validModifiers = validModifiers ?? SpecializedCollections.EmptySet<SyntaxKind>();

            if (modifierTokens.IsProperSubsetOf(validModifiers))
            {
                // the parent is the member
                // the grandparent is the container of the member
                var container = token.Parent.GetParent();
                if (container.IsKind(SyntaxKind.CompilationUnit) ||
                    container.IsKind(SyntaxKind.NamespaceDeclaration) ||
                    container.IsKind(SyntaxKind.ClassDeclaration) ||
                    container.IsKind(SyntaxKind.StructDeclaration))
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsNamespaceContext(
            this SyntaxTree syntaxTree,
            int position,
            CancellationToken cancellationToken,
            SemanticModel semanticModelOpt = null)
        {
            // first do quick exit check
            if (syntaxTree.IsInNonUserCode(position, cancellationToken) ||
                syntaxTree.IsRightOfDotOrArrow(position, cancellationToken))
            {
                return false;
            }

            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
                                  .GetPreviousTokenIfTouchingWord(position);

            // global::
609 610
            if (token.IsKind(SyntaxKind.ColonColonToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.GlobalKeyword))
P
Pilchie 已提交
611 612 613 614 615 616 617 618 619 620 621
            {
                return true;
            }

            // using |
            // but not:
            // using | = Bar

            // Note: we take care of the using alias case in the IsTypeContext
            // call below.

622
            if (token.IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
623 624 625 626
            {
                var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
                if (usingDirective != null)
                {
627
                    if (token.GetNextToken(includeSkipped: true).Kind() != SyntaxKind.EqualsToken &&
P
Pilchie 已提交
628 629 630 631 632 633 634
                        usingDirective.Alias == null)
                    {
                        return true;
                    }
                }
            }

635 636 637 638 639 640
            // using static |
            if (token.IsStaticKeywordInUsingDirective())
            {
                return true;
            }

P
Pilchie 已提交
641 642 643 644 645
            // if it is not using directive location, most of places where 
            // type can appear, namespace can appear as well
            return syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt);
        }

646 647
        public static bool IsNamespaceDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
648
            if (syntaxTree.IsScript() || syntaxTree.IsInNonUserCode(position, cancellationToken))
649 650 651 652
            {
                return false;
            }

653 654 655 656 657 658
            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
                                  .GetPreviousTokenIfTouchingWord(position);

            var declaration = token.GetAncestor<NamespaceDeclarationSyntax>();

            return declaration != null && (declaration.Name.Span.IntersectsWith(position) || declaration.NamespaceKeyword == token);
659 660
        }

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
        public static bool IsPartialTypeDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, out TypeDeclarationSyntax declarationSyntax)
        {
            if (!syntaxTree.IsInNonUserCode(position, cancellationToken))
            {
                var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
                                      .GetPreviousTokenIfTouchingWord(position);

                if ((token.IsKind(SyntaxKind.ClassKeyword) ||
                     token.IsKind(SyntaxKind.StructKeyword) ||
                     token.IsKind(SyntaxKind.InterfaceKeyword)) &&
                     token.GetPreviousToken().IsKind(SyntaxKind.PartialKeyword))
                {
                    declarationSyntax = token.GetAncestor<TypeDeclarationSyntax>();
                    return declarationSyntax != null && declarationSyntax.Keyword == token;
                }
            }

            declarationSyntax = null;
            return false;
        }

P
Pilchie 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
        public static bool IsDefinitelyNotTypeContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            return
                syntaxTree.IsInNonUserCode(position, cancellationToken) ||
                syntaxTree.IsRightOfDotOrArrow(position, cancellationToken);
        }

        public static bool IsTypeContext(
            this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, SemanticModel semanticModelOpt = null)
        {
            // first do quick exit check
            if (syntaxTree.IsDefinitelyNotTypeContext(position, cancellationToken))
            {
                return false;
            }

            // okay, now it is a case where we can't use parse tree (valid or error recovery) to
            // determine whether it is a right place to put type. use lex based one Cyrus created.

            var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            return
                syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
704 705
                syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
                syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
P
Pilchie 已提交
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
                syntaxTree.IsAfterKeyword(position, SyntaxKind.CaseKeyword, cancellationToken) ||
                syntaxTree.IsAfterKeyword(position, SyntaxKind.EventKeyword, cancellationToken) ||
                syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
                syntaxTree.IsAttributeNameContext(position, cancellationToken) ||
                syntaxTree.IsBaseClassOrInterfaceContext(position, cancellationToken) ||
                syntaxTree.IsCatchVariableDeclarationContext(position, cancellationToken) ||
                syntaxTree.IsDefiniteCastTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsDelegateReturnTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) ||
                syntaxTree.IsPrimaryFunctionExpressionContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt) ||
                syntaxTree.IsFixedVariableDeclarationContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsIsOrAsTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsLocalVariableDeclarationContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsObjectCreationTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsParameterTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsStatementContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsTypeParameterConstraintContext(position, tokenOnLeftOfPosition, cancellationToken) ||
                syntaxTree.IsUsingAliasContext(position, cancellationToken) ||
727
                syntaxTree.IsUsingStaticContext(position, cancellationToken) ||
P
Pilchie 已提交
728
                syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
729
                syntaxTree.IsPossibleTupleContext(tokenOnLeftOfPosition, position) ||
P
Pilchie 已提交
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
                syntaxTree.IsMemberDeclarationContext(
                    position,
                    contextOpt: null,
                    validModifiers: SyntaxKindSet.AllMemberModifiers,
                    validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations,
                    canBePartial: false,
                    cancellationToken: cancellationToken);
        }

        public static bool IsBaseClassOrInterfaceContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            // class C : |
            // class C : Bar, |

            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

747 748
            if (token.IsKind(SyntaxKind.ColonToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
749
            {
J
jasonmalinowski 已提交
750
                if (token.Parent.IsKind(SyntaxKind.BaseList))
P
Pilchie 已提交
751 752 753 754 755 756 757 758 759 760
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsUsingAliasContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
761
            // using Goo = |
P
Pilchie 已提交
762 763 764 765

            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

766
            if (token.IsKind(SyntaxKind.EqualsToken) &&
P
Pilchie 已提交
767 768 769 770 771 772 773 774
                token.GetAncestor<UsingDirectiveSyntax>() != null)
            {
                return true;
            }

            return false;
        }

775 776 777 778 779 780 781 782 783 784
        public static bool IsUsingStaticContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            // using static |

            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

            return token.IsStaticKeywordInUsingDirective();
        }

P
Pilchie 已提交
785 786 787 788 789
        public static bool IsTypeArgumentOfConstraintClause(
            this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            // cases:
            //   where |
790
            //   class Goo<T> : Object where |
P
Pilchie 已提交
791 792 793 794

            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

795
            if (token.IsKind(SyntaxKind.WhereKeyword) &&
J
jasonmalinowski 已提交
796
                token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
P
Pilchie 已提交
797 798 799 800
            {
                return true;
            }

801
            if (token.IsKind(SyntaxKind.IdentifierToken) &&
P
Pilchie 已提交
802
                token.HasMatchingText(SyntaxKind.WhereKeyword) &&
J
jasonmalinowski 已提交
803
                token.Parent.IsKind(SyntaxKind.IdentifierName) &&
804 805
                token.Parent.IsParentKind(SyntaxKind.SimpleBaseType) &&
                token.Parent.Parent.IsParentKind(SyntaxKind.BaseList))
P
Pilchie 已提交
806 807 808 809 810 811 812
            {
                return true;
            }

            return false;
        }

813
        public static bool IsTypeParameterConstraintStartContext(
P
Pilchie 已提交
814 815 816 817 818 819 820 821
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //   where T : |

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

822 823 824
            if (token.IsKind(SyntaxKind.ColonToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IdentifierToken) &&
                token.GetPreviousToken(includeSkipped: true).GetPreviousToken().IsKind(SyntaxKind.WhereKeyword))
P
Pilchie 已提交
825 826 827 828 829 830 831 832 833
            {
                return true;
            }

            return false;
        }

        public static bool IsTypeParameterConstraintContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
834
            if (syntaxTree.IsTypeParameterConstraintStartContext(position, tokenOnLeftOfPosition, cancellationToken))
P
Pilchie 已提交
835 836 837 838 839 840 841 842 843 844 845 846
            {
                return true;
            }

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

            // Can't come after new()
            //
            //    where T : |
            //    where T : class, |
            //    where T : struct, |
847
            //    where T : Goo, |
848
            if (token.IsKind(SyntaxKind.CommaToken) &&
J
jasonmalinowski 已提交
849
                token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
P
Pilchie 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
            {
                var constraintClause = token.Parent as TypeParameterConstraintClauseSyntax;

                // Check if there's a 'new()' constraint.  If there isn't, or we're before it, then
                // this is a type parameter constraint context. 
                var firstConstructorConstraint = constraintClause.Constraints.FirstOrDefault(t => t is ConstructorConstraintSyntax);
                if (firstConstructorConstraint == null || firstConstructorConstraint.SpanStart > token.Span.End)
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsTypeOfExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

869
            if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.TypeOfExpression))
P
Pilchie 已提交
870 871 872 873 874 875 876 877 878 879 880
            {
                return true;
            }

            return false;
        }

        public static bool IsDefaultExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

881
            if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.DefaultExpression))
P
Pilchie 已提交
882 883 884 885 886 887 888 889 890 891 892 893
            {
                return true;
            }

            return false;
        }

        public static bool IsSizeOfExpressionContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

894
            if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.SizeOfExpression))
P
Pilchie 已提交
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
            {
                return true;
            }

            return false;
        }

        public static bool IsGenericTypeArgumentContext(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            CancellationToken cancellationToken,
            SemanticModel semanticModelOpt = null)
        {
            // cases: 
910 911 912
            //    Goo<|
            //    Goo<Bar,|
            //    Goo<Bar<Baz<int[],|
P
Pilchie 已提交
913 914 915
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

916
            if (token.Kind() != SyntaxKind.LessThanToken && token.Kind() != SyntaxKind.CommaToken)
P
Pilchie 已提交
917 918 919 920 921 922 923 924 925 926
            {
                return false;
            }

            if (token.Parent is TypeArgumentListSyntax)
            {
                // Easy case, it was known to be a generic name, so this is a type argument context.
                return true;
            }

C
CyrusNajmabadi 已提交
927
            if (!syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out var nameToken))
P
Pilchie 已提交
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
            {
                return false;
            }

            var name = nameToken.Parent as NameSyntax;
            if (name == null)
            {
                return false;
            }

            // Looks viable!  If they provided a binding, then check if it binds properly to
            // an actual generic entity.
            if (semanticModelOpt == null)
            {
                // No binding.  Just make the decision based on the syntax tree.
                return true;
            }

            // '?' is syntactically ambiguous in incomplete top-level statements:
            //
948
            // T ? goo<| 
P
Pilchie 已提交
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
            //
            // Might be an incomplete conditional expression or an incomplete declaration of a method returning a nullable type.
            // Bind T to see if it is a type. If it is we don't show signature help.
            if (name.IsParentKind(SyntaxKind.LessThanExpression) &&
                name.Parent.IsParentKind(SyntaxKind.ConditionalExpression) &&
                name.Parent.Parent.IsParentKind(SyntaxKind.ExpressionStatement) &&
                name.Parent.Parent.Parent.IsParentKind(SyntaxKind.GlobalStatement))
            {
                var conditionOrType = semanticModelOpt.GetSymbolInfo(
                    ((ConditionalExpressionSyntax)name.Parent.Parent).Condition, cancellationToken);
                if (conditionOrType.GetBestOrAllSymbols().FirstOrDefault() != null &&
                    conditionOrType.GetBestOrAllSymbols().FirstOrDefault().Kind == SymbolKind.NamedType)
                {
                    return false;
                }
            }

            var symbols = semanticModelOpt.LookupName(nameToken, namespacesAndTypesOnly: SyntaxFacts.IsInNamespaceOrTypeContext(name), cancellationToken: cancellationToken);
            return symbols.Any(s =>
C
CyrusNajmabadi 已提交
968 969 970 971 972 973 974 975
            {
                switch (s)
                {
                    case INamedTypeSymbol nt: return nt.Arity > 0;
                    case IMethodSymbol m: return m.Arity > 0;
                    default: return false;
                }
            });
P
Pilchie 已提交
976 977 978 979 980 981 982
        }

        public static bool IsParameterModifierContext(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            CancellationToken cancellationToken,
983
            bool includeOperators = false,
984
            bool isThisKeyword = false)
P
Pilchie 已提交
985 986
        {
            // cases:
987 988 989
            //   Goo(|
            //   Goo(int i, |
            //   Goo([Bar]|
P
Pilchie 已提交
990 991 992
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

993
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
994
                token.Parent.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
P
Pilchie 已提交
995 996 997 998
            {
                return true;
            }

999
            if (token.IsKind(SyntaxKind.CommaToken) &&
1000
                token.Parent.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
P
Pilchie 已提交
1001
            {
1002
                if (isThisKeyword)
P
Pilchie 已提交
1003 1004 1005 1006
                {
                    var parameterList = token.GetAncestor<ParameterListSyntax>();
                    var commaIndex = parameterList.Parameters.GetWithSeparators().IndexOf(token);
                    var index = commaIndex / 2 + 1;
1007
                    return index == 0;
P
Pilchie 已提交
1008 1009 1010 1011 1012
                }

                return true;
            }

1013
            if (token.IsKind(SyntaxKind.CloseBracketToken) &&
J
jasonmalinowski 已提交
1014
                token.Parent.IsKind(SyntaxKind.AttributeList) &&
P
Pilchie 已提交
1015
                token.Parent.IsParentKind(SyntaxKind.Parameter) &&
1016
                token.Parent.GetParent().GetParent().IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
P
Pilchie 已提交
1017
            {
1018
                if (isThisKeyword)
P
Pilchie 已提交
1019 1020 1021 1022 1023
                {
                    var parameter = token.GetAncestor<ParameterSyntax>();
                    var parameterList = parameter.GetAncestorOrThis<ParameterListSyntax>();

                    int parameterIndex = parameterList.Parameters.IndexOf(parameter);
1024
                    return parameterIndex == 0;
P
Pilchie 已提交
1025 1026 1027 1028 1029
                }

                return true;
            }

1030
            if (isThisKeyword &&
O
Omar Tawfik 已提交
1031
                (token.IsKind(SyntaxKind.RefKeyword) || token.IsKind(SyntaxKind.InKeyword)) &&
1032
                token.Parent.GetParent().IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
1033 1034 1035 1036 1037 1038 1039 1040
            {
                var parameter = token.GetAncestor<ParameterSyntax>();
                var parameterList = parameter.GetAncestorOrThis<ParameterListSyntax>();

                int parameterIndex = parameterList.Parameters.IndexOf(parameter);
                return parameterIndex == 0;
            }

P
Pilchie 已提交
1041 1042 1043
            return false;
        }

1044 1045 1046 1047 1048 1049 1050
        public static bool IsParamsModifierContext(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            CancellationToken cancellationToken)
        {
            if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, cancellationToken))
1051
            {
1052
                return true;
1053
            }
1054

1055 1056 1057 1058
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

            if (token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken))
1059
            {
1060
                return token.Parent.IsKind(SyntaxKind.BracketedParameterList);
1061 1062 1063 1064 1065
            }

            return false;
        }

P
Pilchie 已提交
1066 1067 1068 1069 1070 1071
        public static bool IsDelegateReturnTypeContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1072
            if (token.IsKind(SyntaxKind.DelegateKeyword) &&
J
jasonmalinowski 已提交
1073
                token.Parent.IsKind(SyntaxKind.DelegateDeclaration))
P
Pilchie 已提交
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
            {
                return true;
            }

            return false;
        }

        public static bool IsImplicitOrExplicitOperatorTypeContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1087
            if (token.IsKind(SyntaxKind.OperatorKeyword))
P
Pilchie 已提交
1088
            {
1089 1090
                if (token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ImplicitKeyword) ||
                    token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ExplicitKeyword))
P
Pilchie 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsParameterTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

1103 1104
            if (token.IsKind(SyntaxKind.RefKeyword) ||
                token.IsKind(SyntaxKind.OutKeyword) ||
1105
                token.IsKind(SyntaxKind.InKeyword) ||
1106 1107
                token.IsKind(SyntaxKind.ParamsKeyword) ||
                token.IsKind(SyntaxKind.ThisKeyword))
P
Pilchie 已提交
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
            {
                position = token.SpanStart;
                tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            }

            if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, cancellationToken))
            {
                return true;
            }

            // int this[ |
            // int this[int i, |
1120 1121 1122
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1123
            {
J
jasonmalinowski 已提交
1124
                if (token.Parent.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList))
P
Pilchie 已提交
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsPossibleLambdaParameterModifierContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1139 1140
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1141
            {
J
jasonmalinowski 已提交
1142
                if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
P
Pilchie 已提交
1143 1144 1145 1146 1147 1148 1149 1150 1151
                    token.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression))
                {
                    return true;
                }

                // TODO(cyrusn): Tie into semantic analysis system to only 
                // consider this a lambda if this is a location where the
                // lambda's type would be inferred because of a delegate
                // or Expression<T> type.
1152 1153
                if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression) ||
                    token.Parent.IsKind(SyntaxKind.TupleExpression))
P
Pilchie 已提交
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsAnonymousMethodParameterModifierContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1168 1169
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1170
            {
J
jasonmalinowski 已提交
1171
                if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
P
Pilchie 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
                    token.Parent.IsParentKind(SyntaxKind.AnonymousMethodExpression))
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1187
            if (token.IsKind(SyntaxKind.RefKeyword) ||
1188
                token.IsKind(SyntaxKind.InKeyword) ||
1189
                token.IsKind(SyntaxKind.OutKeyword))
P
Pilchie 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
            {
                position = token.SpanStart;
                tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            }

            if (IsAnonymousMethodParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition, cancellationToken) ||
                IsPossibleLambdaParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition, cancellationToken))
            {
                return true;
            }

            return false;
        }

1204 1205 1206 1207 1208 1209
        /// <summary>
        /// Are you possibly typing a tuple type or expression?
        /// This is used to suppress colon as a completion trigger (so that you can type element names).
        /// This is also used to recommend some keywords (like var).
        /// </summary>
        public static bool IsPossibleTupleContext(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position)
1210
        {
1211
            leftToken = leftToken.GetPreviousTokenIfTouchingWord(position);
1212

1213 1214 1215
            // ($$
            // (a, $$
            if (IsPossibleTupleOpenParenOrComma(leftToken))
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
                return true;
            }

            // ((a, b) $$
            // (..., (a, b) $$
            if (leftToken.IsKind(SyntaxKind.CloseParenToken))
            {
                if (leftToken.Parent.IsKind(
                        SyntaxKind.ParenthesizedExpression,
                        SyntaxKind.TupleExpression,
                        SyntaxKind.TupleType))
                {
                    var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent);
                    if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen))
                    {
                        return true;
                    }
                }
            }

            // (a $$
            // (..., b $$
            if (leftToken.IsKind(SyntaxKind.IdentifierToken))
            {
                var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent);
                if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen))
                {
                    return true;
                }
1246 1247
            }

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
            // (a.b $$
            // (..., a.b $$
            if (leftToken.IsKind(SyntaxKind.IdentifierToken) &&
                leftToken.Parent.IsKind(SyntaxKind.IdentifierName) &&
                leftToken.Parent.IsParentKind(SyntaxKind.QualifiedName, SyntaxKind.SimpleMemberAccessExpression))
            {
                var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent.Parent);
                if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen))
                {
                    return true;
                }
            }

            return false;
        }

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
        public static bool IsPatternContext(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position)
        {
            leftToken = leftToken.GetPreviousTokenIfTouchingWord(position);

            // case $$
            // is $$
            if (leftToken.IsKind(SyntaxKind.CaseKeyword, SyntaxKind.IsKeyword))
            {
                return true;
            }

            return false;
        }

1278 1279 1280 1281 1282
        private static SyntaxToken FindTokenOnLeftOfNode(SyntaxNode node)
        {
            return node.FindTokenOnLeftOfPosition(node.SpanStart);
        }

R
Ravi Chande 已提交
1283 1284

        public static bool IsPossibleTupleOpenParenOrComma(SyntaxToken possibleCommaOrParen)
1285 1286 1287 1288 1289 1290 1291
        {
            if (!possibleCommaOrParen.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken))
            {
                return false;
            }

            if (possibleCommaOrParen.Parent.IsKind(
R
Ravi Chande 已提交
1292 1293 1294 1295
                    SyntaxKind.ParenthesizedExpression,
                    SyntaxKind.TupleExpression,
                    SyntaxKind.TupleType,
                    SyntaxKind.CastExpression))
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
            {
                return true;
            }

            // in script
            if (possibleCommaOrParen.Parent.IsKind(SyntaxKind.ParameterList) &&
                possibleCommaOrParen.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression))
            {
                var parenthesizedLambda = (ParenthesizedLambdaExpressionSyntax)possibleCommaOrParen.Parent.Parent;
                if (parenthesizedLambda.ArrowToken.IsMissing)
                {
                    return true;
                }
            }
R
Ravi Chande 已提交
1310

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 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 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
            return false;
        }

        /// <summary>
        /// Are you possibly in the designation part of a deconstruction?
        /// This is used to enter suggestion mode (suggestions become soft-selected).
        /// </summary>
        public static bool IsPossibleDeconstructionDesignation(this SyntaxTree syntaxTree,
            int position, CancellationToken cancellationToken)
        {
            var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            leftToken = leftToken.GetPreviousTokenIfTouchingWord(position);

            // The well-formed cases:
            // var ($$, y) = e;
            // (var $$, var y) = e;
            if (leftToken.Parent.IsKind(SyntaxKind.SingleVariableDesignation, SyntaxKind.ParenthesizedVariableDesignation))
            {
                return true;
            }

            // (var $$, var y)
            // (var x, var y)
            if (syntaxTree.IsPossibleTupleContext(leftToken, position) && !IsPossibleTupleOpenParenOrComma(leftToken))
            {
                return true;
            }

            // var ($$)
            // var (x, $$)
            if (IsPossibleVarDeconstructionOpenParenOrComma(leftToken))
            {
                return true;
            }

            // var (($$), y)
            if (leftToken.IsKind(SyntaxKind.OpenParenToken) && leftToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
            {
                if (IsPossibleVarDeconstructionOpenParenOrComma(FindTokenOnLeftOfNode(leftToken.Parent)))
                {
                    return true;
                }
            }

            // var ((x, $$), y)
            // var (($$, x), y)
            if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.TupleExpression))
            {
                if (IsPossibleVarDeconstructionOpenParenOrComma(FindTokenOnLeftOfNode(leftToken.Parent)))
                {
                    return true;
                }
            }

            // foreach (var ($$
            // foreach (var ((x, $$), y)
            if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken))
            {
                var outer = UnwrapPossibleTuple(leftToken.Parent);
                if (outer.Parent.IsKind(SyntaxKind.ForEachStatement))
                {
                    var @foreach = (ForEachStatementSyntax)outer.Parent;

                    if (@foreach.Expression == outer &&
                        @foreach.Type.IsKind(SyntaxKind.IdentifierName) &&
                        ((IdentifierNameSyntax)@foreach.Type).Identifier.ValueText == "var")
                    {
                        return true;
                    }
                }
1381 1382
            }

1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
            return false;
        }

        /// <summary>
        /// If inside a parenthesized or tuple expression, unwrap the nestings and return the container.
        /// </summary>
        private static SyntaxNode UnwrapPossibleTuple(SyntaxNode node)
        {
            while (true)
            {
                if (node.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
                {
                    node = node.Parent;
                    continue;
                }
                if (node.Parent.IsKind(SyntaxKind.Argument) && node.Parent.IsParentKind(SyntaxKind.TupleExpression))
                {
                    node = node.Parent.Parent;
                    continue;
                }

                return node;
            }
        }

        private static bool IsPossibleVarDeconstructionOpenParenOrComma(SyntaxToken leftToken)
        {
            if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) &&
                leftToken.Parent.IsKind(SyntaxKind.ArgumentList) &&
                leftToken.Parent.IsParentKind(SyntaxKind.InvocationExpression))
            {
                var invocation = (InvocationExpressionSyntax)leftToken.Parent.Parent;
                if (invocation.Expression.IsKind(SyntaxKind.IdentifierName) &&
                    ((IdentifierNameSyntax)invocation.Expression).Identifier.ValueText == "var")
                {
                    return true;
                }
            }
            return false;
1422 1423 1424 1425 1426 1427 1428
        }

        public static bool HasNames(this TupleExpressionSyntax tuple)
        {
            return tuple.Arguments.Any(a => a.NameColon != null);
        }

P
Pilchie 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
        public static bool IsValidContextForFromClause(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            CancellationToken cancellationToken,
            SemanticModel semanticModelOpt = null)
        {
            if (syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) &&
                !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition, cancellationToken))
            {
                return true;
            }

            // cases:
            //   var q = |
            //   var q = f|
            //
            //   var q = from x in y
            //           |
            //
            //   var q = from x in y
            //           f|
            //
            // this list is *not* exhaustive.
            // the first two are handled by 'IsExpressionContext'

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

            // var q = from x in y
            //         |
            if (!token.IntersectsWith(position) &&
                token.IsLastTokenOfQueryClause())
            {
                return true;
            }

            return false;
        }

        public static bool IsValidContextForJoinClause(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

            // var q = from x in y
            //         |
            if (!token.IntersectsWith(position) &&
                token.IsLastTokenOfQueryClause())
            {
                return true;
            }

            return false;
        }

1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
        public static bool IsDeclarationExpressionContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //  M(out var
            //  var x = var

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

J
jasonmalinowski 已提交
1496 1497
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OutKeyword) &&
                token.Parent.IsKind(SyntaxKind.Argument))
1498 1499 1500 1501
            {
                return true;
            }

J
jasonmalinowski 已提交
1502 1503
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.EqualsToken) &&
                token.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
1504 1505 1506 1507 1508 1509 1510 1511
                token.Parent.IsParentKind(SyntaxKind.VariableDeclarator))
            {
                return true;
            }

            return false;
        }

P
Pilchie 已提交
1512 1513 1514 1515 1516
        public static bool IsLocalVariableDeclarationContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //  const var
Š
Šimon Koníček 已提交
1517 1518
            //  ref var
            //  ref readonly var
1519
            //  out var
P
Pilchie 已提交
1520 1521 1522 1523 1524 1525 1526 1527 1528
            //  for (var
            //  foreach (var
            //  using (var
            //  from var
            //  join var

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1529
            if (token.IsKind(SyntaxKind.ConstKeyword) &&
J
jasonmalinowski 已提交
1530
                token.Parent.IsKind(SyntaxKind.LocalDeclarationStatement))
P
Pilchie 已提交
1531 1532 1533 1534
            {
                return true;
            }

Š
Šimon Koníček 已提交
1535 1536 1537 1538 1539 1540 1541 1542
            if (token.IsKind(SyntaxKind.RefKeyword, SyntaxKind.ReadOnlyKeyword) &&
                token.Parent.IsKind(SyntaxKind.RefType) &&
                token.Parent.IsParentKind(SyntaxKind.VariableDeclaration) &&
                token.Parent.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement))
            {
                return true;
            }

1543 1544
            if (token.IsKind(SyntaxKind.OutKeyword) &&
                token.Parent.IsKind(SyntaxKind.Argument) &&
A
AlekseyTs 已提交
1545
                ((ArgumentSyntax)token.Parent).RefOrOutKeyword == token)
1546 1547 1548 1549
            {
                return true;
            }

1550
            if (token.IsKind(SyntaxKind.OpenParenToken))
P
Pilchie 已提交
1551 1552
            {
                var previous = token.GetPreviousToken(includeSkipped: true);
1553 1554 1555
                if (previous.IsKind(SyntaxKind.ForKeyword) ||
                    previous.IsKind(SyntaxKind.ForEachKeyword) ||
                    previous.IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
                {
                    return true;
                }
            }

            var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken);
            if (token.IsKindOrHasMatchingText(SyntaxKind.FromKeyword) &&
                syntaxTree.IsValidContextForFromClause(token.SpanStart, tokenOnLeftOfStart, cancellationToken))
            {
                return true;
            }

J
jasonmalinowski 已提交
1568
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.JoinKeyword) &&
P
Pilchie 已提交
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
                syntaxTree.IsValidContextForJoinClause(token.SpanStart, tokenOnLeftOfStart, cancellationToken))
            {
                return true;
            }

            return false;
        }

        public static bool IsFixedVariableDeclarationContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //  fixed (var

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1586 1587
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.FixedKeyword))
P
Pilchie 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
            {
                return true;
            }

            return false;
        }

        public static bool IsCatchVariableDeclarationContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            // cases:
            //  catch (var

            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

1603 1604
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CatchKeyword))
P
Pilchie 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
            {
                return true;
            }

            return false;
        }

        public static bool IsIsOrAsTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1617 1618
            if (token.IsKind(SyntaxKind.IsKeyword) ||
                token.IsKind(SyntaxKind.AsKeyword))
P
Pilchie 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
            {
                return true;
            }

            return false;
        }

        public static bool IsObjectCreationTypeContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

1631
            if (token.IsKind(SyntaxKind.NewKeyword))
P
Pilchie 已提交
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
            {
                // we can follow a 'new' if it's the 'new' for an expression.
                var start = token.SpanStart;
                var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
                return
                    IsNonConstantExpressionContext(syntaxTree, token.SpanStart, tokenOnLeftOfStart, cancellationToken) ||
                    syntaxTree.IsStatementContext(token.SpanStart, tokenOnLeftOfStart, cancellationToken) ||
                    syntaxTree.IsGlobalStatementContext(token.SpanStart, cancellationToken);
            }

            return false;
        }

        private static bool IsNonConstantExpressionContext(SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            return
                syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken) &&
                !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition, cancellationToken);
        }

        public static bool IsPreProcessorDirectiveContext(this SyntaxTree syntaxTree, int position, SyntaxToken preProcessorTokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = preProcessorTokenOnLeftOfPosition;
            var directive = token.GetAncestor<DirectiveTriviaSyntax>();

            // Directives contain the EOL, so if the position is within the full span of the
            // directive, then it is on that line, the only exception is if the directive is on the
            // last line, the position at the end if technically not contained by the directive but
            // its also not on a new line, so it should be considered part of the preprocessor
            // context.
            if (directive == null)
            {
                return false;
            }

            return
                directive.FullSpan.Contains(position) ||
                directive.FullSpan.End == syntaxTree.GetRoot(cancellationToken).FullSpan.End;
        }

        public static bool IsPreProcessorDirectiveContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true);

            return syntaxTree.IsPreProcessorDirectiveContext(position, leftToken, cancellationToken);
        }

        public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            return IsPreProcessorKeywordContext(
                syntaxTree, position,
                syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true),
                cancellationToken);
        }

        public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, SyntaxToken preProcessorTokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //  #|
            //  #d|
            //  # |
            //  # d|

            // note: comments are not allowed between the # and item.
            var token = preProcessorTokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1699
            if (token.IsKind(SyntaxKind.HashToken))
P
Pilchie 已提交
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
            {
                return true;
            }

            return false;
        }

        public static bool IsStatementContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
#if false
            // we're in a statement if the thing that comes before allows for
            // statements to follow.  Or if we're on a just started identifier
            // in the first position where a statement can go.
            if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
            {
                return false;
            }
#endif

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

            return token.IsBeginningOfStatementContext();
        }

        public static bool IsGlobalStatementContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
A
Artur Spychaj 已提交
1727
            if (!syntaxTree.IsScript())
P
Pilchie 已提交
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
            {
                return false;
            }

#if false
            if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
            {
                return false;
            }
#endif

            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
                                  .GetPreviousTokenIfTouchingWord(position);

1742
            if (token.IsKind(SyntaxKind.None))
P
Pilchie 已提交
1743 1744
            {
                // global statements can't come before usings/externs
C
CyrusNajmabadi 已提交
1745
                if (syntaxTree.GetRoot(cancellationToken) is CompilationUnitSyntax compilationUnit &&
P
Pilchie 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
                    (compilationUnit.Externs.Count > 0 ||
                    compilationUnit.Usings.Count > 0))
                {
                    return false;
                }

                return true;
            }

            return token.IsBeginningOfGlobalStatementContext();
        }

1758
        public static bool IsInstanceContext(this SyntaxTree syntaxTree, SyntaxToken targetToken, SemanticModel semanticModel, CancellationToken cancellationToken)
P
Pilchie 已提交
1759 1760 1761 1762 1763 1764 1765 1766
        {
#if false
            if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
            {
                return false;
            }
#endif

1767 1768
            var enclosingSymbol = semanticModel.GetEnclosingSymbol(targetToken.SpanStart, cancellationToken);
            return !enclosingSymbol.IsStatic;
P
Pilchie 已提交
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
        }

        private static bool IsInBlock(BlockSyntax bodyOpt, int position)
        {
            if (bodyOpt == null)
            {
                return false;
            }

            return bodyOpt.OpenBraceToken.Span.End <= position &&
                (bodyOpt.CloseBraceToken.IsMissing || position <= bodyOpt.CloseBraceToken.SpanStart);
        }

        public static bool IsPossibleCastTypeContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

J
jasonmalinowski 已提交
1787
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OpenParenToken) &&
P
Pilchie 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
                syntaxTree.IsExpressionContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), false, cancellationToken))
            {
                return true;
            }

            return false;
        }

        public static bool IsDefiniteCastTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1801
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
1802
                token.Parent.IsKind(SyntaxKind.CastExpression))
P
Pilchie 已提交
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
            {
                return true;
            }

            return false;
        }

        public static bool IsConstantExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

            // case |
1815
            if (token.IsKind(SyntaxKind.CaseKeyword) &&
J
jasonmalinowski 已提交
1816
                token.Parent.IsKind(SyntaxKind.CaseSwitchLabel))
P
Pilchie 已提交
1817 1818 1819 1820 1821
            {
                return true;
            }

            // goto case |
1822
            if (token.IsKind(SyntaxKind.CaseKeyword) &&
J
jasonmalinowski 已提交
1823
                token.Parent.IsKind(SyntaxKind.GotoCaseStatement))
P
Pilchie 已提交
1824 1825 1826 1827
            {
                return true;
            }

1828
            if (token.IsKind(SyntaxKind.EqualsToken) &&
J
jasonmalinowski 已提交
1829
                token.Parent.IsKind(SyntaxKind.EqualsValueClause))
P
Pilchie 已提交
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
            {
                var equalsValue = (EqualsValueClauseSyntax)token.Parent;

                if (equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) &&
                    equalsValue.Parent.IsParentKind(SyntaxKind.VariableDeclaration))
                {
                    // class C { const int i = |
                    var fieldDeclaration = equalsValue.GetAncestor<FieldDeclarationSyntax>();
                    if (fieldDeclaration != null)
                    {
                        return fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword);
                    }

                    // void M() { const int i = |
                    var localDeclaration = equalsValue.GetAncestor<LocalDeclarationStatementSyntax>();
                    if (localDeclaration != null)
                    {
                        return localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword);
                    }
                }

                // enum E { A = |
                if (equalsValue.IsParentKind(SyntaxKind.EnumMemberDeclaration))
                {
                    return true;
                }

                // void M(int i = |
                if (equalsValue.IsParentKind(SyntaxKind.Parameter))
                {
                    return true;
                }
            }

1864 1865
            // [Goo( |
            // [Goo(x, |
J
jasonmalinowski 已提交
1866
            if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList) &&
1867 1868
               (token.IsKind(SyntaxKind.CommaToken) ||
                token.IsKind(SyntaxKind.OpenParenToken)))
P
Pilchie 已提交
1869 1870 1871 1872
            {
                return true;
            }

1873
            // [Goo(x: |
1874
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
1875
                token.Parent.IsKind(SyntaxKind.NameColon) &&
P
Pilchie 已提交
1876 1877 1878 1879 1880
                token.Parent.IsParentKind(SyntaxKind.AttributeArgument))
            {
                return true;
            }

1881
            // [Goo(X = |
1882
            if (token.IsKind(SyntaxKind.EqualsToken) &&
J
jasonmalinowski 已提交
1883
                token.Parent.IsKind(SyntaxKind.NameEquals) &&
P
Pilchie 已提交
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 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
                token.Parent.IsParentKind(SyntaxKind.AttributeArgument))
            {
                return true;
            }

            // TODO: Fixed-size buffer declarations

            return false;
        }

        public static bool IsLabelContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);

            var gotoStatement = token.GetAncestor<GotoStatementSyntax>();
            if (gotoStatement != null)
            {
                if (gotoStatement.GotoKeyword == token)
                {
                    return true;
                }

                if (gotoStatement.Expression != null &&
                    !gotoStatement.Expression.IsMissing &&
                    gotoStatement.Expression is IdentifierNameSyntax &&
                    ((IdentifierNameSyntax)gotoStatement.Expression).Identifier == token &&
                    token.IntersectsWith(position))
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsExpressionContext(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            bool attributes,
            CancellationToken cancellationToken,
            SemanticModel semanticModelOpt = null)
        {
            // cases:
            //   var q = |
            //   var q = a|
            // this list is *not* exhaustive.

            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);

            if (token.GetAncestor<ConditionalDirectiveTriviaSyntax>() != null)
            {
                return false;
            }

            if (!attributes)
            {
                if (token.GetAncestor<AttributeListSyntax>() != null)
                {
                    return false;
                }
            }

            if (syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition, cancellationToken))
            {
                return true;
            }

            // no expressions after .   ::   ->
1953 1954 1955
            if (token.IsKind(SyntaxKind.DotToken) ||
                token.IsKind(SyntaxKind.ColonColonToken) ||
                token.IsKind(SyntaxKind.MinusGreaterThanToken))
P
Pilchie 已提交
1956 1957 1958 1959 1960
            {
                return false;
            }

            // Normally you can have any sort of expression after an equals. However, this does not
1961
            // apply to a "using Goo = ..." situation.
1962
            if (token.IsKind(SyntaxKind.EqualsToken))
P
Pilchie 已提交
1963
            {
J
jasonmalinowski 已提交
1964
                if (token.Parent.IsKind(SyntaxKind.NameEquals) &&
P
Pilchie 已提交
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
                    token.Parent.IsParentKind(SyntaxKind.UsingDirective))
                {
                    return false;
                }
            }

            // q = |
            // q -= |
            // q *= |
            // q += |
            // q /= |
            // q ^= |
            // q %= |
            // q &= |
            // q |= |
            // q <<= |
            // q >>= |
1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
            if (token.IsKind(SyntaxKind.EqualsToken) ||
                token.IsKind(SyntaxKind.MinusEqualsToken) ||
                token.IsKind(SyntaxKind.AsteriskEqualsToken) ||
                token.IsKind(SyntaxKind.PlusEqualsToken) ||
                token.IsKind(SyntaxKind.SlashEqualsToken) ||
                token.IsKind(SyntaxKind.ExclamationEqualsToken) ||
                token.IsKind(SyntaxKind.CaretEqualsToken) ||
                token.IsKind(SyntaxKind.AmpersandEqualsToken) ||
                token.IsKind(SyntaxKind.BarEqualsToken) ||
                token.IsKind(SyntaxKind.PercentEqualsToken) ||
                token.IsKind(SyntaxKind.LessThanLessThanEqualsToken) ||
                token.IsKind(SyntaxKind.GreaterThanGreaterThanEqualsToken))
P
Pilchie 已提交
1994 1995 1996 1997 1998
            {
                return true;
            }

            // ( |
1999
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
2000
                token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
P
Pilchie 已提交
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
            {
                return true;
            }

            // - |
            // + |
            // ~ |
            // ! |
            if (token.Parent is PrefixUnaryExpressionSyntax)
            {
                var prefix = token.Parent as PrefixUnaryExpressionSyntax;
                return prefix.OperatorToken == token;
            }

            // not sure about these:
            //   ++ |
            //   -- |
#if false
                token.Kind == SyntaxKind.PlusPlusToken ||
                token.Kind == SyntaxKind.DashDashToken)
#endif
2022 2023 2024 2025 2026 2027 2028
            // await |
            if (token.Parent is AwaitExpressionSyntax)
            {
                var awaitExpression = token.Parent as AwaitExpressionSyntax;
                return awaitExpression.AwaitKeyword == token;
            }

P
Pilchie 已提交
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
            // Check for binary operators.
            // Note:
            //   - We handle < specially as it can be ambiguous with generics.
            //   - We handle * specially because it can be ambiguous with pointer types.

            // a *
            // a /
            // a %
            // a +
            // a -
            // a <<
            // a >>
            // a <
            // a >
            // a &&
            // a ||
            // a &
            // a |
            // a ^
            if (token.Parent is BinaryExpressionSyntax)
            {
                // If the client provided a binding, then check if this is actually generic.  If so,
2051 2052
                // then this is not an expression context. i.e. if we have "Goo < |" then it could
                // be an expression context, or it could be a type context if Goo binds to a type or
P
Pilchie 已提交
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
                // method.
                if (semanticModelOpt != null && syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt))
                {
                    return false;
                }

                var binary = token.Parent as BinaryExpressionSyntax;
                if (binary.OperatorToken == token)
                {
                    // If this is a multiplication expression and a semantic model was passed in,
                    // check to see if the expression to the left is a type name. If it is, treat
                    // this as a pointer type.
2065
                    if (token.IsKind(SyntaxKind.AsteriskToken) && semanticModelOpt != null)
P
Pilchie 已提交
2066
                    {
C
CyrusNajmabadi 已提交
2067
                        if (binary.Left is TypeSyntax type && type.IsPotentialTypeName(semanticModelOpt, cancellationToken))
P
Pilchie 已提交
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }

            // Special case:
2078 2079 2080
            //    Goo * bar
            //    Goo ? bar
            // This parses as a local decl called bar of type Goo* or Goo?
P
Pilchie 已提交
2081
            if (tokenOnLeftOfPosition.IntersectsWith(position) &&
2082
                tokenOnLeftOfPosition.IsKind(SyntaxKind.IdentifierToken))
P
Pilchie 已提交
2083 2084
            {
                var previousToken = tokenOnLeftOfPosition.GetPreviousToken(includeSkipped: true);
2085 2086
                if (previousToken.IsKind(SyntaxKind.AsteriskToken) ||
                    previousToken.IsKind(SyntaxKind.QuestionToken))
P
Pilchie 已提交
2087
                {
J
jasonmalinowski 已提交
2088 2089
                    if (previousToken.Parent.IsKind(SyntaxKind.PointerType) ||
                        previousToken.Parent.IsKind(SyntaxKind.NullableType))
P
Pilchie 已提交
2090 2091 2092 2093 2094 2095 2096 2097
                    {
                        var type = previousToken.Parent as TypeSyntax;
                        if (type.IsParentKind(SyntaxKind.VariableDeclaration) &&
                            type.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement))
                        {
                            var declStatement = type.Parent.Parent as LocalDeclarationStatementSyntax;

                            // note, this doesn't apply for cases where we know it 
C
Charles Stoner 已提交
2098
                            // absolutely is not multiplication or a conditional expression.
P
Pilchie 已提交
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
                            var underlyingType = type is PointerTypeSyntax
                                ? ((PointerTypeSyntax)type).ElementType
                                : ((NullableTypeSyntax)type).ElementType;

                            if (!underlyingType.IsPotentialTypeName(semanticModelOpt, cancellationToken))
                            {
                                return true;
                            }
                        }
                    }
                }
            }

            // new int[|
            // new int[expr, |
2114 2115
            if (token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2116
            {
J
jasonmalinowski 已提交
2117
                if (token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier))
P
Pilchie 已提交
2118 2119 2120 2121 2122
                {
                    return true;
                }
            }

2123
            // goo ? |
2124
            if (token.IsKind(SyntaxKind.QuestionToken) &&
J
jasonmalinowski 已提交
2125
                token.Parent.IsKind(SyntaxKind.ConditionalExpression))
P
Pilchie 已提交
2126 2127 2128 2129 2130 2131 2132 2133 2134
            {
                // If the condition is simply a TypeSyntax that binds to a type, treat this as a nullable type.
                var conditionalExpression = (ConditionalExpressionSyntax)token.Parent;
                var type = conditionalExpression.Condition as TypeSyntax;

                return type == null
                    || !type.IsPotentialTypeName(semanticModelOpt, cancellationToken);
            }

2135
            // goo ? bar : |
2136
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2137
                token.Parent.IsKind(SyntaxKind.ConditionalExpression))
P
Pilchie 已提交
2138 2139 2140 2141 2142 2143 2144
            {
                return true;
            }

            // typeof(|
            // default(|
            // sizeof(|
2145
            if (token.IsKind(SyntaxKind.OpenParenToken))
P
Pilchie 已提交
2146
            {
J
jasonmalinowski 已提交
2147
                if (token.Parent.IsKind(SyntaxKind.TypeOfExpression, SyntaxKind.DefaultExpression, SyntaxKind.SizeOfExpression))
P
Pilchie 已提交
2148 2149 2150 2151 2152
                {
                    return false;
                }
            }

2153 2154 2155 2156 2157 2158 2159 2160 2161
            // var(|
            // var(id, |
            // Those are more likely to be deconstruction-declarations being typed than invocations a method "var"
            if (token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) &&
                token.IsInvocationOfVarExpression())
            {
                return false;
            }

2162 2163
            // Goo(|
            // Goo(expr, |
P
Pilchie 已提交
2164
            // this[|
2165 2166
            // var t = (1, |
            // var t = (| , 2)
2167 2168 2169
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2170
            {
2171
                if (token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList, SyntaxKind.TupleExpression))
P
Pilchie 已提交
2172 2173 2174 2175 2176
                {
                    return true;
                }
            }

2177 2178
            // [Goo(|
            // [Goo(expr, |
P
Pilchie 已提交
2179 2180
            if (attributes)
            {
2181 2182
                if (token.IsKind(SyntaxKind.OpenParenToken) ||
                    token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2183
                {
J
jasonmalinowski 已提交
2184
                    if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList))
P
Pilchie 已提交
2185 2186 2187 2188 2189 2190
                    {
                        return true;
                    }
                }
            }

2191
            // Goo(ref |
2192 2193
            // Goo(in |
            // Goo(out |
2194
            // ref var x = ref |
2195
            if (token.IsKind(SyntaxKind.RefKeyword) ||
2196
                token.IsKind(SyntaxKind.InKeyword) ||
2197
                token.IsKind(SyntaxKind.OutKeyword))
P
Pilchie 已提交
2198
            {
2199
                if (token.Parent.IsKind(SyntaxKind.Argument, SyntaxKind.RefExpression))
P
Pilchie 已提交
2200 2201 2202 2203 2204
                {
                    return true;
                }
            }

2205
            // Goo(bar: |
2206
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2207
                token.Parent.IsKind(SyntaxKind.NameColon) &&
P
Pilchie 已提交
2208 2209 2210 2211 2212 2213
                token.Parent.IsParentKind(SyntaxKind.Argument))
            {
                return true;
            }

            // a => |
2214
            if (token.IsKind(SyntaxKind.EqualsGreaterThanToken))
P
Pilchie 已提交
2215 2216 2217 2218 2219 2220
            {
                return true;
            }

            // new List<int> { |
            // new List<int> { expr, |
2221 2222
            if (token.IsKind(SyntaxKind.OpenBraceToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2223 2224 2225 2226 2227
            {
                if (token.Parent is InitializerExpressionSyntax)
                {
                    // The compiler treats the ambiguous case as an object initializer, so we'll say
                    // expressions are legal here
2228
                    if (token.Parent.IsKind(SyntaxKind.ObjectInitializerExpression) && token.IsKind(SyntaxKind.OpenBraceToken))
P
Pilchie 已提交
2229 2230
                    {
                        // In this position { a$$ =, the user is trying to type an object initializer.
2231
                        if (!token.IntersectsWith(position) && token.GetNextToken().GetNextToken().IsKind(SyntaxKind.EqualsToken))
P
Pilchie 已提交
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
                        {
                            return false;
                        }

                        return true;
                    }

                    // Perform a semantic check to determine whether or not the type being created
                    // can support a collection initializer. If not, this must be an object initializer
                    // and can't be an expression context.
                    if (semanticModelOpt != null &&
                        token.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression))
                    {
                        var objectCreation = (ObjectCreationExpressionSyntax)token.Parent.Parent;
                        var type = semanticModelOpt.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol as ITypeSymbol;
2247 2248
                        var containingSymbol = semanticModelOpt.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
                        if (type != null && !type.CanSupportCollectionInitializer(containingSymbol))
P
Pilchie 已提交
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }

            // for (; |
            // for (; ; |
2260
            if (token.IsKind(SyntaxKind.SemicolonToken) &&
J
jasonmalinowski 已提交
2261
                token.Parent.IsKind(SyntaxKind.ForStatement))
P
Pilchie 已提交
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
            {
                var forStatement = (ForStatementSyntax)token.Parent;
                if (token == forStatement.FirstSemicolonToken ||
                    token == forStatement.SecondSemicolonToken)
                {
                    return true;
                }
            }

            // for ( |
2272
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
2273
                token.Parent.IsKind(SyntaxKind.ForStatement))
P
Pilchie 已提交
2274 2275 2276 2277 2278 2279 2280 2281
            {
                var forStatement = (ForStatementSyntax)token.Parent;
                if (token == forStatement.OpenParenToken)
                {
                    return true;
                }
            }

2282 2283
            // for (; ; Goo(), | 
            // for ( Goo(), |
2284
            if (token.IsKind(SyntaxKind.CommaToken) &&
J
jasonmalinowski 已提交
2285
                token.Parent.IsKind(SyntaxKind.ForStatement))
P
Pilchie 已提交
2286 2287 2288 2289 2290 2291 2292
            {
                return true;
            }

            // foreach (var v in |
            // from a in |
            // join b in |
2293
            if (token.IsKind(SyntaxKind.InKeyword))
P
Pilchie 已提交
2294
            {
2295
                if (token.Parent.IsKind(SyntaxKind.ForEachStatement,
2296
                                        SyntaxKind.ForEachVariableStatement,
2297 2298
                                        SyntaxKind.FromClause,
                                        SyntaxKind.JoinClause))
P
Pilchie 已提交
2299 2300 2301 2302 2303 2304 2305
                {
                    return true;
                }
            }

            // join x in y on |
            // join x in y on a equals |
2306 2307
            if (token.IsKind(SyntaxKind.OnKeyword) ||
                token.IsKind(SyntaxKind.EqualsKeyword))
P
Pilchie 已提交
2308
            {
J
jasonmalinowski 已提交
2309
                if (token.Parent.IsKind(SyntaxKind.JoinClause))
P
Pilchie 已提交
2310 2311 2312 2313 2314 2315
                {
                    return true;
                }
            }

            // where |
2316
            if (token.IsKind(SyntaxKind.WhereKeyword) &&
J
jasonmalinowski 已提交
2317
                token.Parent.IsKind(SyntaxKind.WhereClause))
P
Pilchie 已提交
2318 2319 2320 2321 2322 2323
            {
                return true;
            }

            // orderby |
            // orderby a, |
2324 2325
            if (token.IsKind(SyntaxKind.OrderByKeyword) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2326
            {
J
jasonmalinowski 已提交
2327
                if (token.Parent.IsKind(SyntaxKind.OrderByClause))
P
Pilchie 已提交
2328 2329 2330 2331 2332 2333
                {
                    return true;
                }
            }

            // select |
2334
            if (token.IsKind(SyntaxKind.SelectKeyword) &&
J
jasonmalinowski 已提交
2335
                token.Parent.IsKind(SyntaxKind.SelectClause))
P
Pilchie 已提交
2336 2337 2338 2339 2340 2341
            {
                return true;
            }

            // group |
            // group expr by |
2342 2343
            if (token.IsKind(SyntaxKind.GroupKeyword) ||
                token.IsKind(SyntaxKind.ByKeyword))
P
Pilchie 已提交
2344
            {
J
jasonmalinowski 已提交
2345
                if (token.Parent.IsKind(SyntaxKind.GroupClause))
P
Pilchie 已提交
2346 2347 2348 2349 2350 2351 2352 2353
                {
                    return true;
                }
            }

            // return |
            // yield return |
            // but not: [return |
2354
            if (token.IsKind(SyntaxKind.ReturnKeyword))
P
Pilchie 已提交
2355
            {
2356
                if (token.GetPreviousToken(includeSkipped: true).Kind() != SyntaxKind.OpenBracketToken)
P
Pilchie 已提交
2357 2358 2359 2360 2361 2362
                {
                    return true;
                }
            }

            // throw |
2363
            if (token.IsKind(SyntaxKind.ThrowKeyword))
P
Pilchie 已提交
2364 2365 2366 2367 2368
            {
                return true;
            }

            // while ( |
2369 2370
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhileKeyword))
P
Pilchie 已提交
2371 2372 2373 2374 2375 2376 2377
            {
                return true;
            }

            // todo: handle 'for' cases.

            // using ( |
2378 2379
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
2380 2381 2382 2383 2384
            {
                return true;
            }

            // lock ( |
2385 2386
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.LockKeyword))
P
Pilchie 已提交
2387 2388 2389 2390 2391
            {
                return true;
            }

            // lock ( |
2392 2393
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IfKeyword))
P
Pilchie 已提交
2394 2395 2396 2397 2398
            {
                return true;
            }

            // switch ( |
2399 2400
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.SwitchKeyword))
P
Pilchie 已提交
2401 2402 2403 2404 2405
            {
                return true;
            }

            // checked ( |
2406 2407
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CheckedKeyword))
P
Pilchie 已提交
2408 2409 2410 2411 2412
            {
                return true;
            }

            // unchecked ( |
2413 2414
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UncheckedKeyword))
P
Pilchie 已提交
2415 2416 2417 2418
            {
                return true;
            }

2419
            // when ( |
2420 2421
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhenKeyword))
2422 2423 2424 2425 2426
            {
                return true;
            }

            // (SomeType) |
P
Pilchie 已提交
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
            if (token.IsAfterPossibleCast())
            {
                return true;
            }

            // In anonymous type initializer.
            //
            // new { | We allow new inside of anonymous object member declarators, so that the user
            // can dot into a member afterward. For example:
            //
2437
            // var a = new { new C().Goo };
2438
            if (token.IsKind(SyntaxKind.OpenBraceToken) || token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2439
            {
J
jasonmalinowski 已提交
2440
                if (token.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression))
P
Pilchie 已提交
2441 2442 2443 2444 2445
                {
                    return true;
                }
            }

2446 2447 2448 2449
            // $"{ |
            // $@"{ |
            // $"{x} { |
            // $@"{x} { |
2450
            if (token.IsKind(SyntaxKind.OpenBraceToken))
2451
            {
2452 2453
                return token.Parent.IsKind(SyntaxKind.Interpolation)
                    && ((InterpolationSyntax)token.Parent).OpenBraceToken == token;
2454 2455
            }

P
Pilchie 已提交
2456 2457 2458
            return false;
        }

2459 2460 2461 2462 2463 2464
        public static bool IsInvocationOfVarExpression(this SyntaxToken token)
        {
            return token.Parent.Parent.IsKind(SyntaxKind.InvocationExpression) &&
                ((InvocationExpressionSyntax)token.Parent.Parent).Expression.ToString() == "var";
        }

C
CyrusNajmabadi 已提交
2465
        public static bool IsNameOfContext(this SyntaxTree syntaxTree, int position, SemanticModel semanticModelOpt = null, CancellationToken cancellationToken = default)
2466 2467 2468 2469
        {
            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

2470 2471
            // nameof(Goo.|
            // nameof(Goo.Bar.|
2472
            // Locate the open paren.
2473
            if (token.IsKind(SyntaxKind.DotToken))
2474
            {
2475 2476
                // Could have been parsed as member access
                if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
2477
                {
2478 2479 2480 2481 2482
                    var parentMemberAccess = token.Parent;
                    while (parentMemberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
                    {
                        parentMemberAccess = parentMemberAccess.Parent;
                    }
2483

2484 2485 2486 2487 2488 2489
                    if (parentMemberAccess.IsParentKind(SyntaxKind.Argument) &&
                        parentMemberAccess.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault()))
                    {
                        token = ((ArgumentListSyntax)parentMemberAccess.Parent.Parent).OpenParenToken;
                    }
                }
2490

2491 2492
                // Could have been parsed as a qualified name.
                if (token.Parent.IsKind(SyntaxKind.QualifiedName))
2493
                {
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
                    var parentQualifiedName = token.Parent;
                    while (parentQualifiedName.IsParentKind(SyntaxKind.QualifiedName))
                    {
                        parentQualifiedName = parentQualifiedName.Parent;
                    }

                    if (parentQualifiedName.IsParentKind(SyntaxKind.Argument) &&
                        parentQualifiedName.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault()))
                    {
                        token = ((ArgumentListSyntax)parentQualifiedName.Parent.Parent).OpenParenToken;
                    }
2505 2506 2507
                }
            }

2508 2509
            ExpressionSyntax parentExpression = null;

2510
            // if the nameof expression has a missing close paren, it is parsed as an invocation expression.
2511
            if (token.Parent.IsKind(SyntaxKind.ArgumentList) &&
2512 2513
                token.Parent.Parent is InvocationExpressionSyntax invocationExpression &&
                invocationExpression.IsNameOfInvocation())
2514
            {
2515
                parentExpression = invocationExpression;
2516 2517 2518 2519 2520 2521 2522 2523 2524
            }

            if (parentExpression != null)
            {
                if (semanticModelOpt == null)
                {
                    return true;
                }

2525
                return semanticModelOpt.GetSymbolInfo(parentExpression, cancellationToken).Symbol == null;
2526 2527 2528 2529 2530
            }

            return false;
        }

P
Pilchie 已提交
2531 2532 2533 2534 2535 2536 2537 2538
        public static bool IsIsOrAsContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //    expr |

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

2539 2540 2541 2542 2543 2544
            // Not if the position is *within* a numeric literal
            if (token.IsKind(SyntaxKind.NumericLiteralToken) && token.Span.Contains(position))
            {
                return false;
            }

P
Pilchie 已提交
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
            if (token.GetAncestor<BlockSyntax>() == null)
            {
                return false;
            }

            // is/as are valid after expressions.
            if (token.IsLastTokenOfNode<ExpressionSyntax>())
            {
                // However, many names look like expressions.  For example:
                //    foreach (var |
                // ('var' is a TypeSyntax which is an expression syntax.

                var type = token.GetAncestors<TypeSyntax>().LastOrDefault();
                if (type == null)
                {
                    return true;
                }

                if (type.IsKind(SyntaxKind.GenericName) ||
                    type.IsKind(SyntaxKind.AliasQualifiedName) ||
                    type.IsKind(SyntaxKind.PredefinedType))
                {
                    return false;
                }

                ExpressionSyntax nameExpr = type;
                if (IsRightSideName(nameExpr))
                {
                    nameExpr = (ExpressionSyntax)nameExpr.Parent;
                }

                // If this name is the start of a local variable declaration context, we
                // shouldn't show is or as. For example: for(var |
                if (syntaxTree.IsLocalVariableDeclarationContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), cancellationToken))
                {
                    return false;
                }

                // Not on the left hand side of an object initializer
J
jasonmalinowski 已提交
2584 2585
                if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) &&
                    token.Parent.IsKind(SyntaxKind.IdentifierName) &&
P
Pilchie 已提交
2586 2587 2588 2589 2590
                    (token.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression) || token.Parent.IsParentKind(SyntaxKind.CollectionInitializerExpression)))
                {
                    return false;
                }

2591
                // Not after an 'out' declaration expression. For example: M(out var |
J
jasonmalinowski 已提交
2592 2593
                if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) &&
                    token.Parent.IsKind(SyntaxKind.IdentifierName))
2594 2595
                {
                    if (token.Parent.IsParentKind(SyntaxKind.Argument) &&
J
jasonmalinowski 已提交
2596
                        CodeAnalysis.CSharpExtensions.IsKind(((ArgumentSyntax)token.Parent.Parent).RefOrOutKeyword, SyntaxKind.OutKeyword))
2597 2598 2599 2600 2601
                    {
                        return false;
                    }
                }

P
Pilchie 已提交
2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
                // Now, make sure the name was actually in a location valid for
                // an expression.  If so, then we know we can follow it.
                if (syntaxTree.IsExpressionContext(nameExpr.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(nameExpr.SpanStart, cancellationToken), attributes: false, cancellationToken: cancellationToken))
                {
                    return true;
                }

                return false;
            }

            return false;
        }

        private static bool IsRightSideName(ExpressionSyntax name)
        {
            if (name.Parent != null)
            {
2619
                switch (name.Parent.Kind())
P
Pilchie 已提交
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 2649 2650 2651 2652 2653
                {
                    case SyntaxKind.QualifiedName:
                        return ((QualifiedNameSyntax)name.Parent).Right == name;
                    case SyntaxKind.AliasQualifiedName:
                        return ((AliasQualifiedNameSyntax)name.Parent).Name == name;
                    case SyntaxKind.SimpleMemberAccessExpression:
                        return ((MemberAccessExpressionSyntax)name.Parent).Name == name;
                }
            }

            return false;
        }

        public static bool IsCatchOrFinallyContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            // try { 
            // } |

            // try {
            // } c|

            // try {
            // } catch {
            // } |

            // try {
            // } catch {
            // } c|

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

2654
            if (token.IsKind(SyntaxKind.CloseBraceToken))
P
Pilchie 已提交
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
            {
                var block = token.GetAncestor<BlockSyntax>();

                if (block != null && token == block.GetLastToken(includeSkipped: true))
                {
                    if (block.IsParentKind(SyntaxKind.TryStatement) ||
                        block.IsParentKind(SyntaxKind.CatchClause))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public static bool IsCatchFilterContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition)
        {
            // cases:
            //  catch |
            //  catch i|
            //  catch (declaration) |
            //  catch (declaration) i|

            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

J
jasonmalinowski 已提交
2682
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CatchKeyword))
P
Pilchie 已提交
2683 2684 2685 2686
            {
                return true;
            }

J
jasonmalinowski 已提交
2687
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CloseParenToken) &&
P
Pilchie 已提交
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
                token.Parent.IsKind(SyntaxKind.CatchDeclaration))
            {
                return true;
            }

            return false;
        }

        public static bool IsEnumBaseListContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

            // Options:
            //  enum E : |
            //  enum E : i|

            return
2706
                token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2707
                token.Parent.IsKind(SyntaxKind.BaseList) &&
P
Pilchie 已提交
2708 2709 2710 2711 2712 2713 2714 2715 2716
                token.Parent.IsParentKind(SyntaxKind.EnumDeclaration);
        }

        public static bool IsEnumTypeMemberAccessContext(this SyntaxTree syntaxTree, SemanticModel semanticModel, int position, CancellationToken cancellationToken)
        {
            var token = syntaxTree
                .FindTokenOnLeftOfPosition(position, cancellationToken)
                .GetPreviousTokenIfTouchingWord(position);

J
jasonmalinowski 已提交
2717 2718
            if (!token.IsKind(SyntaxKind.DotToken) ||
                !token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
P
Pilchie 已提交
2719 2720 2721 2722 2723
            {
                return false;
            }

            var memberAccess = (MemberAccessExpressionSyntax)token.Parent;
2724
            var leftHandBinding = semanticModel.GetSymbolInfo(memberAccess.Expression, cancellationToken);
P
Pilchie 已提交
2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
            var symbol = leftHandBinding.GetBestOrAllSymbols().FirstOrDefault();

            if (symbol == null)
            {
                return false;
            }

            switch (symbol.Kind)
            {
                case SymbolKind.NamedType:
                    return ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Enum;
                case SymbolKind.Alias:
                    var target = ((IAliasSymbol)symbol).Target;
                    return target.IsType && ((ITypeSymbol)target).TypeKind == TypeKind.Enum;
            }

            return false;
        }
    }
2744
}