SyntaxTreeExtensions.cs 102.3 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
            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();
580 581 582 583 584 585 586 587

                // ref $$
                // readonly ref $$
                if (container.IsKind(SyntaxKind.IncompleteMember))
                {
                    return ((IncompleteMemberSyntax)container).Type.IsKind(SyntaxKind.RefType);
                }

P
Pilchie 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
                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::
617 618
            if (token.IsKind(SyntaxKind.ColonColonToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.GlobalKeyword))
P
Pilchie 已提交
619 620 621 622 623 624 625 626 627 628 629
            {
                return true;
            }

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

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

630
            if (token.IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
631 632 633 634
            {
                var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
                if (usingDirective != null)
                {
635
                    if (token.GetNextToken(includeSkipped: true).Kind() != SyntaxKind.EqualsToken &&
P
Pilchie 已提交
636 637 638 639 640 641 642
                        usingDirective.Alias == null)
                    {
                        return true;
                    }
                }
            }

643 644 645 646 647 648
            // using static |
            if (token.IsStaticKeywordInUsingDirective())
            {
                return true;
            }

P
Pilchie 已提交
649 650 651 652 653
            // 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);
        }

654 655
        public static bool IsNamespaceDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
656
            if (syntaxTree.IsScript() || syntaxTree.IsInNonUserCode(position, cancellationToken))
657 658 659 660
            {
                return false;
            }

661 662 663 664 665 666
            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
                                  .GetPreviousTokenIfTouchingWord(position);

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

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

669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
        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 已提交
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        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) ||
712 713
                syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
                syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
P
Pilchie 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
                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) ||
735
                syntaxTree.IsUsingStaticContext(position, cancellationToken) ||
P
Pilchie 已提交
736
                syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
737
                syntaxTree.IsPossibleTupleContext(tokenOnLeftOfPosition, position) ||
P
Pilchie 已提交
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                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);

755 756
            if (token.IsKind(SyntaxKind.ColonToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
757
            {
J
jasonmalinowski 已提交
758
                if (token.Parent.IsKind(SyntaxKind.BaseList))
P
Pilchie 已提交
759 760 761 762 763 764 765 766 767 768
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsUsingAliasContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
769
            // using Goo = |
P
Pilchie 已提交
770 771 772 773

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

774
            if (token.IsKind(SyntaxKind.EqualsToken) &&
P
Pilchie 已提交
775 776 777 778 779 780 781 782
                token.GetAncestor<UsingDirectiveSyntax>() != null)
            {
                return true;
            }

            return false;
        }

783 784 785 786 787 788 789 790 791 792
        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 已提交
793 794 795 796 797
        public static bool IsTypeArgumentOfConstraintClause(
            this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
        {
            // cases:
            //   where |
798
            //   class Goo<T> : Object where |
P
Pilchie 已提交
799 800 801 802

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

803
            if (token.IsKind(SyntaxKind.WhereKeyword) &&
J
jasonmalinowski 已提交
804
                token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
P
Pilchie 已提交
805 806 807 808
            {
                return true;
            }

809
            if (token.IsKind(SyntaxKind.IdentifierToken) &&
P
Pilchie 已提交
810
                token.HasMatchingText(SyntaxKind.WhereKeyword) &&
J
jasonmalinowski 已提交
811
                token.Parent.IsKind(SyntaxKind.IdentifierName) &&
812 813
                token.Parent.IsParentKind(SyntaxKind.SimpleBaseType) &&
                token.Parent.Parent.IsParentKind(SyntaxKind.BaseList))
P
Pilchie 已提交
814 815 816 817 818 819 820
            {
                return true;
            }

            return false;
        }

821
        public static bool IsTypeParameterConstraintStartContext(
P
Pilchie 已提交
822 823 824 825 826 827 828 829
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //   where T : |

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

830 831 832
            if (token.IsKind(SyntaxKind.ColonToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IdentifierToken) &&
                token.GetPreviousToken(includeSkipped: true).GetPreviousToken().IsKind(SyntaxKind.WhereKeyword))
P
Pilchie 已提交
833 834 835 836 837 838 839 840 841
            {
                return true;
            }

            return false;
        }

        public static bool IsTypeParameterConstraintContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
842
            if (syntaxTree.IsTypeParameterConstraintStartContext(position, tokenOnLeftOfPosition, cancellationToken))
P
Pilchie 已提交
843 844 845 846 847 848 849 850 851 852 853 854
            {
                return true;
            }

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

            // Can't come after new()
            //
            //    where T : |
            //    where T : class, |
            //    where T : struct, |
855
            //    where T : Goo, |
856
            if (token.IsKind(SyntaxKind.CommaToken) &&
J
jasonmalinowski 已提交
857
                token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause))
P
Pilchie 已提交
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
            {
                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);

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

            return false;
        }

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

889
            if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.DefaultExpression))
