SyntaxTreeExtensions.cs 100.9 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 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
        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) ||
                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) ||
725
                syntaxTree.IsUsingStaticContext(position, cancellationToken) ||
P
Pilchie 已提交
726
                syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
727
                syntaxTree.IsPossibleTupleContext(tokenOnLeftOfPosition, position) ||
P
Pilchie 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
                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);

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

            return false;
        }

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

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

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

            return false;
        }

773 774 775 776 777 778 779 780 781 782
        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 已提交
783 784 785 786 787
        public static bool IsTypeArgumentOfConstraintClause(
            this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            // cases:
            //   where |
788
            //   class Goo<T> : Object where |
P
Pilchie 已提交
789 790 791 792

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

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

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

            return false;
        }

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

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

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

            return false;
        }

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

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

            // Can't come after new()
            //
            //    where T : |
            //    where T : class, |
            //    where T : struct, |
845
            //    where T : Goo, |
846
            if (token.IsKind(SyntaxKind.CommaToken) &&
J
jasonmalinowski 已提交
847
                token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
P
Pilchie 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
            {
                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);

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

            return false;
        }

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

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

            return false;
        }

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

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

            return false;
        }

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

914
            if (token.Kind() != SyntaxKind.LessThanToken && token.Kind() != SyntaxKind.CommaToken)
P
Pilchie 已提交
915 916 917 918 919 920 921 922 923 924
            {
                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 已提交
925
            if (!syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out var nameToken))
P
Pilchie 已提交
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
            {
                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:
            //
946
            // T ? goo<| 
P
Pilchie 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
            //
            // 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 已提交
966 967 968 969 970 971 972 973
            {
                switch (s)
                {
                    case INamedTypeSymbol nt: return nt.Arity > 0;
                    case IMethodSymbol m: return m.Arity > 0;
                    default: return false;
                }
            });
P
Pilchie 已提交
974 975 976 977 978 979 980
        }

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

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

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

                return true;
            }

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

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

                return true;
            }

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

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

P
Pilchie 已提交
1039 1040 1041
            return false;
        }

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

1053 1054 1055 1056
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

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

            return false;
        }

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

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

            return false;
        }

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

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

            return false;
        }

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

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

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

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

            return false;
        }

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

1137 1138
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1139
            {
J
jasonmalinowski 已提交
1140
                if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
P
Pilchie 已提交
1141 1142 1143 1144 1145 1146 1147 1148 1149
                    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.
1150 1151
                if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression) ||
                    token.Parent.IsKind(SyntaxKind.TupleExpression))
P
Pilchie 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
                {
                    return true;
                }
            }

            return false;
        }

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

1166 1167
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1168
            {
J
jasonmalinowski 已提交
1169
                if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
P
Pilchie 已提交
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
                    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);

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

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

            return false;
        }

1202 1203 1204 1205 1206 1207
        /// <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)
1208
        {
1209
            leftToken = leftToken.GetPreviousTokenIfTouchingWord(position);
1210

1211 1212 1213
            // ($$
            // (a, $$
            if (IsPossibleTupleOpenParenOrComma(leftToken))
1214
            {
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
                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;
                }
1244 1245
            }

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
            // (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;
        }

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
        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;
        }

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

R
Ravi Chande 已提交
1281 1282

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

            if (possibleCommaOrParen.Parent.IsKind(
R
Ravi Chande 已提交
1290 1291 1292 1293
                    SyntaxKind.ParenthesizedExpression,
                    SyntaxKind.TupleExpression,
                    SyntaxKind.TupleType,
                    SyntaxKind.CastExpression))
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
            {
                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 已提交
1308

1309 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
            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;
                    }
                }
1379 1380
            }

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
            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;
1420 1421 1422 1423 1424 1425 1426
        }

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

P
Pilchie 已提交
1427 1428 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
        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;
        }

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
        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 已提交
1494 1495
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OutKeyword) &&
                token.Parent.IsKind(SyntaxKind.Argument))
