SyntaxTokenExtensions.cs 21.9 KB
Newer Older
1
// Copyright (c) Microsoft Open Technologies, Inc.  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 4 5 6 7 8 9 10 11 12 13 14 15 16

using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
    internal static class SyntaxTokenExtensions
    {
        public static bool IsUsingOrExternKeyword(this SyntaxToken token)
        {
            return
17 18
                token.Kind() == SyntaxKind.UsingKeyword ||
                token.Kind() == SyntaxKind.ExternKeyword;
P
Pilchie 已提交
19 20
        }

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
        {
            if (token.IsKind(SyntaxKind.UsingKeyword))
            {
                var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
                if (usingDirective != null &&
                    usingDirective.UsingKeyword == token)
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
        {
            if (token.IsKind(SyntaxKind.StaticKeyword))
            {
                var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
                if (usingDirective != null &&
                    usingDirective.StaticKeyword == token)
                {
                    return true;
                }
            }

            return false;
        }

P
Pilchie 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
        public static bool IsBeginningOfStatementContext(this SyntaxToken token)
        {
            // cases:
            //    {
            //      |

            // }
            // |

            // Note, the following is *not* a legal statement context: 
            //    do { } |

            // ...;
            // |

            // case 0:
            //   |

            // default:
            //   |

            // label:
            //   |

            // if (foo)
            //   |

            // while (true)
            //   |

            // do
            //   |

            // for (;;)
            //   |

            // foreach (var v in c)
            //   |

            // else
            //   |

            // using (expr)
            //   |

            // lock (expr)
            //   |

            // for ( ; ; Foo(), |

101
            if (token.Kind() == SyntaxKind.OpenBraceToken &&
J
jasonmalinowski 已提交
102
                token.Parent.IsKind(SyntaxKind.Block))
P
Pilchie 已提交
103 104 105 106
            {
                return true;
            }

107
            if (token.Kind() == SyntaxKind.SemicolonToken)
P
Pilchie 已提交
108 109 110 111 112 113 114 115 116
            {
                var statement = token.GetAncestor<StatementSyntax>();
                if (statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
                    statement.GetLastToken(includeZeroWidth: true) == token)
                {
                    return true;
                }
            }

117
            if (token.Kind() == SyntaxKind.CloseBraceToken &&
J
jasonmalinowski 已提交
118
                token.Parent.IsKind(SyntaxKind.Block))
P
Pilchie 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
            {
                if (token.Parent.Parent is StatementSyntax)
                {
                    // Most blocks that are the child of statement are places
                    // that we can follow with another statement.  i.e.:
                    // if { }
                    // while () { }
                    // There are two exceptions.
                    // try {}
                    // do {}
                    if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
                        !token.Parent.IsParentKind(SyntaxKind.DoStatement))
                    {
                        return true;
                    }
                }
                else if (
                    token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
                    token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
                    token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
                    token.Parent.IsParentKind(SyntaxKind.SwitchSection))
                {
                    return true;
                }
            }

145
            if (token.Kind() == SyntaxKind.CloseBraceToken &&
J
jasonmalinowski 已提交
146
                token.Parent.IsKind(SyntaxKind.SwitchStatement))
P
Pilchie 已提交
147 148 149 150
            {
                return true;
            }

151
            if (token.Kind() == SyntaxKind.ColonToken)
P
Pilchie 已提交
152
            {
J
jasonmalinowski 已提交
153
                if (token.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.LabeledStatement))
P
Pilchie 已提交
154 155 156 157 158
                {
                    return true;
                }
            }

159
            if (token.Kind() == SyntaxKind.DoKeyword &&
J
jasonmalinowski 已提交
160
                token.Parent.IsKind(SyntaxKind.DoStatement))
P
Pilchie 已提交
161 162 163 164
            {
                return true;
            }

165
            if (token.Kind() == SyntaxKind.CloseParenToken)
P
Pilchie 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178
            {
                var parent = token.Parent;
                if (parent.IsKind(SyntaxKind.ForStatement) ||
                    parent.IsKind(SyntaxKind.ForEachStatement) ||
                    parent.IsKind(SyntaxKind.WhileStatement) ||
                    parent.IsKind(SyntaxKind.IfStatement) ||
                    parent.IsKind(SyntaxKind.LockStatement) ||
                    parent.IsKind(SyntaxKind.UsingStatement))
                {
                    return true;
                }
            }

179
            if (token.Kind() == SyntaxKind.ElseKeyword)
P
Pilchie 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
            {
                return true;
            }

            return false;
        }

        public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
        {
            // cases:
            // }
            // |

            // ...;
            // |

            // extern alias Foo;
            // using System;
            // |

200
            // [assembly: Foo]
P
Pilchie 已提交
201 202
            // |

203
            if (token.Kind() == SyntaxKind.CloseBraceToken)
P
Pilchie 已提交
204 205 206 207 208 209 210 211 212
            {
                var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
                if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
                    memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
                {
                    return true;
                }
            }

213
            if (token.Kind() == SyntaxKind.SemicolonToken)
P
Pilchie 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
            {
                var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
                if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
                {
                    return true;
                }

                var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
                if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
                    memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
                {
                    return true;
                }

                var compUnit = token.GetAncestor<CompilationUnitSyntax>();
                if (compUnit != null)
                {
                    if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
                    {
                        return true;
                    }

                    if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
                    {
                        return true;
                    }
                }
            }

243
            if (token.Kind() == SyntaxKind.CloseBracketToken)
P
Pilchie 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
            {
                var compUnit = token.GetAncestor<CompilationUnitSyntax>();
                if (compUnit != null)
                {
                    if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public static bool IsAfterPossibleCast(this SyntaxToken token)
        {
260
            if (token.Kind() == SyntaxKind.CloseParenToken)
P
Pilchie 已提交
261
            {
J
jasonmalinowski 已提交
262
                if (token.Parent.IsKind(SyntaxKind.CastExpression))
P
Pilchie 已提交
263 264 265 266
                {
                    return true;
                }

J
jasonmalinowski 已提交
267
                if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
P
Pilchie 已提交
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
                {
                    var parenExpr = token.Parent as ParenthesizedExpressionSyntax;
                    var expr = parenExpr.Expression;

                    if (expr is TypeSyntax)
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public static bool IsLastTokenOfNode<T>(this SyntaxToken token)
            where T : SyntaxNode
        {
            var node = token.GetAncestor<T>();
            return node != null && token == node.GetLastToken(includeZeroWidth: true);
        }

        public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
        {
            if (token.IsLastTokenOfNode<QueryClauseSyntax>())
            {
                return true;
            }

296 297
            if (token.Kind() == SyntaxKind.IdentifierToken &&
                token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
P
Pilchie 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
            {
                return true;
            }

            return false;
        }

        public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
        {
            // cases:
            //   #if |
            //   #if foo || |
            //   #if foo && |
            //   #if ( |
            //   #if ! |
            // Same for elif

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

            // #if
            // #elif
322 323
            if (targetToken.Kind() == SyntaxKind.IfKeyword ||
                targetToken.Kind() == SyntaxKind.ElifKeyword)
P
Pilchie 已提交
324 325 326 327 328
            {
                return true;
            }

            // ( |
329
            if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
J
jasonmalinowski 已提交
330
                targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
P
Pilchie 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
            {
                return true;
            }

            // ! |
            if (targetToken.Parent is PrefixUnaryExpressionSyntax)
            {
                var prefix = targetToken.Parent as PrefixUnaryExpressionSyntax;
                return prefix.OperatorToken == targetToken;
            }

            // a &&
            // a ||
            if (targetToken.Parent is BinaryExpressionSyntax)
            {
                var binary = targetToken.Parent as BinaryExpressionSyntax;
                return binary.OperatorToken == targetToken;
            }

            return false;
        }

        public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
        {
            // cases:
            //   orderby a |
            //   orderby a a|
            //   orderby a, b |
            //   orderby a, b a|

J
jasonmalinowski 已提交
361
            if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
P
Pilchie 已提交
362 363 364 365 366 367 368 369 370 371 372 373
            {
                return false;
            }

            var ordering = targetToken.GetAncestor<OrderingSyntax>();
            if (ordering == null)
            {
                return false;
            }

            // orderby a |
            // orderby a, b |
374 375 376
            var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);

            if (targetToken == lastToken)
P
Pilchie 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
            {
                return true;
            }

            return false;
        }

        public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
        {
            // cases:
            //   case X: |
            //   default: |
            //   switch (e) { |
            //
            //   case X: Statement(); |

393
            if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
J
jasonmalinowski 已提交
394
                targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
P
Pilchie 已提交
395 396 397 398
            {
                return true;
            }

399
            if (targetToken.Kind() == SyntaxKind.ColonToken)
P
Pilchie 已提交
400
            {
J
jasonmalinowski 已提交
401
                if (targetToken.Parent.IsKind(SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel))
P
Pilchie 已提交
402 403 404 405 406
                {
                    return true;
                }
            }

407 408
            if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
                targetToken.Kind() == SyntaxKind.CloseBraceToken)
P
Pilchie 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
            {
                var section = targetToken.GetAncestor<SwitchSectionSyntax>();
                if (section != null)
                {
                    foreach (var statement in section.Statements)
                    {
                        if (targetToken == statement.GetLastToken(includeSkipped: true))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
        {
J
jasonmalinowski 已提交
428 429
            return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
                && targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
P
Pilchie 已提交
430 431 432 433 434 435 436 437 438 439 440
        }

        public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
        {
            // cases:
            //   Foo( |
            //   Foo(expr, |
            //   Foo(bar: |
            //   new Foo( |
            //   new Foo(expr, |
            //   new Foo(bar: |
441 442 443 444
            //   Foo : base( |
            //   Foo : base(bar: |
            //   Foo : this( |
            //   Foo : ths(bar: |
P
Pilchie 已提交
445 446

            // Foo(bar: |
447
            if (targetToken.Kind() == SyntaxKind.ColonToken &&
J
jasonmalinowski 已提交
448
                targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
P
Pilchie 已提交
449 450 451 452 453
                targetToken.Parent.IsParentKind(SyntaxKind.Argument) &&
                targetToken.Parent.GetParent().IsParentKind(SyntaxKind.ArgumentList))
            {
                var owner = targetToken.Parent.GetParent().GetParent().GetParent();
                if (owner.IsKind(SyntaxKind.InvocationExpression) ||
454 455 456
                    owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
                    owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
                    owner.IsKind(SyntaxKind.ThisConstructorInitializer))
P
Pilchie 已提交
457 458 459 460 461
                {
                    return true;
                }
            }

462 463
            if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
                targetToken.Kind() == SyntaxKind.CommaToken)
P
Pilchie 已提交
464
            {
J
jasonmalinowski 已提交
465
                if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
P
Pilchie 已提交
466 467
                {
                    if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) ||
468 469 470
                        targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
                        targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
                        targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
P
Pilchie 已提交
471 472 473 474 475 476 477 478 479 480 481
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
        {
482
            if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
P
Pilchie 已提交
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 524 525 526 527 528 529 530
                targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
            {
                return true;
            }

            return false;
        }

        public static bool IsUnsafeContext(this SyntaxToken targetToken)
        {
            return
                targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
                targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
        }

        public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
        {
            // yield |
            // yield r|

            if (targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword))
            {
                return true;
            }

            return false;
        }

        public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
            where TMemberNode : SyntaxNode
        {
            if (!IsAccessorDeclarationContextWorker(targetToken))
            {
                return false;
            }

            var list = targetToken.GetAncestor<AccessorListSyntax>();
            if (list == null)
            {
                return false;
            }

            // Check if we already have this accessor.  (however, don't count it
            // if the user is *on* that accessor.
            var existingAccessor = list.Accessors
                .Select(a => a.Keyword)
                .FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));

531
            if (existingAccessor.Kind() != SyntaxKind.None)
P
Pilchie 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
            {
                var existingAccessorSpan = existingAccessor.Span;
                if (!existingAccessorSpan.IntersectsWith(position))
                {
                    return false;
                }
            }

            var decl = targetToken.GetAncestor<TMemberNode>();
            return decl != null;
        }

        private static bool IsAccessorDeclarationContextWorker(SyntaxToken targetToken)
        {
            // cases:
            //   int Foo { |
            //   int Foo { private |
            //   int Foo { set { } |
            //   int Foo { set; |
            //   int Foo { [Bar]|

            // Consume all preceding access modifiers
554 555 556 557
            while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
                targetToken.Kind() == SyntaxKind.PublicKeyword ||
                targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
                targetToken.Kind() == SyntaxKind.PrivateKeyword)
P
Pilchie 已提交
558 559 560 561 562 563
            {
                targetToken = targetToken.GetPreviousToken(includeSkipped: true);
            }

            // int Foo { |
            // int Foo { private |
564
            if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
J
jasonmalinowski 已提交
565
                targetToken.Parent.IsKind(SyntaxKind.AccessorList))
P
Pilchie 已提交
566 567 568 569 570 571
            {
                return true;
            }

            // int Foo { set { } |
            // int Foo { set { } private |
572
            if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
J
jasonmalinowski 已提交
573
                targetToken.Parent.IsKind(SyntaxKind.Block) &&
P
Pilchie 已提交
574 575 576 577 578 579
                targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
            {
                return true;
            }

            // int Foo { set; |
580
            if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
P
Pilchie 已提交
581 582 583 584 585 586
                targetToken.Parent is AccessorDeclarationSyntax)
            {
                return true;
            }

            // int Foo { [Bar]|
587
            if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
J
jasonmalinowski 已提交
588
                targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
P
Pilchie 已提交
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 617 618 619 620 621 622 623 624 625
                targetToken.Parent.GetParent() is AccessorDeclarationSyntax)
            {
                return true;
            }

            return false;
        }

        private static bool IsGenericInterfaceOrDelegateTypeParameterList(SyntaxNode node)
        {
            if (node.IsKind(SyntaxKind.TypeParameterList))
            {
                if (node.IsParentKind(SyntaxKind.InterfaceDeclaration))
                {
                    var decl = node.Parent as TypeDeclarationSyntax;
                    return decl.TypeParameterList == node;
                }
                else if (node.IsParentKind(SyntaxKind.DelegateDeclaration))
                {
                    var decl = node.Parent as DelegateDeclarationSyntax;
                    return decl.TypeParameterList == node;
                }
            }

            return false;
        }

        public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
        {
            // cases:
            // interface IFoo<|
            // interface IFoo<A,|
            // interface IFoo<[Bar]|

            // deletate X D<|
            // deletate X D<A,|
            // deletate X D<[Bar]|
626
            if (targetToken.Kind() == SyntaxKind.LessThanToken &&
P
Pilchie 已提交
627 628 629 630 631
                IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
            {
                return true;
            }

632
            if (targetToken.Kind() == SyntaxKind.CommaToken &&
P
Pilchie 已提交
633 634 635 636 637
                IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent))
            {
                return true;
            }

638
            if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
J
jasonmalinowski 已提交
639
                targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
P
Pilchie 已提交
640 641 642 643 644 645 646 647
                targetToken.Parent.IsParentKind(SyntaxKind.TypeParameter) &&
                IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.GetParent().GetParent()))
            {
                return true;
            }

            return false;
        }
648 649 650

        public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
        {
651
            if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
            {
                var argumentList = (BaseArgumentListSyntax)token.Parent;

                foreach (var item in argumentList.Arguments.GetWithSeparators())
                {
                    if (item.IsToken && item.AsToken() == token)
                    {
                        return false;
                    }

                    if (item.IsNode)
                    {
                        var node = item.AsNode() as ArgumentSyntax;
                        if (node != null && node.NameColon != null)
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
P
Pilchie 已提交
675 676
    }
}