P
Pilchie 已提交
890 891 892 893 894 895 896 897 898 899 900 901
            {
                return true;
            }

            return false;
        }

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

902
            if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.SizeOfExpression))
P
Pilchie 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
            {
                return true;
            }

            return false;
        }

        public static bool IsGenericTypeArgumentContext(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            CancellationToken cancellationToken,
            SemanticModel semanticModelOpt = null)
        {
            // cases: 
918 919 920
            //    Goo<|
            //    Goo<Bar,|
            //    Goo<Bar<Baz<int[],|
P
Pilchie 已提交
921 922 923
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

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

        public static bool IsParameterModifierContext(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            CancellationToken cancellationToken,
991
            bool includeOperators = false,
992
            bool isThisKeyword = false)
P
Pilchie 已提交
993 994
        {
            // cases:
995 996 997
            //   Goo(|
            //   Goo(int i, |
            //   Goo([Bar]|
P
Pilchie 已提交
998 999 1000
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1001
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
1002
                token.Parent.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
P
Pilchie 已提交
1003 1004 1005 1006
            {
                return true;
            }

1007
            if (token.IsKind(SyntaxKind.CommaToken) &&
1008
                token.Parent.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
P
Pilchie 已提交
1009
            {
1010
                if (isThisKeyword)
P
Pilchie 已提交
1011 1012 1013 1014
                {
                    var parameterList = token.GetAncestor<ParameterListSyntax>();
                    var commaIndex = parameterList.Parameters.GetWithSeparators().IndexOf(token);
                    var index = commaIndex / 2 + 1;
1015
                    return index == 0;
P
Pilchie 已提交
1016 1017 1018 1019 1020
                }

                return true;
            }

1021
            if (token.IsKind(SyntaxKind.CloseBracketToken) &&
J
jasonmalinowski 已提交
1022
                token.Parent.IsKind(SyntaxKind.AttributeList) &&
P
Pilchie 已提交
1023
                token.Parent.IsParentKind(SyntaxKind.Parameter) &&
1024
                token.Parent.GetParent().GetParent().IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
P
Pilchie 已提交
1025
            {
1026
                if (isThisKeyword)
P
Pilchie 已提交
1027 1028 1029 1030 1031
                {
                    var parameter = token.GetAncestor<ParameterSyntax>();
                    var parameterList = parameter.GetAncestorOrThis<ParameterListSyntax>();

                    int parameterIndex = parameterList.Parameters.IndexOf(parameter);
1032
                    return parameterIndex == 0;
P
Pilchie 已提交
1033 1034 1035 1036 1037
                }

                return true;
            }

1038
            if (isThisKeyword &&
O
Omar Tawfik 已提交
1039
                (token.IsKind(SyntaxKind.RefKeyword) || token.IsKind(SyntaxKind.InKeyword)) &&
1040
                token.Parent.GetParent().IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators))
1041 1042 1043 1044 1045 1046 1047 1048
            {
                var parameter = token.GetAncestor<ParameterSyntax>();
                var parameterList = parameter.GetAncestorOrThis<ParameterListSyntax>();

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

P
Pilchie 已提交
1049 1050 1051
            return false;
        }

1052 1053 1054 1055 1056 1057 1058
        public static bool IsParamsModifierContext(
            this SyntaxTree syntaxTree,
            int position,
            SyntaxToken tokenOnLeftOfPosition,
            CancellationToken cancellationToken)
        {
            if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, cancellationToken))
1059
            {
1060
                return true;
1061
            }
1062

1063 1064 1065 1066
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

            if (token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken))
1067
            {
1068
                return token.Parent.IsKind(SyntaxKind.BracketedParameterList);
1069 1070 1071 1072 1073
            }

            return false;
        }

P
Pilchie 已提交
1074 1075 1076 1077 1078 1079
        public static bool IsDelegateReturnTypeContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            var token = tokenOnLeftOfPosition;
            token = token.GetPreviousTokenIfTouchingWord(position);

1080
            if (token.IsKind(SyntaxKind.DelegateKeyword) &&
J
jasonmalinowski 已提交
1081
                token.Parent.IsKind(SyntaxKind.DelegateDeclaration))
P
Pilchie 已提交
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
            {
                return true;
            }

            return false;
        }

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

1095
            if (token.IsKind(SyntaxKind.OperatorKeyword))
P
Pilchie 已提交
1096
            {
1097 1098
                if (token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ImplicitKeyword) ||
                    token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ExplicitKeyword))
P
Pilchie 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                {
                    return true;
                }
            }

            return false;
        }

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