1496 1497 1498 1499
            {
                return true;
            }

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

            return false;
        }

P
Pilchie 已提交
1510 1511 1512 1513 1514
        public static bool IsLocalVariableDeclarationContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //  const var
1515
            //  out var
P
Pilchie 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524
            //  for (var
            //  foreach (var
            //  using (var
            //  from var
            //  join var

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

1525
            if (token.IsKind(SyntaxKind.ConstKeyword) &&
J
jasonmalinowski 已提交
1526
                token.Parent.IsKind(SyntaxKind.LocalDeclarationStatement))
P
Pilchie 已提交
1527 1528 1529 1530
            {
                return true;
            }

1531 1532
            if (token.IsKind(SyntaxKind.OutKeyword) &&
                token.Parent.IsKind(SyntaxKind.Argument) &&
A
AlekseyTs 已提交
1533
                ((ArgumentSyntax)token.Parent).RefOrOutKeyword == token)
1534 1535 1536 1537
            {
                return true;
            }

1538
            if (token.IsKind(SyntaxKind.OpenParenToken))
P
Pilchie 已提交
1539 1540
            {
                var previous = token.GetPreviousToken(includeSkipped: true);
1541 1542 1543
                if (previous.IsKind(SyntaxKind.ForKeyword) ||
                    previous.IsKind(SyntaxKind.ForEachKeyword) ||
                    previous.IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
                {
                    return true;
                }
            }

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

J
jasonmalinowski 已提交
1556
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.JoinKeyword) &&
P
Pilchie 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
                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);

1574 1575
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.FixedKeyword))
P
Pilchie 已提交
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
            {
                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);

1591 1592
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CatchKeyword))
P
Pilchie 已提交
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
            {
                return true;
            }

            return false;
        }

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

1605 1606
            if (token.IsKind(SyntaxKind.IsKeyword) ||
                token.IsKind(SyntaxKind.AsKeyword))
P
Pilchie 已提交
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
            {
                return true;
            }

            return false;
        }

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

1619
            if (token.IsKind(SyntaxKind.NewKeyword))
P
Pilchie 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 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
            {
                // 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);

1687
            if (token.IsKind(SyntaxKind.HashToken))
P
Pilchie 已提交
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
            {
                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 已提交
1715
            if (!syntaxTree.IsScript())
P
Pilchie 已提交
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
            {
                return false;
            }

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

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

1730
            if (token.IsKind(SyntaxKind.None))
P
Pilchie 已提交
1731 1732
            {
                // global statements can't come before usings/externs
C
CyrusNajmabadi 已提交
1733
                if (syntaxTree.GetRoot(cancellationToken) is CompilationUnitSyntax compilationUnit &&
P
Pilchie 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
                    (compilationUnit.Externs.Count > 0 ||
                    compilationUnit.Usings.Count > 0))
                {
                    return false;
                }

                return true;
            }

            return token.IsBeginningOfGlobalStatementContext();
        }

1746
        public static bool IsInstanceContext(this SyntaxTree syntaxTree, SyntaxToken targetToken, SemanticModel semanticModel, CancellationToken cancellationToken)
P
Pilchie 已提交
1747 1748 1749 1750 1751 1752 1753 1754
        {
#if false
            if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
            {
                return false;
            }
#endif

1755 1756
            var enclosingSymbol = semanticModel.GetEnclosingSymbol(targetToken.SpanStart, cancellationToken);
            return !enclosingSymbol.IsStatic;
P
Pilchie 已提交
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
        }

        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 已提交
1775
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OpenParenToken) &&
P
Pilchie 已提交
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
                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);

1789
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
1790
                token.Parent.IsKind(SyntaxKind.CastExpression))
P
Pilchie 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
            {
                return true;
            }

            return false;
        }

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

            // case |
1803
            if (token.IsKind(SyntaxKind.CaseKeyword) &&
J
jasonmalinowski 已提交
1804
                token.Parent.IsKind(SyntaxKind.CaseSwitchLabel))
P
Pilchie 已提交
1805 1806 1807 1808 1809
            {
                return true;
            }

            // goto case |
