1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 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 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 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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 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 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
|
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
public delegate void FoundReferenceCallback(AstNode astNode, ResolveResult result);
/// <summary>
/// 'Find references' implementation.
/// </summary>
/// <remarks>
/// This class is thread-safe.
/// The intended multi-threaded usage is to call GetSearchScopes() once, and then
/// call FindReferencesInFile() concurrently on multiple threads (parallel foreach over all interesting files).
/// </remarks>
public sealed class FindReferences
{
#region Properties
/// <summary>
/// Specifies whether to find type references even if an alias is being used.
/// Aliases may be <c>var</c> or <c>using Alias = ...;</c>.
/// </summary>
public bool FindTypeReferencesEvenIfAliased { get; set; }
/// <summary>
/// Specifies whether find references should only look for specialized matches
/// with equal type parameter substitution to the member we are searching for.
/// </summary>
public bool FindOnlySpecializedReferences { get; set; }
/// <summary>
/// If this option is enabled, find references on a overridden member
/// will find calls to the base member.
/// </summary>
public bool FindCallsThroughVirtualBaseMethod { get; set; }
/// <summary>
/// If this option is enabled, find references on a member implementing
/// an interface will also find calls to the interface.
/// </summary>
public bool FindCallsThroughInterface { get; set; }
/// <summary>
/// If this option is enabled, find references will look for all references
/// to the virtual method slot.
/// </summary>
public bool WholeVirtualSlot { get; set; }
//public bool FindAllOverloads { get; set; }
/// <summary>
/// Specifies whether to look for references in documentation comments.
/// This will find entity references in <c>cref</c> attributes and
/// parameter references in <c><param></c> and <c><paramref></c> tags.
/// TODO: implement this feature.
/// </summary>
public bool SearchInDocumentationComments { get; set; }
#endregion
#region GetEffectiveAccessibility
/// <summary>
/// Gets the effective accessibility of the specified entity -
/// that is, the accessibility viewed from the top level.
/// </summary>
/// <remarks>
/// internal member in public class -> internal
/// public member in internal class -> internal
/// protected member in public class -> protected
/// protected member in internal class -> protected and internal
/// </remarks>
public static Accessibility GetEffectiveAccessibility(IEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
Accessibility a = entity.Accessibility;
for (ITypeDefinition declType = entity.DeclaringTypeDefinition; declType != null; declType = declType.DeclaringTypeDefinition) {
a = MergeAccessibility(declType.Accessibility, a);
}
return a;
}
static Accessibility MergeAccessibility(Accessibility outer, Accessibility inner)
{
if (outer == inner)
return inner;
if (outer == Accessibility.None || inner == Accessibility.None)
return Accessibility.None;
if (outer == Accessibility.Private || inner == Accessibility.Private)
return Accessibility.Private;
if (outer == Accessibility.Public)
return inner;
if (inner == Accessibility.Public)
return outer;
// Inner and outer are both in { protected, internal, protected and internal, protected or internal }
// (but they aren't both the same)
if (outer == Accessibility.ProtectedOrInternal)
return inner;
if (inner == Accessibility.ProtectedOrInternal)
return outer;
// Inner and outer are both in { protected, internal, protected and internal },
// but aren't both the same, so the result is protected and internal.
return Accessibility.ProtectedAndInternal;
}
#endregion
#region class SearchScope
sealed class SearchScope : IFindReferenceSearchScope
{
readonly Func<ICompilation, FindReferenceNavigator> factory;
public SearchScope(Func<ICompilation, FindReferenceNavigator> factory)
{
this.factory = factory;
}
public SearchScope(string searchTerm, Func<ICompilation, FindReferenceNavigator> factory)
{
this.searchTerm = searchTerm;
this.factory = factory;
}
internal string searchTerm;
internal FindReferences findReferences;
internal ICompilation declarationCompilation;
internal Accessibility accessibility;
internal ITypeDefinition topLevelTypeDefinition;
IResolveVisitorNavigator IFindReferenceSearchScope.GetNavigator(ICompilation compilation, FoundReferenceCallback callback)
{
FindReferenceNavigator n = factory(compilation);
if (n != null) {
n.callback = callback;
n.findReferences = findReferences;
return n;
} else {
return new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Skip, null);
}
}
ICompilation IFindReferenceSearchScope.Compilation {
get { return declarationCompilation; }
}
string IFindReferenceSearchScope.SearchTerm {
get { return searchTerm; }
}
Accessibility IFindReferenceSearchScope.Accessibility {
get { return accessibility; }
}
ITypeDefinition IFindReferenceSearchScope.TopLevelTypeDefinition {
get { return topLevelTypeDefinition; }
}
}
abstract class FindReferenceNavigator : IResolveVisitorNavigator
{
internal FoundReferenceCallback callback;
internal FindReferences findReferences;
internal abstract bool CanMatch(AstNode node);
internal abstract bool IsMatch(ResolveResult rr);
ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node)
{
if (CanMatch(node))
return ResolveVisitorNavigationMode.Resolve;
else
return ResolveVisitorNavigationMode.Scan;
}
void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
{
if (CanMatch(node) && IsMatch(result)) {
ReportMatch(node, result);
}
}
public virtual void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
{
}
protected void ReportMatch(AstNode node, ResolveResult result)
{
if (callback != null)
callback(node, result);
}
internal virtual void NavigatorDone(CSharpAstResolver resolver, CancellationToken cancellationToken)
{
}
}
#endregion
#region GetSearchScopes
public IList<IFindReferenceSearchScope> GetSearchScopes(ISymbol symbol)
{
if (symbol == null)
throw new ArgumentNullException("symbol");
switch (symbol.SymbolKind) {
case SymbolKind.Namespace:
return new[] { GetSearchScopeForNamespace((INamespace)symbol) };
case SymbolKind.TypeParameter:
return new[] { GetSearchScopeForTypeParameter((ITypeParameter)symbol) };
}
IEntity entity = symbol as IEntity;
if (entity == null)
throw new NotSupportedException("Unsupported symbol type");
if (entity is IMember)
entity = NormalizeMember((IMember)entity);
Accessibility effectiveAccessibility = GetEffectiveAccessibility(entity);
var topLevelTypeDefinition = GetTopLevelTypeDefinition(entity);
SearchScope scope;
SearchScope additionalScope = null;
switch (entity.SymbolKind) {
case SymbolKind.TypeDefinition:
scope = FindTypeDefinitionReferences((ITypeDefinition)entity, this.FindTypeReferencesEvenIfAliased, out additionalScope);
break;
case SymbolKind.Field:
if (entity.DeclaringTypeDefinition != null && entity.DeclaringTypeDefinition.Kind == TypeKind.Enum)
scope = FindMemberReferences(entity, m => new FindEnumMemberReferences((IField)m));
else
scope = FindMemberReferences(entity, m => new FindFieldReferences((IField)m));
break;
case SymbolKind.Property:
scope = FindMemberReferences(entity, m => new FindPropertyReferences((IProperty)m));
if (entity.Name == "Current")
additionalScope = FindEnumeratorCurrentReferences((IProperty)entity);
else if (entity.Name == "IsCompleted")
additionalScope = FindAwaiterIsCompletedReferences((IProperty)entity);
break;
case SymbolKind.Event:
scope = FindMemberReferences(entity, m => new FindEventReferences((IEvent)m));
break;
case SymbolKind.Method:
scope = GetSearchScopeForMethod((IMethod)entity);
break;
case SymbolKind.Indexer:
scope = FindIndexerReferences((IProperty)entity);
break;
case SymbolKind.Operator:
scope = GetSearchScopeForOperator((IMethod)entity);
break;
case SymbolKind.Constructor:
IMethod ctor = (IMethod)entity;
scope = FindObjectCreateReferences(ctor);
additionalScope = FindChainedConstructorReferences(ctor);
break;
case SymbolKind.Destructor:
scope = GetSearchScopeForDestructor((IMethod)entity);
break;
default:
throw new ArgumentException("Unknown entity type " + entity.SymbolKind);
}
if (scope.accessibility == Accessibility.None)
scope.accessibility = effectiveAccessibility;
scope.declarationCompilation = entity.Compilation;
scope.topLevelTypeDefinition = topLevelTypeDefinition;
scope.findReferences = this;
if (additionalScope != null) {
if (additionalScope.accessibility == Accessibility.None)
additionalScope.accessibility = effectiveAccessibility;
additionalScope.declarationCompilation = entity.Compilation;
additionalScope.topLevelTypeDefinition = topLevelTypeDefinition;
additionalScope.findReferences = this;
return new[] { scope, additionalScope };
} else {
return new[] { scope };
}
}
public IList<IFindReferenceSearchScope> GetSearchScopes(IEnumerable<ISymbol> symbols)
{
if (symbols == null)
throw new ArgumentNullException("symbols");
return symbols.SelectMany(GetSearchScopes).ToList();
}
static ITypeDefinition GetTopLevelTypeDefinition(IEntity entity)
{
if (entity == null)
return null;
ITypeDefinition topLevelTypeDefinition = entity.DeclaringTypeDefinition;
while (topLevelTypeDefinition != null && topLevelTypeDefinition.DeclaringTypeDefinition != null)
topLevelTypeDefinition = topLevelTypeDefinition.DeclaringTypeDefinition;
return topLevelTypeDefinition;
}
#endregion
#region GetInterestingFileNames
/// <summary>
/// Gets the file names that possibly contain references to the element being searched for.
/// </summary>
public IEnumerable<CSharpUnresolvedFile> GetInterestingFiles(IFindReferenceSearchScope searchScope, ICompilation compilation)
{
if (searchScope == null)
throw new ArgumentNullException("searchScope");
if (compilation == null)
throw new ArgumentNullException("compilation");
var pc = compilation.MainAssembly.UnresolvedAssembly as IProjectContent;
if (pc == null)
throw new ArgumentException("Main assembly is not a project content");
if (searchScope.TopLevelTypeDefinition != null) {
ITypeDefinition topLevelTypeDef = compilation.Import(searchScope.TopLevelTypeDefinition);
if (topLevelTypeDef == null) {
// This compilation cannot have references to the target entity.
return EmptyList<CSharpUnresolvedFile>.Instance;
}
switch (searchScope.Accessibility) {
case Accessibility.None:
case Accessibility.Private:
if (topLevelTypeDef.ParentAssembly == compilation.MainAssembly)
return topLevelTypeDef.Parts.Select(p => p.UnresolvedFile).OfType<CSharpUnresolvedFile>().Distinct();
else
return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.Protected:
return GetInterestingFilesProtected(topLevelTypeDef);
case Accessibility.Internal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return pc.Files.OfType<CSharpUnresolvedFile>();
else
return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.ProtectedAndInternal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return GetInterestingFilesProtected(topLevelTypeDef);
else
return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.ProtectedOrInternal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return pc.Files.OfType<CSharpUnresolvedFile>();
else
return GetInterestingFilesProtected(topLevelTypeDef);
default:
return pc.Files.OfType<CSharpUnresolvedFile>();
}
} else {
return pc.Files.OfType<CSharpUnresolvedFile>();
}
}
IEnumerable<CSharpUnresolvedFile> GetInterestingFilesProtected(ITypeDefinition referencedTypeDefinition)
{
return (from typeDef in referencedTypeDefinition.Compilation.MainAssembly.GetAllTypeDefinitions()
where typeDef.IsDerivedFrom(referencedTypeDefinition)
from part in typeDef.Parts
select part.UnresolvedFile
).OfType<CSharpUnresolvedFile>().Distinct();
}
#endregion
#region FindReferencesInFile
/// <summary>
/// Finds all references in the given file.
/// </summary>
/// <param name="searchScope">The search scope for which to look.</param>
/// <param name="resolver">AST resolver for the file to search in.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpAstResolver resolver,
FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (resolver == null)
throw new ArgumentNullException("resolver");
FindReferencesInFile(searchScope, resolver.UnresolvedFile, (SyntaxTree)resolver.RootNode, resolver.Compilation, callback, cancellationToken);
}
/// <summary>
/// Finds all references in the given file.
/// </summary>
/// <param name="searchScopes">The search scopes for which to look.</param>
/// <param name="resolver">AST resolver for the file to search in.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpAstResolver resolver,
FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (resolver == null)
throw new ArgumentNullException("resolver");
FindReferencesInFile(searchScopes, resolver.UnresolvedFile, (SyntaxTree)resolver.RootNode, resolver.Compilation, callback, cancellationToken);
}
/// <summary>
/// Finds all references in the given file.
/// </summary>
/// <param name="searchScope">The search scope for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation for the project that contains the file.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (searchScope == null)
throw new ArgumentNullException("searchScope");
FindReferencesInFile(new[] { searchScope }, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
}
/// <summary>
/// Finds all references in the given file.
/// </summary>
/// <param name="searchScopes">The search scopes for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation for the project that contains the file.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (searchScopes == null)
throw new ArgumentNullException("searchScopes");
if (syntaxTree == null)
throw new ArgumentNullException("syntaxTree");
if (compilation == null)
throw new ArgumentNullException("compilation");
if (callback == null)
throw new ArgumentNullException("callback");
if (searchScopes.Count == 0)
return;
var navigators = new IResolveVisitorNavigator[searchScopes.Count];
for (int i = 0; i < navigators.Length; i++) {
navigators[i] = searchScopes[i].GetNavigator(compilation, callback);
}
IResolveVisitorNavigator combinedNavigator;
if (searchScopes.Count == 1) {
combinedNavigator = navigators[0];
} else {
combinedNavigator = new CompositeResolveVisitorNavigator(navigators);
}
cancellationToken.ThrowIfCancellationRequested();
combinedNavigator = new DetectSkippableNodesNavigator(combinedNavigator, syntaxTree);
cancellationToken.ThrowIfCancellationRequested();
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
resolver.ApplyNavigator(combinedNavigator, cancellationToken);
foreach (var n in navigators) {
var frn = n as FindReferenceNavigator;
if (frn != null)
frn.NavigatorDone(resolver, cancellationToken);
}
}
#endregion
#region RenameReferencesInFile
AstNode GetNodeToReplace(AstNode node)
{
if (node is ConstructorInitializer)
return null;
if (node is ObjectCreateExpression)
node = ((ObjectCreateExpression)node).Type;
if (node is InvocationExpression)
node = ((InvocationExpression)node).Target;
if (node is MemberReferenceExpression)
node = ((MemberReferenceExpression)node).MemberNameToken;
if (node is SimpleType)
node = ((SimpleType)node).IdentifierToken;
if (node is MemberType)
node = ((MemberType)node).MemberNameToken;
if (node is NamespaceDeclaration) {
// var nsd = ((NamespaceDeclaration)node);
// node = nsd.Identifiers.LastOrDefault (n => n.Name == memberName) ?? nsd.Identifiers.FirstOrDefault ();
// if (node == null)
return null;
}
if (node is TypeDeclaration)
node = ((TypeDeclaration)node).NameToken;
if (node is DelegateDeclaration)
node = ((DelegateDeclaration)node).NameToken;
if (node is EntityDeclaration)
node = ((EntityDeclaration)node).NameToken;
if (node is ParameterDeclaration)
node = ((ParameterDeclaration)node).NameToken;
if (node is ConstructorDeclaration)
node = ((ConstructorDeclaration)node).NameToken;
if (node is DestructorDeclaration)
node = ((DestructorDeclaration)node).NameToken;
if (node is NamedArgumentExpression)
node = ((NamedArgumentExpression)node).NameToken;
if (node is NamedExpression)
node = ((NamedExpression)node).NameToken;
if (node is VariableInitializer)
node = ((VariableInitializer)node).NameToken;
if (node is IdentifierExpression) {
node = ((IdentifierExpression)node).IdentifierToken;
}
return node;
}
public void RenameReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, string newName, CSharpAstResolver resolver,
Action<RenameCallbackArguments> callback, Action<Error> errorCallback, CancellationToken cancellationToken = default (CancellationToken))
{
FindReferencesInFile(
searchScopes,
resolver,
delegate(AstNode astNode, ResolveResult result) {
var nodeToReplace = GetNodeToReplace(astNode);
if (nodeToReplace == null) {
errorCallback (new Error (ErrorType.Error, "no node to replace found."));
return;
}
callback (new RenameCallbackArguments(nodeToReplace, Identifier.Create(newName)));
},
cancellationToken);
}
#endregion
#region Find TypeDefinition References
SearchScope FindTypeDefinitionReferences(ITypeDefinition typeDefinition, bool findTypeReferencesEvenIfAliased, out SearchScope additionalScope)
{
string searchTerm = null;
additionalScope = null;
if (!findTypeReferencesEvenIfAliased && KnownTypeReference.GetCSharpNameByTypeCode(typeDefinition.KnownTypeCode) == null) {
// We can optimize the search by looking only for the type references with the right identifier,
// but only if it's not a primitive type and we're not looking for indirect references (through an alias)
searchTerm = typeDefinition.Name;
if (searchTerm.Length > 9 && searchTerm.EndsWith("Attribute", StringComparison.Ordinal)) {
// The type might be an attribute, so we also need to look for the short form:
string shortForm = searchTerm.Substring(0, searchTerm.Length - 9);
additionalScope = FindTypeDefinitionReferences(typeDefinition, shortForm);
}
}
return FindTypeDefinitionReferences(typeDefinition, searchTerm);
}
SearchScope FindTypeDefinitionReferences(ITypeDefinition typeDefinition, string searchTerm)
{
return new SearchScope(
searchTerm,
delegate (ICompilation compilation) {
ITypeDefinition imported = compilation.Import(typeDefinition);
if (imported != null)
return new FindTypeDefinitionReferencesNavigator(imported, searchTerm);
else
return null;
});
}
sealed class FindTypeDefinitionReferencesNavigator : FindReferenceNavigator
{
readonly ITypeDefinition typeDefinition;
readonly string searchTerm;
public FindTypeDefinitionReferencesNavigator(ITypeDefinition typeDefinition, string searchTerm)
{
this.typeDefinition = typeDefinition;
this.searchTerm = searchTerm;
}
internal override bool CanMatch(AstNode node)
{
IdentifierExpression ident = node as IdentifierExpression;
if (ident != null)
return searchTerm == null || ident.Identifier == searchTerm;
MemberReferenceExpression mre = node as MemberReferenceExpression;
if (mre != null)
return searchTerm == null || mre.MemberName == searchTerm;
SimpleType st = node as SimpleType;
if (st != null)
return searchTerm == null || st.Identifier == searchTerm;
MemberType mt = node as MemberType;
if (mt != null)
return searchTerm == null || mt.MemberName == searchTerm;
if (searchTerm == null && node is PrimitiveType)
return true;
TypeDeclaration typeDecl = node as TypeDeclaration;
if (typeDecl != null)
return searchTerm == null || typeDecl.Name == searchTerm;
DelegateDeclaration delegateDecl = node as DelegateDeclaration;
if (delegateDecl != null)
return searchTerm == null || delegateDecl.Name == searchTerm;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
TypeResolveResult trr = rr as TypeResolveResult;
return trr != null && typeDefinition.Equals(trr.Type.GetDefinition());
}
}
#endregion
#region Find Member References
SearchScope FindMemberReferences(IEntity member, Func<IMember, FindMemberReferencesNavigator> factory)
{
string searchTerm = member.Name;
return new SearchScope(
searchTerm,
delegate(ICompilation compilation) {
IMember imported = compilation.Import((IMember)member);
return imported != null ? factory(imported) : null;
});
}
class FindMemberReferencesNavigator : FindReferenceNavigator
{
readonly IMember member;
readonly string searchTerm;
public FindMemberReferencesNavigator(IMember member)
{
this.member = member;
this.searchTerm = member.Name;
}
internal override bool CanMatch(AstNode node)
{
IdentifierExpression ident = node as IdentifierExpression;
if (ident != null)
return ident.Identifier == searchTerm;
MemberReferenceExpression mre = node as MemberReferenceExpression;
if (mre != null)
return mre.MemberName == searchTerm;
PointerReferenceExpression pre = node as PointerReferenceExpression;
if (pre != null)
return pre.MemberName == searchTerm;
NamedExpression ne = node as NamedExpression;
if (ne != null)
return ne.Name == searchTerm;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(member, mrr.Member, mrr.IsVirtualCall);
}
}
IMember NormalizeMember(IMember member)
{
if (WholeVirtualSlot && member.IsOverride)
member = InheritanceHelper.GetBaseMembers(member, false).FirstOrDefault(m => !m.IsOverride) ?? member;
if (!FindOnlySpecializedReferences)
member = member.MemberDefinition;
return member;
}
bool IsMemberMatch(IMember member, IMember referencedMember, bool isVirtualCall)
{
referencedMember = NormalizeMember(referencedMember);
if (member.Equals(referencedMember))
return true;
if (!isVirtualCall)
return false;
bool isInterfaceCall = referencedMember.DeclaringTypeDefinition != null && referencedMember.DeclaringTypeDefinition.Kind == TypeKind.Interface;
if (FindCallsThroughVirtualBaseMethod && member.IsOverride && !WholeVirtualSlot && !isInterfaceCall) {
// Test if 'member' overrides 'referencedMember':
foreach (var baseMember in InheritanceHelper.GetBaseMembers(member, false)) {
if (FindOnlySpecializedReferences) {
if (baseMember.Equals(referencedMember))
return true;
} else {
if (baseMember.MemberDefinition.Equals(referencedMember))
return true;
}
if (!baseMember.IsOverride)
break;
}
return false;
} else if (FindCallsThroughInterface && isInterfaceCall) {
// Test if 'member' implements 'referencedMember':
if (FindOnlySpecializedReferences) {
return member.ImplementedInterfaceMembers.Contains(referencedMember);
} else {
return member.ImplementedInterfaceMembers.Any(m => m.MemberDefinition.Equals(referencedMember));
}
}
return false;
}
bool PerformVirtualLookup(IMember member, IMember referencedMember)
{
if (FindCallsThroughVirtualBaseMethod && member.IsOverride && !WholeVirtualSlot)
return true;
var typeDef = referencedMember.DeclaringTypeDefinition;
return FindCallsThroughInterface && typeDef != null && typeDef.Kind == TypeKind.Interface;
}
sealed class FindFieldReferences : FindMemberReferencesNavigator
{
public FindFieldReferences(IField field) : base(field)
{
}
internal override bool CanMatch(AstNode node)
{
if (node is VariableInitializer) {
return node.Parent is FieldDeclaration;
}
return base.CanMatch(node);
}
}
sealed class FindEnumMemberReferences : FindMemberReferencesNavigator
{
public FindEnumMemberReferences(IField field) : base(field)
{
}
internal override bool CanMatch(AstNode node)
{
return node is EnumMemberDeclaration || base.CanMatch(node);
}
}
sealed class FindPropertyReferences : FindMemberReferencesNavigator
{
public FindPropertyReferences(IProperty property) : base(property)
{
}
internal override bool CanMatch(AstNode node)
{
return node is PropertyDeclaration || base.CanMatch(node);
}
}
sealed class FindEventReferences : FindMemberReferencesNavigator
{
public FindEventReferences(IEvent ev) : base(ev)
{
}
internal override bool CanMatch(AstNode node)
{
if (node is VariableInitializer) {
return node.Parent is EventDeclaration;
}
return node is CustomEventDeclaration || base.CanMatch(node);
}
}
#endregion
#region Find References to IEnumerator.Current
SearchScope FindEnumeratorCurrentReferences(IProperty property)
{
return new SearchScope(
delegate(ICompilation compilation) {
IProperty imported = compilation.Import(property);
return imported != null ? new FindEnumeratorCurrentReferencesNavigator(imported) : null;
});
}
SearchScope FindAwaiterIsCompletedReferences(IProperty property)
{
return new SearchScope(
delegate(ICompilation compilation) {
IProperty imported = compilation.Import(property);
return imported != null ? new FindAwaiterIsCompletedReferencesNavigator(imported) : null;
});
}
sealed class FindEnumeratorCurrentReferencesNavigator : FindReferenceNavigator
{
IProperty property;
public FindEnumeratorCurrentReferencesNavigator(IProperty property)
{
this.property = property;
}
internal override bool CanMatch(AstNode node)
{
return node is ForeachStatement;
}
internal override bool IsMatch(ResolveResult rr)
{
ForEachResolveResult ferr = rr as ForEachResolveResult;
return ferr != null && ferr.CurrentProperty != null && findReferences.IsMemberMatch(property, ferr.CurrentProperty, true);
}
}
sealed class FindAwaiterIsCompletedReferencesNavigator : FindReferenceNavigator
{
IProperty property;
public FindAwaiterIsCompletedReferencesNavigator(IProperty property)
{
this.property = property;
}
internal override bool CanMatch(AstNode node)
{
return node is UnaryOperatorExpression;
}
internal override bool IsMatch(ResolveResult rr)
{
AwaitResolveResult arr = rr as AwaitResolveResult;
return arr != null && arr.IsCompletedProperty != null && findReferences.IsMemberMatch(property, arr.IsCompletedProperty, true);
}
}
#endregion
#region Find Method References
SearchScope GetSearchScopeForMethod(IMethod method)
{
Type specialNodeType;
switch (method.Name) {
case "Add":
specialNodeType = typeof(ArrayInitializerExpression);
break;
case "Where":
specialNodeType = typeof(QueryWhereClause);
break;
case "Select":
specialNodeType = typeof(QuerySelectClause);
break;
case "SelectMany":
specialNodeType = typeof(QueryFromClause);
break;
case "Join":
case "GroupJoin":
specialNodeType = typeof(QueryJoinClause);
break;
case "OrderBy":
case "OrderByDescending":
case "ThenBy":
case "ThenByDescending":
specialNodeType = typeof(QueryOrdering);
break;
case "GroupBy":
specialNodeType = typeof(QueryGroupClause);
break;
case "Invoke":
if (method.DeclaringTypeDefinition != null && method.DeclaringTypeDefinition.Kind == TypeKind.Delegate)
specialNodeType = typeof(InvocationExpression);
else
specialNodeType = null;
break;
case "GetEnumerator":
case "MoveNext":
specialNodeType = typeof(ForeachStatement);
break;
case "GetAwaiter":
case "GetResult":
case "OnCompleted":
case "UnsafeOnCompleted":
specialNodeType = typeof(UnaryOperatorExpression);
break;
default:
specialNodeType = null;
break;
}
// Use searchTerm only if specialNodeType==null
string searchTerm = (specialNodeType == null) ? method.Name : null;
return new SearchScope(
searchTerm,
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(method);
if (imported != null)
return new FindMethodReferences(imported, specialNodeType);
else
return null;
});
}
sealed class FindMethodReferences : FindReferenceNavigator
{
readonly IMethod method;
readonly Type specialNodeType;
HashSet<Expression> potentialMethodGroupConversions = new HashSet<Expression>();
public FindMethodReferences(IMethod method, Type specialNodeType)
{
this.method = method;
this.specialNodeType = specialNodeType;
}
internal override bool CanMatch(AstNode node)
{
if (specialNodeType != null && node.GetType() == specialNodeType)
return true;
Expression expr = node as Expression;
if (expr == null)
return node is MethodDeclaration;
InvocationExpression ie = node as InvocationExpression;
if (ie != null) {
Expression target = ParenthesizedExpression.UnpackParenthesizedExpression(ie.Target);
IdentifierExpression ident = target as IdentifierExpression;
if (ident != null)
return ident.Identifier == method.Name;
MemberReferenceExpression mre = target as MemberReferenceExpression;
if (mre != null)
return mre.MemberName == method.Name;
PointerReferenceExpression pre = target as PointerReferenceExpression;
if (pre != null)
return pre.MemberName == method.Name;
} else if (expr.Role != Roles.TargetExpression) {
// MemberReferences & Identifiers that aren't used in an invocation can still match the method
// as delegate name.
if (expr.GetChildByRole(Roles.Identifier).Name == method.Name)
potentialMethodGroupConversions.Add(expr);
}
return node is MethodDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
if (specialNodeType != null) {
var ferr = rr as ForEachResolveResult;
if (ferr != null) {
return IsMatch(ferr.GetEnumeratorCall)
|| (ferr.MoveNextMethod != null && findReferences.IsMemberMatch(method, ferr.MoveNextMethod, true));
}
var arr = rr as AwaitResolveResult;
if (arr != null) {
return IsMatch(arr.GetAwaiterInvocation)
|| (arr.GetResultMethod != null && findReferences.IsMemberMatch(method, arr.GetResultMethod, true))
|| (arr.OnCompletedMethod != null && findReferences.IsMemberMatch(method, arr.OnCompletedMethod, true));
}
}
var mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(method, mrr.Member, mrr.IsVirtualCall);
}
internal override void NavigatorDone(CSharpAstResolver resolver, CancellationToken cancellationToken)
{
foreach (var expr in potentialMethodGroupConversions) {
var conversion = resolver.GetConversion(expr, cancellationToken);
if (conversion.IsMethodGroupConversion && findReferences.IsMemberMatch(method, conversion.Method, conversion.IsVirtualMethodLookup)) {
IType targetType = resolver.GetExpectedType(expr, cancellationToken);
ResolveResult result = resolver.Resolve(expr, cancellationToken);
ReportMatch(expr, new ConversionResolveResult(targetType, result, conversion));
}
}
base.NavigatorDone(resolver, cancellationToken);
}
}
#endregion
#region Find Indexer References
SearchScope FindIndexerReferences(IProperty indexer)
{
return new SearchScope(
delegate (ICompilation compilation) {
IProperty imported = compilation.Import(indexer);
if (imported != null)
return new FindIndexerReferencesNavigator(imported);
else
return null;
});
}
sealed class FindIndexerReferencesNavigator : FindReferenceNavigator
{
readonly IProperty indexer;
public FindIndexerReferencesNavigator(IProperty indexer)
{
this.indexer = indexer;
}
internal override bool CanMatch(AstNode node)
{
return node is IndexerExpression || node is IndexerDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(indexer, mrr.Member, mrr.IsVirtualCall);
}
}
#endregion
#region Find Operator References
SearchScope GetSearchScopeForOperator(IMethod op)
{
OperatorType? opType = OperatorDeclaration.GetOperatorType(op.Name);
if (opType == null)
return GetSearchScopeForMethod(op);
switch (opType.Value) {
case OperatorType.LogicalNot:
return FindUnaryOperator(op, UnaryOperatorType.Not);
case OperatorType.OnesComplement:
return FindUnaryOperator(op, UnaryOperatorType.BitNot);
case OperatorType.UnaryPlus:
return FindUnaryOperator(op, UnaryOperatorType.Plus);
case OperatorType.UnaryNegation:
return FindUnaryOperator(op, UnaryOperatorType.Minus);
case OperatorType.Increment:
return FindUnaryOperator(op, UnaryOperatorType.Increment);
case OperatorType.Decrement:
return FindUnaryOperator(op, UnaryOperatorType.Decrement);
case OperatorType.True:
case OperatorType.False:
// TODO: implement search for op_True/op_False correctly
return GetSearchScopeForMethod(op);
case OperatorType.Addition:
return FindBinaryOperator(op, BinaryOperatorType.Add);
case OperatorType.Subtraction:
return FindBinaryOperator(op, BinaryOperatorType.Subtract);
case OperatorType.Multiply:
return FindBinaryOperator(op, BinaryOperatorType.Multiply);
case OperatorType.Division:
return FindBinaryOperator(op, BinaryOperatorType.Divide);
case OperatorType.Modulus:
return FindBinaryOperator(op, BinaryOperatorType.Modulus);
case OperatorType.BitwiseAnd:
// TODO: an overloaded bitwise operator can also be called using the corresponding logical operator
// (if op_True/op_False is defined)
return FindBinaryOperator(op, BinaryOperatorType.BitwiseAnd);
case OperatorType.BitwiseOr:
return FindBinaryOperator(op, BinaryOperatorType.BitwiseOr);
case OperatorType.ExclusiveOr:
return FindBinaryOperator(op, BinaryOperatorType.ExclusiveOr);
case OperatorType.LeftShift:
return FindBinaryOperator(op, BinaryOperatorType.ShiftLeft);
case OperatorType.RightShift:
return FindBinaryOperator(op, BinaryOperatorType.ShiftRight);
case OperatorType.Equality:
return FindBinaryOperator(op, BinaryOperatorType.Equality);
case OperatorType.Inequality:
return FindBinaryOperator(op, BinaryOperatorType.InEquality);
case OperatorType.GreaterThan:
return FindBinaryOperator(op, BinaryOperatorType.GreaterThan);
case OperatorType.LessThan:
return FindBinaryOperator(op, BinaryOperatorType.LessThan);
case OperatorType.GreaterThanOrEqual:
return FindBinaryOperator(op, BinaryOperatorType.GreaterThanOrEqual);
case OperatorType.LessThanOrEqual:
return FindBinaryOperator(op, BinaryOperatorType.LessThanOrEqual);
case OperatorType.Implicit:
return FindOperator(op, m => new FindImplicitOperatorNavigator(m));
case OperatorType.Explicit:
return FindOperator(op, m => new FindExplicitOperatorNavigator(m));
default:
throw new InvalidOperationException("Invalid value for OperatorType");
}
}
SearchScope FindOperator(IMethod op, Func<IMethod, FindReferenceNavigator> factory)
{
return new SearchScope(
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(op);
return imported != null ? factory(imported) : null;
});
}
SearchScope FindUnaryOperator(IMethod op, UnaryOperatorType operatorType)
{
return FindOperator(op, m => new FindUnaryOperatorNavigator(m, operatorType));
}
sealed class FindUnaryOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
readonly UnaryOperatorType operatorType;
public FindUnaryOperatorNavigator(IMethod op, UnaryOperatorType operatorType)
{
this.op = op;
this.operatorType = operatorType;
}
internal override bool CanMatch(AstNode node)
{
UnaryOperatorExpression uoe = node as UnaryOperatorExpression;
if (uoe != null) {
if (operatorType == UnaryOperatorType.Increment)
return uoe.Operator == UnaryOperatorType.Increment || uoe.Operator == UnaryOperatorType.PostIncrement;
else if (operatorType == UnaryOperatorType.Decrement)
return uoe.Operator == UnaryOperatorType.Decrement || uoe.Operator == UnaryOperatorType.PostDecrement;
else
return uoe.Operator == operatorType;
}
return node is OperatorDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
}
}
SearchScope FindBinaryOperator(IMethod op, BinaryOperatorType operatorType)
{
return FindOperator(op, m => new FindBinaryOperatorNavigator(m, operatorType));
}
sealed class FindBinaryOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
readonly BinaryOperatorType operatorType;
public FindBinaryOperatorNavigator(IMethod op, BinaryOperatorType operatorType)
{
this.op = op;
this.operatorType = operatorType;
}
internal override bool CanMatch(AstNode node)
{
BinaryOperatorExpression boe = node as BinaryOperatorExpression;
if (boe != null) {
return boe.Operator == operatorType;
}
return node is OperatorDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
}
}
sealed class FindImplicitOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
public FindImplicitOperatorNavigator(IMethod op)
{
this.op = op;
}
internal override bool CanMatch(AstNode node)
{
return true;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(op, mrr.Member, mrr.IsVirtualCall);
}
public override void ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
{
if (conversion.IsUserDefined && findReferences.IsMemberMatch(op, conversion.Method, conversion.IsVirtualMethodLookup)) {
ReportMatch(expression, result);
}
}
}
sealed class FindExplicitOperatorNavigator : FindReferenceNavigator
{
readonly IMethod op;
public FindExplicitOperatorNavigator(IMethod op)
{
this.op = op;
}
internal override bool CanMatch(AstNode node)
{
return node is CastExpression;
}
internal override bool IsMatch(ResolveResult rr)
{
ConversionResolveResult crr = rr as ConversionResolveResult;
return crr != null && crr.Conversion.IsUserDefined
&& findReferences.IsMemberMatch(op, crr.Conversion.Method, crr.Conversion.IsVirtualMethodLookup);
}
}
#endregion
#region Find Constructor References
SearchScope FindObjectCreateReferences(IMethod ctor)
{
string searchTerm = null;
if (KnownTypeReference.GetCSharpNameByTypeCode(ctor.DeclaringTypeDefinition.KnownTypeCode) == null) {
// not a built-in type
searchTerm = ctor.DeclaringTypeDefinition.Name;
if (searchTerm.Length > 9 && searchTerm.EndsWith("Attribute", StringComparison.Ordinal)) {
// we also need to look for the short form
searchTerm = null;
}
}
return new SearchScope(
searchTerm,
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(ctor);
if (imported != null)
return new FindObjectCreateReferencesNavigator(imported);
else
return null;
});
}
sealed class FindObjectCreateReferencesNavigator : FindReferenceNavigator
{
readonly IMethod ctor;
public FindObjectCreateReferencesNavigator(IMethod ctor)
{
this.ctor = ctor;
}
internal override bool CanMatch(AstNode node)
{
return node is ObjectCreateExpression || node is ConstructorDeclaration || node is Attribute;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(ctor, mrr.Member, mrr.IsVirtualCall);
}
}
SearchScope FindChainedConstructorReferences(IMethod ctor)
{
SearchScope searchScope = new SearchScope(
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(ctor);
if (imported != null)
return new FindChainedConstructorReferencesNavigator(imported);
else
return null;
});
if (ctor.DeclaringTypeDefinition.IsSealed)
searchScope.accessibility = Accessibility.Private;
else
searchScope.accessibility = Accessibility.Protected;
searchScope.accessibility = MergeAccessibility(GetEffectiveAccessibility(ctor), searchScope.accessibility);
return searchScope;
}
sealed class FindChainedConstructorReferencesNavigator : FindReferenceNavigator
{
readonly IMethod ctor;
public FindChainedConstructorReferencesNavigator(IMethod ctor)
{
this.ctor = ctor;
}
internal override bool CanMatch(AstNode node)
{
return node is ConstructorInitializer;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(ctor, mrr.Member, mrr.IsVirtualCall);
}
}
#endregion
#region Find Destructor References
SearchScope GetSearchScopeForDestructor(IMethod dtor)
{
var scope = new SearchScope (
delegate (ICompilation compilation) {
IMethod imported = compilation.Import(dtor);
if (imported != null) {
return new FindDestructorReferencesNavigator (imported);
} else {
return null;
}
});
scope.accessibility = Accessibility.Private;
return scope;
}
sealed class FindDestructorReferencesNavigator : FindReferenceNavigator
{
readonly IMethod dtor;
public FindDestructorReferencesNavigator (IMethod dtor)
{
this.dtor = dtor;
}
internal override bool CanMatch(AstNode node)
{
return node is DestructorDeclaration;
}
internal override bool IsMatch(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
return mrr != null && findReferences.IsMemberMatch(dtor, mrr.Member, mrr.IsVirtualCall);
}
}
#endregion
#region Find Local Variable References
/// <summary>
/// Finds all references of a given variable.
/// </summary>
/// <param name="variable">The variable for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
public void FindLocalReferences(IVariable variable, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (variable == null)
throw new ArgumentNullException("variable");
var searchScope = new SearchScope(c => new FindLocalReferencesNavigator(variable));
searchScope.declarationCompilation = compilation;
FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
}
class FindLocalReferencesNavigator : FindReferenceNavigator
{
readonly IVariable variable;
public FindLocalReferencesNavigator(IVariable variable)
{
this.variable = variable;
}
internal override bool CanMatch(AstNode node)
{
var expr = node as IdentifierExpression;
if (expr != null)
return expr.TypeArguments.Count == 0 && variable.Name == expr.Identifier;
var vi = node as VariableInitializer;
if (vi != null)
return vi.Name == variable.Name;
var pd = node as ParameterDeclaration;
if (pd != null)
return pd.Name == variable.Name;
var id = node as Identifier;
if (id != null)
return id.Name == variable.Name;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
var lrr = rr as LocalResolveResult;
return lrr != null && lrr.Variable.Name == variable.Name && lrr.Variable.Region == variable.Region;
}
}
#endregion
#region Find Type Parameter References
/// <summary>
/// Finds all references of a given type parameter.
/// </summary>
/// <param name="typeParameter">The type parameter for which to look.</param>
/// <param name="unresolvedFile">The type system representation of the file being searched.</param>
/// <param name="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
[Obsolete("Use GetSearchScopes(typeParameter) instead")]
public void FindTypeParameterReferences(IType typeParameter, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (typeParameter == null)
throw new ArgumentNullException("typeParameter");
if (typeParameter.Kind != TypeKind.TypeParameter)
throw new ArgumentOutOfRangeException("typeParameter", "Only type parameters are allowed");
var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator((ITypeParameter)typeParameter));
searchScope.declarationCompilation = compilation;
searchScope.accessibility = Accessibility.Private;
FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
}
SearchScope GetSearchScopeForTypeParameter(ITypeParameter tp)
{
var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator(tp));
var compilationProvider = tp as ICompilationProvider;
if (compilationProvider != null)
searchScope.declarationCompilation = compilationProvider.Compilation;
searchScope.topLevelTypeDefinition = GetTopLevelTypeDefinition(tp.Owner);
searchScope.accessibility = Accessibility.Private;
return searchScope;
}
class FindTypeParameterReferencesNavigator : FindReferenceNavigator
{
readonly ITypeParameter typeParameter;
public FindTypeParameterReferencesNavigator(ITypeParameter typeParameter)
{
this.typeParameter = typeParameter;
}
internal override bool CanMatch(AstNode node)
{
var type = node as SimpleType;
if (type != null)
return type.Identifier == typeParameter.Name;
var declaration = node as TypeParameterDeclaration;
if (declaration != null)
return declaration.Name == typeParameter.Name;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
var lrr = rr as TypeResolveResult;
return lrr != null && lrr.Type.Kind == TypeKind.TypeParameter && ((ITypeParameter)lrr.Type).Region == typeParameter.Region;
}
}
#endregion
#region Find Namespace References
SearchScope GetSearchScopeForNamespace(INamespace ns)
{
var scope = new SearchScope (
delegate (ICompilation compilation) {
return new FindNamespaceNavigator (ns);
}
);
return scope;
}
sealed class FindNamespaceNavigator : FindReferenceNavigator
{
readonly INamespace ns;
public FindNamespaceNavigator (INamespace ns)
{
this.ns = ns;
}
internal override bool CanMatch(AstNode node)
{
var nsd = node as NamespaceDeclaration;
if (nsd != null && nsd.FullName.StartsWith(ns.FullName, StringComparison.Ordinal))
return true;
var ud = node as UsingDeclaration;
if (ud != null && ud.Namespace == ns.FullName)
return true;
var st = node as SimpleType;
if (st != null && st.Identifier == ns.Name)
return !st.AncestorsAndSelf.TakeWhile (n => n is AstType).Any (m => m.Role == NamespaceDeclaration.NamespaceNameRole);
var mt = node as MemberType;
if (mt != null && mt.MemberName == ns.Name)
return !mt.AncestorsAndSelf.TakeWhile (n => n is AstType).Any (m => m.Role == NamespaceDeclaration.NamespaceNameRole);
var identifer = node as IdentifierExpression;
if (identifer != null && identifer.Identifier == ns.Name)
return true;
var mrr = node as MemberReferenceExpression;
if (mrr != null && mrr.MemberName == ns.Name)
return true;
return false;
}
internal override bool IsMatch(ResolveResult rr)
{
var nsrr = rr as NamespaceResolveResult;
return nsrr != null && nsrr.NamespaceName.StartsWith(ns.FullName, StringComparison.Ordinal);
}
}
#endregion
}
}
|