1111 1112
            if (token.IsKind(SyntaxKind.RefKeyword) ||
                token.IsKind(SyntaxKind.OutKeyword) ||
1113
                token.IsKind(SyntaxKind.InKeyword) ||
1114 1115
                token.IsKind(SyntaxKind.ParamsKeyword) ||
                token.IsKind(SyntaxKind.ThisKeyword))
P
Pilchie 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
            {
                position = token.SpanStart;
                tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            }

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

            // int this[ |
            // int this[int i, |
1128 1129 1130
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1131
            {
J
jasonmalinowski 已提交
1132
                if (token.Parent.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList))
P
Pilchie 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
                {
                    return true;
                }
            }

            return false;
        }

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

1147 1148
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1149
            {
J
jasonmalinowski 已提交
1150
                if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
P
Pilchie 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159
                    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.
1160 1161
                if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression) ||
                    token.Parent.IsKind(SyntaxKind.TupleExpression))
P
Pilchie 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
                {
                    return true;
                }
            }

            return false;
        }

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

1176 1177
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
1178
            {
J
jasonmalinowski 已提交
1179
                if (token.Parent.IsKind(SyntaxKind.ParameterList) &&
P
Pilchie 已提交
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
                    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);

1195
            if (token.IsKind(SyntaxKind.RefKeyword) ||
1196
                token.IsKind(SyntaxKind.InKeyword) ||
1197
                token.IsKind(SyntaxKind.OutKeyword))
P
Pilchie 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
            {
                position = token.SpanStart;
                tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            }

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

            return false;
        }

1212 1213 1214 1215 1216 1217
        /// <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)
1218
        {
1219
            leftToken = leftToken.GetPreviousTokenIfTouchingWord(position);
1220

1221 1222 1223
            // ($$
            // (a, $$
            if (IsPossibleTupleOpenParenOrComma(leftToken))
1224
            {
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
                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;
                }
1254 1255
            }

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
            // (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;
        }

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
        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;
        }

1286 1287 1288 1289 1290
        private static SyntaxToken FindTokenOnLeftOfNode(SyntaxNode node)
        {
            return node.FindTokenOnLeftOfPosition(node.SpanStart);
        }

R
Ravi Chande 已提交
1291 1292

        public static bool IsPossibleTupleOpenParenOrComma(SyntaxToken possibleCommaOrParen)
1293 1294 1295 1296 1297 1298 1299
        {
            if (!possibleCommaOrParen.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken))
            {
                return false;
            }

            if (possibleCommaOrParen.Parent.IsKind(
R
Ravi Chande 已提交
1300 1301 1302 1303
                    SyntaxKind.ParenthesizedExpression,
                    SyntaxKind.TupleExpression,
                    SyntaxKind.TupleType,
                    SyntaxKind.CastExpression))
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            {
                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 已提交
1318

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
            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;
1335 1336
            if (leftToken.Parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation) ||
                leftToken.Parent.IsParentKind(SyntaxKind.ParenthesizedVariableDesignation))
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
            {
                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;
                    }
                }
1390 1391
            }

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
            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;
1431 1432 1433 1434 1435 1436 1437
        }

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

P
Pilchie 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        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;
        }

1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
        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 已提交
1505 1506
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OutKeyword) &&
                token.Parent.IsKind(SyntaxKind.Argument))
1507 1508 1509 1510
            {
                return true;
            }

J
jasonmalinowski 已提交
1511 1512
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.EqualsToken) &&
                token.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
1513 1514 1515 1516 1517 1518 1519 1520
                token.Parent.IsParentKind(SyntaxKind.VariableDeclarator))
            {
                return true;
            }

            return false;
        }

P
Pilchie 已提交
1521 1522 1523
        public static bool IsLocalVariableDeclarationContext(
            this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
Š
Šimon Koníček 已提交
1524
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
P
Pilchie 已提交
1525

Š
Šimon Koníček 已提交
1526
            // const |
1527
            if (token.IsKind(SyntaxKind.ConstKeyword) &&
J
jasonmalinowski 已提交
1528
                token.Parent.IsKind(SyntaxKind.LocalDeclarationStatement))
P
Pilchie 已提交
1529 1530 1531 1532
            {
                return true;
            }

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

Š
Šimon Koníček 已提交
1543
            // out |
1544 1545
            if (token.IsKind(SyntaxKind.OutKeyword) &&
                token.Parent.IsKind(SyntaxKind.Argument) &&
Š
Šimon Koníček 已提交
1546
                ((ArgumentSyntax)token.Parent).RefKindKeyword == token)
1547 1548 1549 1550
            {
                return true;
            }

Š
Šimon Koníček 已提交
1551 1552 1553
            // for ( |
            // foreach ( |
            // using ( |
1554
            if (token.IsKind(SyntaxKind.OpenParenToken))
P
Pilchie 已提交
1555 1556
            {
                var previous = token.GetPreviousToken(includeSkipped: true);
1557 1558 1559
                if (previous.IsKind(SyntaxKind.ForKeyword) ||
                    previous.IsKind(SyntaxKind.ForEachKeyword) ||
                    previous.IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
1560 1561 1562 1563 1564
                {
                    return true;
                }
            }

Š
Šimon Koníček 已提交
1565
            // from |
P
Pilchie 已提交
1566 1567 1568 1569 1570 1571 1572
            var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken);
            if (token.IsKindOrHasMatchingText(SyntaxKind.FromKeyword) &&
                syntaxTree.IsValidContextForFromClause(token.SpanStart, tokenOnLeftOfStart, cancellationToken))
            {
                return true;
            }

Š
Šimon Koníček 已提交
1573
            // join |
J
jasonmalinowski 已提交
1574
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.JoinKeyword) &&
P
Pilchie 已提交
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
                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);