1810
            if (token.IsKind(SyntaxKind.CaseKeyword) &&
J
jasonmalinowski 已提交
1811
                token.Parent.IsKind(SyntaxKind.GotoCaseStatement))
P
Pilchie 已提交
1812 1813 1814 1815
            {
                return true;
            }

1816
            if (token.IsKind(SyntaxKind.EqualsToken) &&
J
jasonmalinowski 已提交
1817
                token.Parent.IsKind(SyntaxKind.EqualsValueClause))
P
Pilchie 已提交
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
            {
                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;
                }
            }

1852 1853
            // [Goo( |
            // [Goo(x, |
J
jasonmalinowski 已提交
1854
            if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList) &&
1855 1856
               (token.IsKind(SyntaxKind.CommaToken) ||
                token.IsKind(SyntaxKind.OpenParenToken)))
P
Pilchie 已提交
1857 1858 1859 1860
            {
                return true;
            }

1861
            // [Goo(x: |
1862
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
1863
                token.Parent.IsKind(SyntaxKind.NameColon) &&
P
Pilchie 已提交
1864 1865 1866 1867 1868
                token.Parent.IsParentKind(SyntaxKind.AttributeArgument))
            {
                return true;
            }

1869
            // [Goo(X = |
1870
            if (token.IsKind(SyntaxKind.EqualsToken) &&
J
jasonmalinowski 已提交
1871
                token.Parent.IsKind(SyntaxKind.NameEquals) &&
P
Pilchie 已提交
1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 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
                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 .   ::   ->
1941 1942 1943
            if (token.IsKind(SyntaxKind.DotToken) ||
                token.IsKind(SyntaxKind.ColonColonToken) ||
                token.IsKind(SyntaxKind.MinusGreaterThanToken))
P
Pilchie 已提交
1944 1945 1946 1947 1948
            {
                return false;
            }

            // Normally you can have any sort of expression after an equals. However, this does not
1949
            // apply to a "using Goo = ..." situation.
1950
            if (token.IsKind(SyntaxKind.EqualsToken))
P
Pilchie 已提交
1951
            {
J
jasonmalinowski 已提交
1952
                if (token.Parent.IsKind(SyntaxKind.NameEquals) &&
P
Pilchie 已提交
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
                    token.Parent.IsParentKind(SyntaxKind.UsingDirective))
                {
                    return false;
                }
            }

            // q = |
            // q -= |
            // q *= |
            // q += |
            // q /= |
            // q ^= |
            // q %= |
            // q &= |
            // q |= |
            // q <<= |
            // q >>= |
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
            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 已提交
1982 1983 1984 1985 1986
            {
                return true;
            }

            // ( |
1987
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
1988
                token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
P
Pilchie 已提交
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
            {
                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
2010 2011 2012 2013 2014 2015 2016
            // await |
            if (token.Parent is AwaitExpressionSyntax)
            {
                var awaitExpression = token.Parent as AwaitExpressionSyntax;
                return awaitExpression.AwaitKeyword == token;
            }

P
Pilchie 已提交
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
            // 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,
2039 2040
                // 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 已提交
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
                // 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.
2053
                    if (token.IsKind(SyntaxKind.AsteriskToken) && semanticModelOpt != null)
P
Pilchie 已提交
2054
                    {
C
CyrusNajmabadi 已提交
2055
                        if (binary.Left is TypeSyntax type && type.IsPotentialTypeName(semanticModelOpt, cancellationToken))
P
Pilchie 已提交
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }

            // Special case:
2066 2067 2068
            //    Goo * bar
            //    Goo ? bar
            // This parses as a local decl called bar of type Goo* or Goo?
P
Pilchie 已提交
2069
            if (tokenOnLeftOfPosition.IntersectsWith(position) &&
2070
                tokenOnLeftOfPosition.IsKind(SyntaxKind.IdentifierToken))
P
Pilchie 已提交
2071 2072
            {
                var previousToken = tokenOnLeftOfPosition.GetPreviousToken(includeSkipped: true);
2073 2074
                if (previousToken.IsKind(SyntaxKind.AsteriskToken) ||
                    previousToken.IsKind(SyntaxKind.QuestionToken))
P
Pilchie 已提交
2075
                {
J
jasonmalinowski 已提交
2076 2077
                    if (previousToken.Parent.IsKind(SyntaxKind.PointerType) ||
                        previousToken.Parent.IsKind(SyntaxKind.NullableType))
P
Pilchie 已提交
2078 2079 2080 2081 2082 2083 2084 2085
                    {
                        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 已提交
2086
                            // absolutely is not multiplication or a conditional expression.
P
Pilchie 已提交
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
                            var underlyingType = type is PointerTypeSyntax
                                ? ((PointerTypeSyntax)type).ElementType
                                : ((NullableTypeSyntax)type).ElementType;

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

            // new int[|
            // new int[expr, |
2102 2103
            if (token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2104
            {
J
jasonmalinowski 已提交
2105
                if (token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier))
P
Pilchie 已提交
2106 2107 2108 2109 2110
                {
                    return true;
                }
            }

2111
            // goo ? |
2112
            if (token.IsKind(SyntaxKind.QuestionToken) &&
J
jasonmalinowski 已提交
2113
                token.Parent.IsKind(SyntaxKind.ConditionalExpression))
P
Pilchie 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122
            {
                // 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);
            }

2123
            // goo ? bar : |
2124
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2125
                token.Parent.IsKind(SyntaxKind.ConditionalExpression))
P
Pilchie 已提交
2126 2127 2128 2129 2130 2131 2132
            {
                return true;
            }

            // typeof(|
            // default(|
            // sizeof(|
2133
            if (token.IsKind(SyntaxKind.OpenParenToken))
P
Pilchie 已提交
2134
            {
J
jasonmalinowski 已提交
2135
                if (token.Parent.IsKind(SyntaxKind.TypeOfExpression, SyntaxKind.DefaultExpression, SyntaxKind.SizeOfExpression))
P
Pilchie 已提交
2136 2137 2138 2139 2140
                {
                    return false;
                }
            }

2141 2142 2143 2144 2145 2146 2147 2148 2149
            // 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;
            }

2150 2151
            // Goo(|
            // Goo(expr, |
P
Pilchie 已提交
2152
            // this[|
2153 2154
            // var t = (1, |
            // var t = (| , 2)
2155 2156 2157
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2158
            {
2159
                if (token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList, SyntaxKind.TupleExpression))
P
Pilchie 已提交
2160 2161 2162 2163 2164
                {
                    return true;
                }
            }

2165 2166
            // [Goo(|
            // [Goo(expr, |
P
Pilchie 已提交
2167 2168
            if (attributes)
            {
2169 2170
                if (token.IsKind(SyntaxKind.OpenParenToken) ||
                    token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2171
                {
J
jasonmalinowski 已提交
2172
                    if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList))
P
Pilchie 已提交
2173 2174 2175 2176 2177 2178
                    {
                        return true;
                    }
                }
            }

2179
            // Goo(ref |
2180 2181
            // Goo(in |
            // Goo(out |
2182
            // ref var x = ref |
2183
            if (token.IsKind(SyntaxKind.RefKeyword) ||
2184
                token.IsKind(SyntaxKind.InKeyword) ||
2185
                token.IsKind(SyntaxKind.OutKeyword))
P
Pilchie 已提交
2186
            {
2187
                if (token.Parent.IsKind(SyntaxKind.Argument, SyntaxKind.RefExpression))
P
Pilchie 已提交
2188 2189 2190 2191 2192
                {
                    return true;
                }
            }

2193
            // Goo(bar: |
2194
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2195
                token.Parent.IsKind(SyntaxKind.NameColon) &&
P
Pilchie 已提交
2196 2197 2198 2199 2200 2201
                token.Parent.IsParentKind(SyntaxKind.Argument))
            {
                return true;
            }

            // a => |
2202
            if (token.IsKind(SyntaxKind.EqualsGreaterThanToken))
P
Pilchie 已提交
2203 2204 2205 2206 2207 2208
            {
                return true;
            }

            // new List<int> { |
            // new List<int> { expr, |
2209 2210
            if (token.IsKind(SyntaxKind.OpenBraceToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2211 2212 2213 2214 2215
            {
                if (token.Parent is InitializerExpressionSyntax)
                {
                    // The compiler treats the ambiguous case as an object initializer, so we'll say
                    // expressions are legal here
2216
                    if (token.Parent.IsKind(SyntaxKind.ObjectInitializerExpression) && token.IsKind(SyntaxKind.OpenBraceToken))
P
Pilchie 已提交
2217 2218
                    {
                        // In this position { a$$ =, the user is trying to type an object initializer.
2219
                        if (!token.IntersectsWith(position) && token.GetNextToken().GetNextToken().IsKind(SyntaxKind.EqualsToken))
P
Pilchie 已提交
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
                        {
                            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;
2235 2236
                        var containingSymbol = semanticModelOpt.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
                        if (type != null && !type.CanSupportCollectionInitializer(containingSymbol))
P
Pilchie 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }

            // for (; |
            // for (; ; |
2248
            if (token.IsKind(SyntaxKind.SemicolonToken) &&
J
jasonmalinowski 已提交
2249
                token.Parent.IsKind(SyntaxKind.ForStatement))
P
Pilchie 已提交
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
            {
                var forStatement = (ForStatementSyntax)token.Parent;
                if (token == forStatement.FirstSemicolonToken ||
                    token == forStatement.SecondSemicolonToken)
                {
                    return true;
                }
            }

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

2270 2271
            // for (; ; Goo(), | 
            // for ( Goo(), |
2272
            if (token.IsKind(SyntaxKind.CommaToken) &&
J
jasonmalinowski 已提交
2273
                token.Parent.IsKind(SyntaxKind.ForStatement))
P
Pilchie 已提交
2274 2275 2276 2277 2278 2279 2280
            {
                return true;
            }

            // foreach (var v in |
            // from a in |
            // join b in |
2281
            if (token.IsKind(SyntaxKind.InKeyword))
P
Pilchie 已提交
2282
            {
2283
                if (token.Parent.IsKind(SyntaxKind.ForEachStatement,
2284
                                        SyntaxKind.ForEachVariableStatement,
2285 2286
                                        SyntaxKind.FromClause,
                                        SyntaxKind.JoinClause))
P
Pilchie 已提交
2287 2288 2289 2290 2291 2292 2293
                {
                    return true;
                }
            }

            // join x in y on |
            // join x in y on a equals |
2294 2295
            if (token.IsKind(SyntaxKind.OnKeyword) ||
                token.IsKind(SyntaxKind.EqualsKeyword))
P
Pilchie 已提交
2296
            {
J
jasonmalinowski 已提交
2297
                if (token.Parent.IsKind(SyntaxKind.JoinClause))
P
Pilchie 已提交
2298 2299 2300 2301 2302 2303
                {
                    return true;
                }
            }

            // where |
2304
            if (token.IsKind(SyntaxKind.WhereKeyword) &&
J
jasonmalinowski 已提交
2305
                token.Parent.IsKind(SyntaxKind.WhereClause))
P
Pilchie 已提交
2306 2307 2308 2309 2310 2311
            {
                return true;
            }

            // orderby |
            // orderby a, |
2312 2313
            if (token.IsKind(SyntaxKind.OrderByKeyword) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2314
            {
J
jasonmalinowski 已提交
2315
                if (token.Parent.IsKind(SyntaxKind.OrderByClause))
P
Pilchie 已提交
2316 2317 2318 2319 2320 2321
                {
                    return true;
                }
            }

            // select |
2322
            if (token.IsKind(SyntaxKind.SelectKeyword) &&
J
jasonmalinowski 已提交
2323
                token.Parent.IsKind(SyntaxKind.SelectClause))
P
Pilchie 已提交
2324 2325 2326 2327 2328 2329
            {
                return true;
            }

            // group |
            // group expr by |
2330 2331
            if (token.IsKind(SyntaxKind.GroupKeyword) ||
                token.IsKind(SyntaxKind.ByKeyword))
P
Pilchie 已提交
2332
            {
J
jasonmalinowski 已提交
2333
                if (token.Parent.IsKind(SyntaxKind.GroupClause))
P
Pilchie 已提交
2334 2335 2336 2337 2338 2339 2340 2341
                {
                    return true;
                }
            }

            // return |
            // yield return |
            // but not: [return |
2342
            if (token.IsKind(SyntaxKind.ReturnKeyword))
P
Pilchie 已提交
2343
            {
2344
                if (token.GetPreviousToken(includeSkipped: true).Kind() != SyntaxKind.OpenBracketToken)
P
Pilchie 已提交
2345 2346 2347 2348 2349 2350
                {
                    return true;
                }
            }

            // throw |
2351
            if (token.IsKind(SyntaxKind.ThrowKeyword))
P
Pilchie 已提交
2352 2353 2354 2355 2356
            {
                return true;
            }

            // while ( |
2357 2358
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhileKeyword))
P
Pilchie 已提交
2359 2360 2361 2362 2363 2364 2365
            {
                return true;
            }

            // todo: handle 'for' cases.

            // using ( |
2366 2367
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
2368 2369 2370 2371 2372
            {
                return true;
            }

            // lock ( |
2373 2374
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.LockKeyword))
P
Pilchie 已提交
2375 2376 2377 2378 2379
            {
                return true;
            }

            // lock ( |
2380 2381
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IfKeyword))
P
Pilchie 已提交
2382 2383 2384 2385 2386
            {
                return true;
            }

            // switch ( |