1592 1593
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.FixedKeyword))
P
Pilchie 已提交
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
            {
                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);

1609 1610
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CatchKeyword))
P
Pilchie 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
            {
                return true;
            }

            return false;
        }

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

1623 1624
            if (token.IsKind(SyntaxKind.IsKeyword) ||
                token.IsKind(SyntaxKind.AsKeyword))
P
Pilchie 已提交
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
            {
                return true;
            }

            return false;
        }

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

1637
            if (token.IsKind(SyntaxKind.NewKeyword))
P
Pilchie 已提交
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
            {
                // 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);

1705
            if (token.IsKind(SyntaxKind.HashToken))
P
Pilchie 已提交
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
            {
                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 已提交
1733
            if (!syntaxTree.IsScript())
P
Pilchie 已提交
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
            {
                return false;
            }

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

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

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

                return true;
            }

            return token.IsBeginningOfGlobalStatementContext();
        }

1764
        public static bool IsInstanceContext(this SyntaxTree syntaxTree, SyntaxToken targetToken, SemanticModel semanticModel, CancellationToken cancellationToken)
P
Pilchie 已提交
1765 1766 1767 1768 1769 1770 1771 1772
        {
#if false
            if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken))
            {
                return false;
            }
#endif

1773
            var enclosingSymbol = semanticModel.GetEnclosingSymbol(targetToken.SpanStart, cancellationToken);
1774

1775
            while (enclosingSymbol is IMethodSymbol method && (method.MethodKind == MethodKind.LocalFunction || method.MethodKind == MethodKind.AnonymousFunction))
1776 1777 1778 1779 1780
            {
                // It is allowed to reference the instance (`this`) within a local function, as long as the containing method allows it
                enclosingSymbol = method.ContainingSymbol;
            }

1781
            return !enclosingSymbol.IsStatic;
P
Pilchie 已提交
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
        }

        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 已提交
1800
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OpenParenToken) &&
P
Pilchie 已提交
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
                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);

1814
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
1815
                token.Parent.IsKind(SyntaxKind.CastExpression))
P
Pilchie 已提交
1816 1817 1818 1819 1820 1821 1822
            {
                return true;
            }

            return false;
        }

1823 1824
        public static bool IsConstantExpressionContext(this SyntaxTree syntaxTree, int position,
            SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
P
Pilchie 已提交
1825
        {
1826
            if (IsPatternContext(syntaxTree, tokenOnLeftOfPosition, position))
P
Pilchie 已提交
1827 1828 1829 1830
            {
                return true;
            }

1831
            var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position);
P
Pilchie 已提交
1832 1833

            // goto case |
1834
            if (token.IsKind(SyntaxKind.CaseKeyword) &&
J
jasonmalinowski 已提交
1835
                token.Parent.IsKind(SyntaxKind.GotoCaseStatement))
P
Pilchie 已提交
1836 1837 1838 1839
            {
                return true;
            }

1840
            if (token.IsKind(SyntaxKind.EqualsToken) &&
J
jasonmalinowski 已提交
1841
                token.Parent.IsKind(SyntaxKind.EqualsValueClause))
P
Pilchie 已提交
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
            {
                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;
                }
            }

1876 1877
            // [Goo( |
            // [Goo(x, |
J
jasonmalinowski 已提交
1878
            if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList) &&
1879 1880
               (token.IsKind(SyntaxKind.CommaToken) ||
                token.IsKind(SyntaxKind.OpenParenToken)))
P
Pilchie 已提交
1881 1882 1883 1884
            {
                return true;
            }

1885
            // [Goo(x: |
1886
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
1887
                token.Parent.IsKind(SyntaxKind.NameColon) &&
P
Pilchie 已提交
1888 1889 1890 1891 1892
                token.Parent.IsParentKind(SyntaxKind.AttributeArgument))
            {
                return true;
            }

1893
            // [Goo(X = |
1894
            if (token.IsKind(SyntaxKind.EqualsToken) &&
J
jasonmalinowski 已提交
1895
                token.Parent.IsKind(SyntaxKind.NameEquals) &&
P
Pilchie 已提交
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
                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 .   ::   ->
1965 1966 1967
            if (token.IsKind(SyntaxKind.DotToken) ||
                token.IsKind(SyntaxKind.ColonColonToken) ||
                token.IsKind(SyntaxKind.MinusGreaterThanToken))
P
Pilchie 已提交
1968 1969 1970 1971 1972
            {
                return false;
            }

            // Normally you can have any sort of expression after an equals. However, this does not
1973
            // apply to a "using Goo = ..." situation.
1974
            if (token.IsKind(SyntaxKind.EqualsToken))
P
Pilchie 已提交
1975
            {
J
jasonmalinowski 已提交
1976
                if (token.Parent.IsKind(SyntaxKind.NameEquals) &&
P
Pilchie 已提交
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
                    token.Parent.IsParentKind(SyntaxKind.UsingDirective))
                {
                    return false;
                }
            }

            // q = |
            // q -= |
            // q *= |
            // q += |
            // q /= |
            // q ^= |
            // q %= |
            // q &= |
            // q |= |
            // q <<= |
            // q >>= |
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
            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 已提交
2006 2007 2008 2009 2010
            {
                return true;
            }

            // ( |
2011
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
2012
                token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
P
Pilchie 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
            {
                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
2034 2035 2036 2037 2038 2039 2040
            // await |
            if (token.Parent is AwaitExpressionSyntax)
            {
                var awaitExpression = token.Parent as AwaitExpressionSyntax;
                return awaitExpression.AwaitKeyword == token;
            }

P
Pilchie 已提交
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
            // 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,
2063 2064
                // 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 已提交
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
                // 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.
2077
                    if (token.IsKind(SyntaxKind.AsteriskToken) && semanticModelOpt != null)
P
Pilchie 已提交
2078
                    {
C
CyrusNajmabadi 已提交
2079
                        if (binary.Left is TypeSyntax type && type.IsPotentialTypeName(semanticModelOpt, cancellationToken))
P
Pilchie 已提交
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }

            // Special case:
2090 2091 2092
            //    Goo * bar
            //    Goo ? bar
            // This parses as a local decl called bar of type Goo* or Goo?
P
Pilchie 已提交
2093
            if (tokenOnLeftOfPosition.IntersectsWith(position) &&
2094
                tokenOnLeftOfPosition.IsKind(SyntaxKind.IdentifierToken))
P
Pilchie 已提交
2095 2096
            {
                var previousToken = tokenOnLeftOfPosition.GetPreviousToken(includeSkipped: true);
2097 2098
                if (previousToken.IsKind(SyntaxKind.AsteriskToken) ||
                    previousToken.IsKind(SyntaxKind.QuestionToken))
P
Pilchie 已提交
2099
                {
J
jasonmalinowski 已提交
2100 2101
                    if (previousToken.Parent.IsKind(SyntaxKind.PointerType) ||
                        previousToken.Parent.IsKind(SyntaxKind.NullableType))
P
Pilchie 已提交
2102 2103 2104 2105 2106 2107 2108 2109
                    {
                        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 已提交
2110
                            // absolutely is not multiplication or a conditional expression.
P
Pilchie 已提交
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
                            var underlyingType = type is PointerTypeSyntax
                                ? ((PointerTypeSyntax)type).ElementType
                                : ((NullableTypeSyntax)type).ElementType;

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

            // new int[|
            // new int[expr, |
2126 2127
            if (token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2128
            {
J
jasonmalinowski 已提交
2129
                if (token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier))
P
Pilchie 已提交
2130 2131 2132 2133 2134
                {
                    return true;
                }
            }

2135
            // goo ? |
2136
            if (token.IsKind(SyntaxKind.QuestionToken) &&
J
jasonmalinowski 已提交
2137
                token.Parent.IsKind(SyntaxKind.ConditionalExpression))
P
Pilchie 已提交
2138 2139 2140 2141 2142 2143 2144 2145 2146
            {
                // 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);
            }

2147
            // goo ? bar : |
2148
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2149
                token.Parent.IsKind(SyntaxKind.ConditionalExpression))
P
Pilchie 已提交
2150 2151 2152 2153 2154 2155 2156
            {
                return true;
            }

            // typeof(|
            // default(|
            // sizeof(|
2157
            if (token.IsKind(SyntaxKind.OpenParenToken))
P
Pilchie 已提交
2158
            {
J
jasonmalinowski 已提交
2159
                if (token.Parent.IsKind(SyntaxKind.TypeOfExpression, SyntaxKind.DefaultExpression, SyntaxKind.SizeOfExpression))
P
Pilchie 已提交
2160 2161 2162 2163 2164
                {
                    return false;
                }
            }

2165 2166 2167 2168 2169 2170 2171 2172 2173
            // 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;
            }

2174 2175
            // Goo(|
            // Goo(expr, |
P
Pilchie 已提交
2176
            // this[|
2177 2178
            // var t = (1, |
            // var t = (| , 2)
2179 2180 2181
            if (token.IsKind(SyntaxKind.OpenParenToken) ||
                token.IsKind(SyntaxKind.OpenBracketToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2182
            {
2183
                if (token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList, SyntaxKind.TupleExpression))
P
Pilchie 已提交
2184 2185 2186 2187 2188
                {
                    return true;
                }
            }

2189 2190
            // [Goo(|
            // [Goo(expr, |
P
Pilchie 已提交
2191 2192
            if (attributes)
            {
2193 2194
                if (token.IsKind(SyntaxKind.OpenParenToken) ||
                    token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2195
                {
J
jasonmalinowski 已提交
2196
                    if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList))
P
Pilchie 已提交
2197 2198 2199 2200 2201 2202
                    {
                        return true;
                    }
                }
            }

2203
            // Goo(ref |
2204 2205
            // Goo(in |
            // Goo(out |
2206
            // ref var x = ref |
2207
            if (token.IsKind(SyntaxKind.RefKeyword) ||
2208
                token.IsKind(SyntaxKind.InKeyword) ||
2209
                token.IsKind(SyntaxKind.OutKeyword))
P
Pilchie 已提交
2210
            {
2211
                if (token.Parent.IsKind(SyntaxKind.Argument, SyntaxKind.RefExpression))
P
Pilchie 已提交
2212 2213 2214 2215 2216
                {
                    return true;
                }
            }

2217
            // Goo(bar: |
2218
            if (token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2219
                token.Parent.IsKind(SyntaxKind.NameColon) &&
P
Pilchie 已提交
2220 2221 2222 2223 2224 2225
                token.Parent.IsParentKind(SyntaxKind.Argument))
            {
                return true;
            }

            // a => |
2226
            if (token.IsKind(SyntaxKind.EqualsGreaterThanToken))
P
Pilchie 已提交
2227 2228 2229 2230 2231 2232
            {
                return true;
            }

            // new List<int> { |
            // new List<int> { expr, |
2233 2234
            if (token.IsKind(SyntaxKind.OpenBraceToken) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2235 2236 2237 2238 2239
            {
                if (token.Parent is InitializerExpressionSyntax)
                {
                    // The compiler treats the ambiguous case as an object initializer, so we'll say
                    // expressions are legal here
2240
                    if (token.Parent.IsKind(SyntaxKind.ObjectInitializerExpression) && token.IsKind(SyntaxKind.OpenBraceToken))
P
Pilchie 已提交
2241 2242
                    {
                        // In this position { a$$ =, the user is trying to type an object initializer.
2243
                        if (!token.IntersectsWith(position) && token.GetNextToken().GetNextToken().IsKind(SyntaxKind.EqualsToken))
P
Pilchie 已提交
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
                        {
                            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;
2259 2260
                        var containingSymbol = semanticModelOpt.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
                        if (type != null && !type.CanSupportCollectionInitializer(containingSymbol))
P
Pilchie 已提交
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
                        {
                            return false;
                        }
                    }

                    return true;
                }
            }

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

            // for ( |
2284
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
J
jasonmalinowski 已提交
2285
                token.Parent.IsKind(SyntaxKind.ForStatement))
P
Pilchie 已提交
2286 2287 2288 2289 2290 2291 2292 2293
            {
                var forStatement = (ForStatementSyntax)token.Parent;
                if (token == forStatement.OpenParenToken)
                {
                    return true;
                }
            }

2294 2295
            // for (; ; Goo(), | 
            // for ( Goo(), |
2296
            if (token.IsKind(SyntaxKind.CommaToken) &&
J
jasonmalinowski 已提交
2297
                token.Parent.IsKind(SyntaxKind.ForStatement))
P
Pilchie 已提交
2298 2299 2300 2301 2302 2303 2304
            {
                return true;
            }

            // foreach (var v in |
            // from a in |
            // join b in |
2305
            if (token.IsKind(SyntaxKind.InKeyword))
P
Pilchie 已提交
2306
            {
2307
                if (token.Parent.IsKind(SyntaxKind.ForEachStatement,
2308
                                        SyntaxKind.ForEachVariableStatement,
2309 2310
                                        SyntaxKind.FromClause,
                                        SyntaxKind.JoinClause))
P
Pilchie 已提交
2311 2312 2313 2314 2315 2316 2317
                {
                    return true;
                }
            }

            // join x in y on |
            // join x in y on a equals |
2318 2319
            if (token.IsKind(SyntaxKind.OnKeyword) ||
                token.IsKind(SyntaxKind.EqualsKeyword))
P
Pilchie 已提交
2320
            {
J
jasonmalinowski 已提交
2321
                if (token.Parent.IsKind(SyntaxKind.JoinClause))
P
Pilchie 已提交
2322 2323 2324 2325 2326 2327
                {
                    return true;
                }
            }

            // where |
2328
            if (token.IsKind(SyntaxKind.WhereKeyword) &&
J
jasonmalinowski 已提交
2329
                token.Parent.IsKind(SyntaxKind.WhereClause))
P
Pilchie 已提交
2330 2331 2332 2333 2334 2335
            {
                return true;
            }

            // orderby |
            // orderby a, |
2336 2337
            if (token.IsKind(SyntaxKind.OrderByKeyword) ||
                token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2338
            {
J
jasonmalinowski 已提交
2339
                if (token.Parent.IsKind(SyntaxKind.OrderByClause))
P
Pilchie 已提交
2340 2341 2342 2343 2344 2345
                {
                    return true;
                }
            }

            // select |
2346
            if (token.IsKind(SyntaxKind.SelectKeyword) &&
J
jasonmalinowski 已提交
2347
                token.Parent.IsKind(SyntaxKind.SelectClause))
P
Pilchie 已提交
2348 2349 2350 2351 2352 2353
            {
                return true;
            }

            // group |
            // group expr by |
2354 2355
            if (token.IsKind(SyntaxKind.GroupKeyword) ||
                token.IsKind(SyntaxKind.ByKeyword))
P
Pilchie 已提交
2356
            {
J
jasonmalinowski 已提交
2357
                if (token.Parent.IsKind(SyntaxKind.GroupClause))
P
Pilchie 已提交
2358 2359 2360 2361 2362 2363 2364 2365
                {
                    return true;
                }
            }

            // return |
            // yield return |
            // but not: [return |
2366
            if (token.IsKind(SyntaxKind.ReturnKeyword))
P
Pilchie 已提交
2367
            {
2368
                if (token.GetPreviousToken(includeSkipped: true).Kind() != SyntaxKind.OpenBracketToken)
P
Pilchie 已提交
2369 2370 2371 2372 2373 2374
                {
                    return true;
                }
            }

            // throw |
2375
            if (token.IsKind(SyntaxKind.ThrowKeyword))
P
Pilchie 已提交
2376 2377 2378 2379 2380
            {
                return true;
            }

            // while ( |
2381 2382
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhileKeyword))
P
Pilchie 已提交
2383 2384 2385 2386 2387 2388 2389
            {
                return true;
            }

            // todo: handle 'for' cases.

            // using ( |
2390 2391
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UsingKeyword))
P
Pilchie 已提交
2392 2393 2394 2395 2396
            {
                return true;
            }

            // lock ( |
2397 2398
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.LockKeyword))
P
Pilchie 已提交
2399 2400 2401 2402 2403
            {
                return true;
            }

            // lock ( |