2387 2388
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.SwitchKeyword))
P
Pilchie 已提交
2389 2390 2391 2392 2393
            {
                return true;
            }

            // checked ( |
2394 2395
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CheckedKeyword))
P
Pilchie 已提交
2396 2397 2398 2399 2400
            {
                return true;
            }

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

2407
            // when ( |
2408 2409
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhenKeyword))
2410 2411 2412 2413 2414
            {
                return true;
            }

            // (SomeType) |
P
Pilchie 已提交
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
            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:
            //
2425
            // var a = new { new C().Goo };
2426
            if (token.IsKind(SyntaxKind.OpenBraceToken) || token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2427
            {
J
jasonmalinowski 已提交
2428
                if (token.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression))
P
Pilchie 已提交
2429 2430 2431 2432 2433
                {
                    return true;
                }
            }

2434 2435 2436 2437
            // $"{ |
            // $@"{ |
            // $"{x} { |
            // $@"{x} { |
2438
            if (token.IsKind(SyntaxKind.OpenBraceToken))
2439
            {
2440 2441
                return token.Parent.IsKind(SyntaxKind.Interpolation)
                    && ((InterpolationSyntax)token.Parent).OpenBraceToken == token;
2442 2443
            }

P
Pilchie 已提交
2444 2445 2446
            return false;
        }