2404 2405
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IfKeyword))
P
Pilchie 已提交
2406 2407 2408 2409 2410
            {
                return true;
            }

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

            // checked ( |
2418 2419
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CheckedKeyword))
P
Pilchie 已提交
2420 2421 2422 2423 2424
            {
                return true;
            }

            // unchecked ( |
2425 2426
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UncheckedKeyword))
P
Pilchie 已提交
2427 2428 2429 2430
            {
                return true;
            }

2431
            // when ( |
2432 2433
            if (token.IsKind(SyntaxKind.OpenParenToken) &&
                token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhenKeyword))
2434 2435 2436
            {
                return true;
            }
2437 2438 2439 2440 2441 2442

            // case ... when |
            if (token.IsKind(SyntaxKind.WhenKeyword) && token.Parent.IsKind(SyntaxKind.WhenClause))
            {
                return true;
            }
2443 2444

            // (SomeType) |
P
Pilchie 已提交
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
            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:
            //
2455
            // var a = new { new C().Goo };
2456
            if (token.IsKind(SyntaxKind.OpenBraceToken) || token.IsKind(SyntaxKind.CommaToken))
P
Pilchie 已提交
2457
            {
J
jasonmalinowski 已提交
2458
                if (token.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression))
P
Pilchie 已提交
2459 2460 2461 2462 2463
                {
                    return true;
                }
            }