2447 2448 2449 2450 2451 2452
        public static bool IsInvocationOfVarExpression(this SyntaxToken token)
        {
            return token.Parent.Parent.IsKind(SyntaxKind.InvocationExpression) &&
                ((InvocationExpressionSyntax)token.Parent.Parent).Expression.ToString() == "var";
        }

C
CyrusNajmabadi 已提交
2453
        public static bool IsNameOfContext(this SyntaxTree syntaxTree, int position, SemanticModel semanticModelOpt = null, CancellationToken cancellationToken = default)
2454 2455 2456 2457
        {
            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

2458 2459
            // nameof(Goo.|
            // nameof(Goo.Bar.|
2460
            // Locate the open paren.
2461
            if (token.IsKind(SyntaxKind.DotToken))
2462
            {
2463 2464
                // Could have been parsed as member access
                if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
2465
                {
2466 2467 2468 2469 2470
                    var parentMemberAccess = token.Parent;
                    while (parentMemberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
                    {
                        parentMemberAccess = parentMemberAccess.Parent;
                    }
2471

2472 2473 2474 2475 2476 2477
                    if (parentMemberAccess.IsParentKind(SyntaxKind.Argument) &&
                        parentMemberAccess.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault()))
                    {
                        token = ((ArgumentListSyntax)parentMemberAccess.Parent.Parent).OpenParenToken;
                    }
                }
2478

2479 2480
                // Could have been parsed as a qualified name.
                if (token.Parent.IsKind(SyntaxKind.QualifiedName))
2481
                {
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
                    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;
                    }
2493 2494 2495
                }
            }

2496 2497
            ExpressionSyntax parentExpression = null;

2498
            // if the nameof expression has a missing close paren, it is parsed as an invocation expression.
2499
            if (token.Parent.IsKind(SyntaxKind.ArgumentList) &&
2500 2501
                token.Parent.Parent is InvocationExpressionSyntax invocationExpression &&
                invocationExpression.IsNameOfInvocation())
2502
            {
2503
                parentExpression = invocationExpression;
2504 2505 2506 2507 2508 2509 2510 2511 2512
            }

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

2513
                return semanticModelOpt.GetSymbolInfo(parentExpression, cancellationToken).Symbol == null;
2514 2515 2516 2517 2518
            }

            return false;
        }

P
Pilchie 已提交
2519 2520 2521 2522 2523 2524 2525 2526
        public static bool IsIsOrAsContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //    expr |

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

2527 2528 2529 2530 2531 2532
            // Not if the position is *within* a numeric literal
            if (token.IsKind(SyntaxKind.NumericLiteralToken) && token.Span.Contains(position))
            {
                return false;
            }

P
Pilchie 已提交
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 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
            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 已提交
2572 2573
                if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) &&
                    token.Parent.IsKind(SyntaxKind.IdentifierName) &&
P
Pilchie 已提交
2574 2575 2576 2577 2578
                    (token.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression) || token.Parent.IsParentKind(SyntaxKind.CollectionInitializerExpression)))
                {
                    return false;
                }

2579
                // Not after an 'out' declaration expression. For example: M(out var |
J
jasonmalinowski 已提交
2580 2581
                if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) &&
                    token.Parent.IsKind(SyntaxKind.IdentifierName))
2582 2583
                {
                    if (token.Parent.IsParentKind(SyntaxKind.Argument) &&
J
jasonmalinowski 已提交
2584
                        CodeAnalysis.CSharpExtensions.IsKind(((ArgumentSyntax)token.Parent.Parent).RefOrOutKeyword, SyntaxKind.OutKeyword))
2585 2586 2587 2588 2589
                    {
                        return false;
                    }
                }

P
Pilchie 已提交
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
                // 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)
            {
2607
                switch (name.Parent.Kind())
P
Pilchie 已提交
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
                {
                    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);

2642
            if (token.IsKind(SyntaxKind.CloseBraceToken))
P
Pilchie 已提交
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
            {
                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 已提交
2670
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CatchKeyword))
P
Pilchie 已提交
2671 2672 2673 2674
            {
                return true;
            }

J
jasonmalinowski 已提交
2675
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CloseParenToken) &&
P
Pilchie 已提交
2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
                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
2694
                token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2695
                token.Parent.IsKind(SyntaxKind.BaseList) &&
P
Pilchie 已提交
2696 2697 2698 2699 2700 2701 2702 2703 2704
                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 已提交
2705 2706
            if (!token.IsKind(SyntaxKind.DotToken) ||
                !token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
P
Pilchie 已提交
2707 2708 2709 2710 2711
            {
                return false;
            }

            var memberAccess = (MemberAccessExpressionSyntax)token.Parent;
2712
            var leftHandBinding = semanticModel.GetSymbolInfo(memberAccess.Expression, cancellationToken);
P
Pilchie 已提交
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
            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;
        }
    }
2732
}