2464 2465 2466 2467
            // $"{ |
            // $@"{ |
            // $"{x} { |
            // $@"{x} { |
2468
            if (token.IsKind(SyntaxKind.OpenBraceToken))
2469
            {
2470 2471
                return token.Parent.IsKind(SyntaxKind.Interpolation)
                    && ((InterpolationSyntax)token.Parent).OpenBraceToken == token;
2472 2473
            }

P
Pilchie 已提交
2474 2475 2476
            return false;
        }

2477 2478 2479 2480 2481 2482
        public static bool IsInvocationOfVarExpression(this SyntaxToken token)
        {
            return token.Parent.Parent.IsKind(SyntaxKind.InvocationExpression) &&
                ((InvocationExpressionSyntax)token.Parent.Parent).Expression.ToString() == "var";
        }

C
CyrusNajmabadi 已提交
2483
        public static bool IsNameOfContext(this SyntaxTree syntaxTree, int position, SemanticModel semanticModelOpt = null, CancellationToken cancellationToken = default)
2484 2485 2486 2487
        {
            var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
            token = token.GetPreviousTokenIfTouchingWord(position);

2488 2489
            // nameof(Goo.|
            // nameof(Goo.Bar.|
2490
            // Locate the open paren.
2491
            if (token.IsKind(SyntaxKind.DotToken))
2492
            {
2493 2494
                // Could have been parsed as member access
                if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
2495
                {
2496 2497 2498 2499 2500
                    var parentMemberAccess = token.Parent;
                    while (parentMemberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))
                    {
                        parentMemberAccess = parentMemberAccess.Parent;
                    }
2501

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

2509 2510
                // Could have been parsed as a qualified name.
                if (token.Parent.IsKind(SyntaxKind.QualifiedName))
2511
                {
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
                    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;
                    }
2523 2524 2525
                }
            }

2526 2527
            ExpressionSyntax parentExpression = null;

2528
            // if the nameof expression has a missing close paren, it is parsed as an invocation expression.
2529
            if (token.Parent.IsKind(SyntaxKind.ArgumentList) &&
2530 2531
                token.Parent.Parent is InvocationExpressionSyntax invocationExpression &&
                invocationExpression.IsNameOfInvocation())
2532
            {
2533
                parentExpression = invocationExpression;
2534 2535 2536 2537 2538 2539 2540 2541 2542
            }

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

2543
                return semanticModelOpt.GetSymbolInfo(parentExpression, cancellationToken).Symbol == null;
2544 2545 2546 2547 2548
            }

            return false;
        }

P
Pilchie 已提交
2549 2550 2551 2552 2553 2554 2555 2556
        public static bool IsIsOrAsContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken)
        {
            // cases:
            //    expr |

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

2557 2558 2559 2560 2561 2562
            // Not if the position is *within* a numeric literal
            if (token.IsKind(SyntaxKind.NumericLiteralToken) && token.Span.Contains(position))
            {
                return false;
            }

P
Pilchie 已提交
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
            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 已提交
2602 2603
                if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) &&
                    token.Parent.IsKind(SyntaxKind.IdentifierName) &&
P
Pilchie 已提交
2604 2605 2606 2607 2608
                    (token.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression) || token.Parent.IsParentKind(SyntaxKind.CollectionInitializerExpression)))
                {
                    return false;
                }

2609
                // Not after an 'out' declaration expression. For example: M(out var |
J
jasonmalinowski 已提交
2610 2611
                if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) &&
                    token.Parent.IsKind(SyntaxKind.IdentifierName))
2612 2613
                {
                    if (token.Parent.IsParentKind(SyntaxKind.Argument) &&
J
jasonmalinowski 已提交
2614
                        CodeAnalysis.CSharpExtensions.IsKind(((ArgumentSyntax)token.Parent.Parent).RefOrOutKeyword, SyntaxKind.OutKeyword))
2615 2616 2617 2618 2619
                    {
                        return false;
                    }
                }

P
Pilchie 已提交
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
                // 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)
            {
2637
                switch (name.Parent.Kind())
P
Pilchie 已提交
2638 2639 2640 2641 2642 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 2670 2671
                {
                    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);

2672
            if (token.IsKind(SyntaxKind.CloseBraceToken))
P
Pilchie 已提交
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
            {
                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 已提交
2700
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CatchKeyword))
P
Pilchie 已提交
2701 2702 2703 2704
            {
                return true;
            }

J
jasonmalinowski 已提交
2705
            if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CloseParenToken) &&
P
Pilchie 已提交
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
                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
2724
                token.IsKind(SyntaxKind.ColonToken) &&
J
jasonmalinowski 已提交
2725
                token.Parent.IsKind(SyntaxKind.BaseList) &&
P
Pilchie 已提交
2726 2727 2728 2729 2730 2731 2732 2733 2734
                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 已提交
2735 2736
            if (!token.IsKind(SyntaxKind.DotToken) ||
                !token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression))
P
Pilchie 已提交
2737 2738 2739 2740 2741
            {
                return false;
            }

            var memberAccess = (MemberAccessExpressionSyntax)token.Parent;
2742
            var leftHandBinding = semanticModel.GetSymbolInfo(memberAccess.Expression, cancellationToken);
P
Pilchie 已提交
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
            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;
        }
    }
2762
}