Browse Source

Merge branch 'master' into simonl

newNRvisualizers
Simon Lindgren 14 years ago
parent
commit
19815e8132
  1. 2
      .gitignore
  2. 3
      ICSharpCode.NRefactory.CSharp.AstVerifier/.gitignore
  3. 3
      ICSharpCode.NRefactory.CSharp/.gitignore
  4. 54
      ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs
  5. 4
      ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs
  6. 103
      ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs
  7. 4
      ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs
  8. 4
      ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngineBase.cs
  9. 16
      ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs
  10. 9
      ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj
  11. 6
      ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs
  12. 4
      ICSharpCode.NRefactory.CSharp/Refactoring/BaseRefactoringContext.cs
  13. 2
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertToInitializer/StatementsToInitializerConverter.cs
  14. 2
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/InlineLocalVariableAction.cs
  15. 2
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/MoveToOuterScopeAction.cs
  16. 2
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveRedundantCatchTypeAction.cs
  17. 2
      ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/ValueParameterUnusedIssue.cs
  18. 44
      ICSharpCode.NRefactory.CSharp/Resolver/CSharpAstResolver.cs
  19. 54
      ICSharpCode.NRefactory.CSharp/Resolver/FindReferences.cs
  20. 107
      ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolution.cs
  21. 15
      ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolutionErrors.cs
  22. 16
      ICSharpCode.NRefactory.CSharp/Resolver/ResolveAtLocation.cs
  23. 40
      ICSharpCode.NRefactory.CSharp/Resolver/ResolveVisitor.cs
  24. 6
      ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpAssembly.cs
  25. 8
      ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpUnresolvedFile.cs
  26. 38
      ICSharpCode.NRefactory.CSharp/TypeSystem/TypeSystemConvertVisitor.cs
  27. 3
      ICSharpCode.NRefactory.ConsistencyCheck/.gitignore
  28. 68
      ICSharpCode.NRefactory.ConsistencyCheck/CSharpFile.cs
  29. 197
      ICSharpCode.NRefactory.ConsistencyCheck/CSharpProject.cs
  30. 13
      ICSharpCode.NRefactory.ConsistencyCheck/FindReferencesConsistencyCheck.cs
  31. 13
      ICSharpCode.NRefactory.ConsistencyCheck/ICSharpCode.NRefactory.ConsistencyCheck.csproj
  32. 6
      ICSharpCode.NRefactory.ConsistencyCheck/Program.cs
  33. 4
      ICSharpCode.NRefactory.ConsistencyCheck/RandomizedOrderResolverTest.cs
  34. 8
      ICSharpCode.NRefactory.ConsistencyCheck/ResolverTest.cs
  35. 2
      ICSharpCode.NRefactory.ConsistencyCheck/RoundtripTest.cs
  36. 23
      ICSharpCode.NRefactory.ConsistencyCheck/Solution.cs
  37. 5
      ICSharpCode.NRefactory.ConsistencyCheck/VisitorBenchmark.cs
  38. 3
      ICSharpCode.NRefactory.Demo/.gitignore
  39. 16
      ICSharpCode.NRefactory.Demo/CSDemo.cs
  40. 15
      ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj
  41. 3
      ICSharpCode.NRefactory.GtkDemo/.gitignore
  42. 6
      ICSharpCode.NRefactory.GtkDemo/MainWindow.cs
  43. 3
      ICSharpCode.NRefactory.Tests/.gitignore
  44. 12
      ICSharpCode.NRefactory.Tests/CSharp/CodeActions/TestRefactoringContext.cs
  45. 16
      ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/CodeCompletionBugTests.cs
  46. 12
      ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/ParameterCompletionTests.cs
  47. 12
      ICSharpCode.NRefactory.Tests/CSharp/CodeDomConvertVisitorTests.cs
  48. 12
      ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseSelfTests.cs
  49. 4
      ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs
  50. 8
      ICSharpCode.NRefactory.Tests/CSharp/Refactoring/TypeSystemAstBuilderTests.cs
  51. 1
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/ExplicitConversionsTest.cs
  52. 8
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/FindReferencesTest.cs
  53. 28
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs
  54. 20
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/MemberLookupTests.cs
  55. 12
      ICSharpCode.NRefactory.Tests/CSharp/Resolver/ResolverTestBase.cs
  56. 2
      ICSharpCode.NRefactory.Tests/Documentation/CSharpCrefLookupTests.cs
  57. 2
      ICSharpCode.NRefactory.Tests/Documentation/CSharpDocumentationTests.cs
  58. 60
      ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj
  59. 64
      ICSharpCode.NRefactory.Tests/TypeSystem/CyclicProjectDependency.cs
  60. 4
      ICSharpCode.NRefactory.Tests/TypeSystem/GetAllBaseTypesTest.cs
  61. 12
      ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemHelper.cs
  62. 3
      ICSharpCode.NRefactory.VB.Tests/.gitignore
  63. 3
      ICSharpCode.NRefactory.VB/.gitignore
  64. 3
      ICSharpCode.NRefactory.Xml/.gitignore
  65. 11
      ICSharpCode.NRefactory.Xml/ICSharpCode.NRefactory.Xml.csproj
  66. 3
      ICSharpCode.NRefactory/.gitignore
  67. 10
      ICSharpCode.NRefactory/Editor/ITextSource.cs
  68. 12
      ICSharpCode.NRefactory/Editor/ReadOnlyDocument.cs
  69. 34
      ICSharpCode.NRefactory/Editor/StringBuilderDocument.cs
  70. 12
      ICSharpCode.NRefactory/Editor/StringTextSource.cs
  71. 16
      ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj
  72. 33
      ICSharpCode.NRefactory/TypeSystem/DefaultSolutionSnapshot.cs
  73. 6
      ICSharpCode.NRefactory/TypeSystem/ExtensionMethods.cs
  74. 2
      ICSharpCode.NRefactory/TypeSystem/IEntity.cs
  75. 70
      ICSharpCode.NRefactory/TypeSystem/IProjectContent.cs
  76. 10
      ICSharpCode.NRefactory/TypeSystem/ISolutionSnapshot.cs
  77. 5
      ICSharpCode.NRefactory/TypeSystem/IUnresolvedFile.cs
  78. 9
      ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractFreezable.cs
  79. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractResolvedMember.cs
  80. 8
      ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractUnresolvedEntity.cs
  81. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAssemblyReference.cs
  82. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs
  83. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedEvent.cs
  84. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedField.cs
  85. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedMethod.cs
  86. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedProperty.cs
  87. 2
      ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedTypeDefinition.cs
  88. 3
      ICSharpCode.NRefactory/TypeSystem/Implementation/MinimalCorlib.cs
  89. 3
      ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleCompilation.cs
  90. 56
      ICSharpCode.NRefactory/TypeSystem/ProjectReference.cs
  91. 2
      doc/XML Documentation.html

2
.gitignore vendored

@ -1,3 +1,5 @@
bin
obj
/lib/*.dll /lib/*.dll
/ICSharpCode.NRefactory.Tests/PartCover/* /ICSharpCode.NRefactory.Tests/PartCover/*
_ReSharper*/* _ReSharper*/*

3
ICSharpCode.NRefactory.CSharp.AstVerifier/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

3
ICSharpCode.NRefactory.CSharp/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

54
ICSharpCode.NRefactory.CSharp/Ast/Expressions/ArrayInitializerExpression.cs

@ -34,7 +34,7 @@ namespace ICSharpCode.NRefactory.CSharp
public class ArrayInitializerExpression : Expression public class ArrayInitializerExpression : Expression
{ {
/// <summary> /// <summary>
/// For ease of use purposes in the resolver the ast representation /// For ease of use purposes in the resolver the ast representation
/// of { a, b, c } is { {a}, {b}, {c} }. /// of { a, b, c } is { {a}, {b}, {c} }.
/// If IsSingleElement is true then this array initializer expression is a generated one. /// If IsSingleElement is true then this array initializer expression is a generated one.
/// That has no meaning in the source code (and contains no brace tokens). /// That has no meaning in the source code (and contains no brace tokens).
@ -73,7 +73,7 @@ namespace ICSharpCode.NRefactory.CSharp
public override void AcceptVisitor (IAstVisitor visitor) public override void AcceptVisitor (IAstVisitor visitor)
{ {
} }
public override T AcceptVisitor<T> (IAstVisitor<T> visitor) public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{ {
return default (T); return default (T);
@ -107,7 +107,7 @@ namespace ICSharpCode.NRefactory.CSharp
{ {
visitor.VisitArrayInitializerExpression (this); visitor.VisitArrayInitializerExpression (this);
} }
public override T AcceptVisitor<T> (IAstVisitor<T> visitor) public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{ {
return visitor.VisitArrayInitializerExpression (this); return visitor.VisitArrayInitializerExpression (this);
@ -138,8 +138,54 @@ namespace ICSharpCode.NRefactory.CSharp
return true; return true;
} }
} }
}
#region PatternPlaceholder
public static implicit operator ArrayInitializerExpression(PatternMatching.Pattern pattern)
{
return pattern != null ? new PatternPlaceholder(pattern) : null;
}
sealed class PatternPlaceholder : ArrayInitializerExpression, PatternMatching.INode
{
readonly PatternMatching.Pattern child;
public PatternPlaceholder(PatternMatching.Pattern child)
{
this.child = child;
}
public override NodeType NodeType {
get { return NodeType.Pattern; }
}
public override void AcceptVisitor (IAstVisitor visitor)
{
visitor.VisitPatternPlaceholder(this, child);
}
public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
{
return visitor.VisitPatternPlaceholder(this, child);
}
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitPatternPlaceholder(this, child, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
return child.DoMatch(other, match);
}
bool PatternMatching.INode.DoMatchCollection(Role role, PatternMatching.INode pos, PatternMatching.Match match, PatternMatching.BacktrackingInfo backtrackingInfo)
{
return child.DoMatchCollection(role, pos, match, backtrackingInfo);
}
} }
#endregion
} }
} }

4
ICSharpCode.NRefactory.CSharp/Ast/SyntaxTree.cs

@ -146,13 +146,13 @@ namespace ICSharpCode.NRefactory.CSharp
/// <summary> /// <summary>
/// Converts this syntax tree into a parsed file that can be stored in the type system. /// Converts this syntax tree into a parsed file that can be stored in the type system.
/// </summary> /// </summary>
public CSharpParsedFile ToTypeSystem () public CSharpUnresolvedFile ToTypeSystem ()
{ {
if (string.IsNullOrEmpty (this.FileName)) if (string.IsNullOrEmpty (this.FileName))
throw new InvalidOperationException ("Cannot use ToTypeSystem() on a syntax tree without file name."); throw new InvalidOperationException ("Cannot use ToTypeSystem() on a syntax tree without file name.");
var v = new TypeSystemConvertVisitor (this.FileName); var v = new TypeSystemConvertVisitor (this.FileName);
v.VisitSyntaxTree (this); v.VisitSyntaxTree (this);
return v.ParsedFile; return v.UnresolvedFile;
} }
public static SyntaxTree Parse (string program, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken)) public static SyntaxTree Parse (string program, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default (CancellationToken))

103
ICSharpCode.NRefactory.CSharp/CSharpProjectContent.cs

@ -31,15 +31,15 @@ namespace ICSharpCode.NRefactory.CSharp
public class CSharpProjectContent : IProjectContent public class CSharpProjectContent : IProjectContent
{ {
string assemblyName; string assemblyName;
string projectFileName;
string location; string location;
Dictionary<string, IParsedFile> parsedFiles; Dictionary<string, IUnresolvedFile> unresolvedFiles;
List<IAssemblyReference> assemblyReferences; List<IAssemblyReference> assemblyReferences;
CompilerSettings compilerSettings; CompilerSettings compilerSettings;
public CSharpProjectContent() public CSharpProjectContent()
{ {
this.assemblyName = string.Empty; this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(Platform.FileNameComparer);
this.parsedFiles = new Dictionary<string, IParsedFile>(Platform.FileNameComparer);
this.assemblyReferences = new List<IAssemblyReference>(); this.assemblyReferences = new List<IAssemblyReference>();
this.compilerSettings = new CompilerSettings(); this.compilerSettings = new CompilerSettings();
compilerSettings.Freeze(); compilerSettings.Freeze();
@ -48,20 +48,25 @@ namespace ICSharpCode.NRefactory.CSharp
protected CSharpProjectContent(CSharpProjectContent pc) protected CSharpProjectContent(CSharpProjectContent pc)
{ {
this.assemblyName = pc.assemblyName; this.assemblyName = pc.assemblyName;
this.projectFileName = pc.projectFileName;
this.location = pc.location; this.location = pc.location;
this.parsedFiles = new Dictionary<string, IParsedFile>(pc.parsedFiles, Platform.FileNameComparer); this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(pc.unresolvedFiles, Platform.FileNameComparer);
this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences); this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
this.compilerSettings = pc.compilerSettings; this.compilerSettings = pc.compilerSettings;
} }
public IEnumerable<IParsedFile> Files { public IEnumerable<IUnresolvedFile> Files {
get { return parsedFiles.Values; } get { return unresolvedFiles.Values; }
} }
public IEnumerable<IAssemblyReference> AssemblyReferences { public IEnumerable<IAssemblyReference> AssemblyReferences {
get { return assemblyReferences; } get { return assemblyReferences; }
} }
public string ProjectFileName {
get { return projectFileName; }
}
public string AssemblyName { public string AssemblyName {
get { return assemblyName; } get { return assemblyName; }
} }
@ -96,10 +101,10 @@ namespace ICSharpCode.NRefactory.CSharp
} }
} }
public IParsedFile GetFile(string fileName) public IUnresolvedFile GetFile(string fileName)
{ {
IParsedFile file; IUnresolvedFile file;
if (parsedFiles.TryGetValue(fileName, out file)) if (unresolvedFiles.TryGetValue(fileName, out file))
return file; return file;
else else
return null; return null;
@ -129,11 +134,18 @@ namespace ICSharpCode.NRefactory.CSharp
pc.assemblyName = newAssemblyName; pc.assemblyName = newAssemblyName;
return pc; return pc;
} }
public IProjectContent SetProjectFileName(string newProjectFileName)
{
CSharpProjectContent pc = Clone();
pc.projectFileName = newProjectFileName;
return pc;
}
public IProjectContent SetLocation(string location) public IProjectContent SetLocation(string newLocation)
{ {
CSharpProjectContent pc = Clone(); CSharpProjectContent pc = Clone();
pc.location = location; pc.location = newLocation;
return pc; return pc;
} }
@ -148,6 +160,11 @@ namespace ICSharpCode.NRefactory.CSharp
} }
public IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references) public IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references)
{
return AddAssemblyReferences(references.ToArray());
}
public IProjectContent AddAssemblyReferences(params IAssemblyReference[] references)
{ {
CSharpProjectContent pc = Clone(); CSharpProjectContent pc = Clone();
pc.assemblyReferences.AddRange(references); pc.assemblyReferences.AddRange(references);
@ -155,13 +172,62 @@ namespace ICSharpCode.NRefactory.CSharp
} }
public IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references) public IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references)
{
return RemoveAssemblyReferences(references.ToArray());
}
public IProjectContent RemoveAssemblyReferences(params IAssemblyReference[] references)
{ {
CSharpProjectContent pc = Clone(); CSharpProjectContent pc = Clone();
pc.assemblyReferences.RemoveAll(r => references.Contains(r)); foreach (var r in references)
pc.assemblyReferences.Remove(r);
return pc; return pc;
} }
public IProjectContent UpdateProjectContent(IParsedFile oldFile, IParsedFile newFile) /// <summary>
/// Adds the specified files to the project content.
/// If a file with the same name already exists, updated the existing file.
/// </summary>
public IProjectContent AddOrUpdateFiles(IEnumerable<IUnresolvedFile> newFiles)
{
CSharpProjectContent pc = Clone();
foreach (var file in newFiles) {
pc.unresolvedFiles[file.FileName] = file;
}
return pc;
}
/// <summary>
/// Adds the specified files to the project content.
/// If a file with the same name already exists, this method updates the existing file.
/// </summary>
public IProjectContent AddOrUpdateFiles(params IUnresolvedFile[] newFiles)
{
return AddOrUpdateFiles((IEnumerable<IUnresolvedFile>)newFiles);
}
/// <summary>
/// Removes the files with the specified names.
/// </summary>
public IProjectContent RemoveFiles(IEnumerable<string> fileNames)
{
CSharpProjectContent pc = Clone();
foreach (var fileName in fileNames) {
pc.unresolvedFiles.Remove(fileName);
}
return pc;
}
/// <summary>
/// Removes the files with the specified names.
/// </summary>
public IProjectContent RemoveFiles(params string[] fileNames)
{
return RemoveFiles((IEnumerable<string>)fileNames);
}
[Obsolete("Use RemoveFiles/AddOrUpdateFiles instead")]
public IProjectContent UpdateProjectContent(IUnresolvedFile oldFile, IUnresolvedFile newFile)
{ {
if (oldFile == null && newFile == null) if (oldFile == null && newFile == null)
return this; return this;
@ -171,23 +237,24 @@ namespace ICSharpCode.NRefactory.CSharp
} }
CSharpProjectContent pc = Clone(); CSharpProjectContent pc = Clone();
if (newFile == null) if (newFile == null)
pc.parsedFiles.Remove(oldFile.FileName); pc.unresolvedFiles.Remove(oldFile.FileName);
else else
pc.parsedFiles[newFile.FileName] = newFile; pc.unresolvedFiles[newFile.FileName] = newFile;
return pc; return pc;
} }
public IProjectContent UpdateProjectContent(IEnumerable<IParsedFile> oldFiles, IEnumerable<IParsedFile> newFiles) [Obsolete("Use RemoveFiles/AddOrUpdateFiles instead")]
public IProjectContent UpdateProjectContent(IEnumerable<IUnresolvedFile> oldFiles, IEnumerable<IUnresolvedFile> newFiles)
{ {
CSharpProjectContent pc = Clone(); CSharpProjectContent pc = Clone();
if (oldFiles != null) { if (oldFiles != null) {
foreach (var oldFile in oldFiles) { foreach (var oldFile in oldFiles) {
pc.parsedFiles.Remove(oldFile.FileName); pc.unresolvedFiles.Remove(oldFile.FileName);
} }
} }
if (newFiles != null) { if (newFiles != null) {
foreach (var newFile in newFiles) { foreach (var newFile in newFiles) {
pc.parsedFiles.Add(newFile.FileName, newFile); pc.unresolvedFiles.Add(newFile.FileName, newFile);
} }
} }
return pc; return pc;

4
ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngine.cs

@ -723,7 +723,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
// var astResolver = new CSharpAstResolver( // var astResolver = new CSharpAstResolver(
// GetState(), // GetState(),
// identifierStart.Unit, // identifierStart.Unit,
// CSharpParsedFile // CSharpUnresolvedFile
// ); // );
// //
// foreach (var type in CreateFieldAction.GetValidTypes(astResolver, (Expression)n)) { // foreach (var type in CreateFieldAction.GetValidTypes(astResolver, (Expression)n)) {
@ -1172,7 +1172,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (csResolver == null) { if (csResolver == null) {
if (node != null) { if (node != null) {
csResolver = GetState(); csResolver = GetState();
//var astResolver = new CSharpAstResolver (csResolver, node, xp != null ? xp.Item1 : CSharpParsedFile); //var astResolver = new CSharpAstResolver (csResolver, node, xp != null ? xp.Item1 : CSharpUnresolvedFile);
try { try {
//csResolver = astResolver.GetResolverStateBefore (node); //csResolver = astResolver.GetResolverStateBefore (node);

4
ICSharpCode.NRefactory.CSharp/Completion/CSharpCompletionEngineBase.cs

@ -494,13 +494,13 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
state.CurrentMember = currentMember; state.CurrentMember = currentMember;
state.CurrentTypeDefinition = currentType; state.CurrentTypeDefinition = currentType;
state.CurrentUsingScope = CSharpParsedFile.GetUsingScope (location); state.CurrentUsingScope = CSharpUnresolvedFile.GetUsingScope (location);
if (state.CurrentMember != null) { if (state.CurrentMember != null) {
var node = Unit.GetNodeAt (location); var node = Unit.GetNodeAt (location);
if (node == null) if (node == null)
return state; return state;
var navigator = new NodeListResolveVisitorNavigator (new[] { node }); var navigator = new NodeListResolveVisitorNavigator (new[] { node });
var visitor = new ResolveVisitor (state, CSharpParsedFile, navigator); var visitor = new ResolveVisitor (state, CSharpUnresolvedFile, navigator);
Unit.AcceptVisitor (visitor, null); Unit.AcceptVisitor (visitor, null);
try { try {
var newState = visitor.GetResolverStateBefore (node); var newState = visitor.GetResolverStateBefore (node);

16
ICSharpCode.NRefactory.CSharp/Completion/ICompletionContextProvider.cs

@ -1,4 +1,4 @@
// //
// IMemberProvider.cs // IMemberProvider.cs
// //
// Author: // Author:
@ -45,16 +45,16 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public class DefaultCompletionContextProvider : ICompletionContextProvider public class DefaultCompletionContextProvider : ICompletionContextProvider
{ {
readonly IDocument document; readonly IDocument document;
readonly CSharpParsedFile parsedFile; readonly CSharpUnresolvedFile unresolvedFile;
public DefaultCompletionContextProvider (IDocument document, CSharpParsedFile parsedFile) public DefaultCompletionContextProvider (IDocument document, CSharpUnresolvedFile unresolvedFile)
{ {
if (document == null) if (document == null)
throw new ArgumentNullException("document"); throw new ArgumentNullException("document");
if (parsedFile == null) if (unresolvedFile == null)
throw new ArgumentNullException("parsedFile"); throw new ArgumentNullException("unresolvedFile");
this.document = document; this.document = document;
this.parsedFile = parsedFile; this.unresolvedFile = unresolvedFile;
} }
public void GetCurrentMembers(int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember) public void GetCurrentMembers(int offset, out IUnresolvedTypeDefinition currentType, out IUnresolvedMember currentMember)
@ -64,7 +64,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
currentType = null; currentType = null;
foreach (var type in parsedFile.TopLevelTypeDefinitions) { foreach (var type in unresolvedFile.TopLevelTypeDefinitions) {
if (type.Region.Begin < location) if (type.Region.Begin < location)
currentType = type; currentType = type;
} }
@ -189,7 +189,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
public CSharpAstResolver GetResolver (CSharpResolver resolver, AstNode rootNode) public CSharpAstResolver GetResolver (CSharpResolver resolver, AstNode rootNode)
{ {
return new CSharpAstResolver (resolver, rootNode, parsedFile); return new CSharpAstResolver (resolver, rootNode, unresolvedFile);
} }

9
ICSharpCode.NRefactory.CSharp/ICSharpCode.NRefactory.CSharp.csproj

@ -18,8 +18,9 @@
<AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile>
<DelaySign>False</DelaySign> <DelaySign>False</DelaySign>
<AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode> <AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode>
<DocumentationFile>..\ICSharpCode.NRefactory\bin\$(Configuration)\ICSharpCode.NRefactory.CSharp.xml</DocumentationFile> <DocumentationFile>..\bin\$(Configuration)\ICSharpCode.NRefactory.CSharp.xml</DocumentationFile>
<NoWarn>1591,1587,1570</NoWarn> <NoWarn>1591,1587,1570</NoWarn>
<OutputPath>..\bin\$(Configuration)\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' "> <PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -29,13 +30,11 @@
<FileAlignment>4096</FileAlignment> <FileAlignment>4096</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<Optimize>False</Optimize> <Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;FULL_AST</DefineConstants> <DefineConstants>DEBUG;TRACE;FULL_AST</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;FULL_AST</DefineConstants> <DefineConstants>TRACE;FULL_AST</DefineConstants>
@ -48,7 +47,6 @@
<DebugSymbols>True</DebugSymbols> <DebugSymbols>True</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<Optimize>False</Optimize> <Optimize>False</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;FULL_AST;NET45</DefineConstants> <DefineConstants>DEBUG;TRACE;FULL_AST;NET45</DefineConstants>
@ -59,7 +57,6 @@
<DebugSymbols>True</DebugSymbols> <DebugSymbols>True</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;FULL_AST;NET45</DefineConstants> <DefineConstants>TRACE;FULL_AST;NET45</DefineConstants>
@ -303,7 +300,7 @@
<Compile Include="TypeSystem\CSharpAssembly.cs" /> <Compile Include="TypeSystem\CSharpAssembly.cs" />
<Compile Include="TypeSystem\CSharpAttribute.cs" /> <Compile Include="TypeSystem\CSharpAttribute.cs" />
<Compile Include="TypeSystem\CSharpDocumentationComment.cs" /> <Compile Include="TypeSystem\CSharpDocumentationComment.cs" />
<Compile Include="TypeSystem\CSharpParsedFile.cs" /> <Compile Include="TypeSystem\CSharpUnresolvedFile.cs" />
<Compile Include="TypeSystem\CSharpUnresolvedTypeDefinition.cs" /> <Compile Include="TypeSystem\CSharpUnresolvedTypeDefinition.cs" />
<Compile Include="TypeSystem\CSharpTypeResolveContext.cs" /> <Compile Include="TypeSystem\CSharpTypeResolveContext.cs" />
<Compile Include="TypeSystem\ResolvedUsingScope.cs" /> <Compile Include="TypeSystem\ResolvedUsingScope.cs" />

6
ICSharpCode.NRefactory.CSharp/OutputVisitor/CodeDomConvertVisitor.cs

@ -64,19 +64,19 @@ namespace ICSharpCode.NRefactory.CSharp
/// </summary> /// </summary>
/// <param name="syntaxTree">The input syntax tree.</param> /// <param name="syntaxTree">The input syntax tree.</param>
/// <param name="compilation">The current compilation.</param> /// <param name="compilation">The current compilation.</param>
/// <param name="parsedFile">CSharpParsedFile, used for resolving.</param> /// <param name="unresolvedFile">CSharpUnresolvedFile, used for resolving.</param>
/// <returns>Converted CodeCompileUnit</returns> /// <returns>Converted CodeCompileUnit</returns>
/// <remarks> /// <remarks>
/// This conversion process requires a resolver because it needs to distinguish field/property/event references etc. /// This conversion process requires a resolver because it needs to distinguish field/property/event references etc.
/// </remarks> /// </remarks>
public CodeCompileUnit Convert(ICompilation compilation, SyntaxTree syntaxTree, CSharpParsedFile parsedFile) public CodeCompileUnit Convert(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile)
{ {
if (syntaxTree == null) if (syntaxTree == null)
throw new ArgumentNullException("syntaxTree"); throw new ArgumentNullException("syntaxTree");
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException("compilation");
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, parsedFile); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
return (CodeCompileUnit)Convert(syntaxTree, resolver); return (CodeCompileUnit)Convert(syntaxTree, resolver);
} }

4
ICSharpCode.NRefactory.CSharp/Refactoring/BaseRefactoringContext.cs

@ -73,9 +73,9 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} }
} }
public virtual CSharpParsedFile ParsedFile { public virtual CSharpUnresolvedFile UnresolvedFile {
get { get {
return resolver.ParsedFile; return resolver.UnresolvedFile;
} }
} }

2
ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertToInitializer/StatementsToInitializerConverter.cs

@ -328,7 +328,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
bool HasDependencyCheck(FindReferences referenceFinder, LocalResolveResult localResolveResult) bool HasDependencyCheck(FindReferences referenceFinder, LocalResolveResult localResolveResult)
{ {
bool result = false; bool result = false;
referenceFinder.FindLocalReferences(localResolveResult.Variable, context.ParsedFile, referenceFinder.FindLocalReferences(localResolveResult.Variable, context.UnresolvedFile,
(SyntaxTree)context.RootNode, context.Compilation, (SyntaxTree)context.RootNode, context.Compilation,
(node, resolveResult) => { (node, resolveResult) => {
result |= VariableHasBeenConverted(localResolveResult.Variable); result |= VariableHasBeenConverted(localResolveResult.Variable);

2
ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/InlineLocalVariableAction.cs

@ -58,7 +58,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
yield break; yield break;
} }
yield return new CodeAction(context.TranslateString("Inline local variable"), script => { yield return new CodeAction(context.TranslateString("Inline local variable"), script => {
refFinder.FindLocalReferences(resolveResult.Variable, context.ParsedFile, unit, context.Compilation, (n, r) => script.Replace(n, initializer.Initializer.Clone()), default(CancellationToken)); refFinder.FindLocalReferences(resolveResult.Variable, context.UnresolvedFile, unit, context.Compilation, (n, r) => script.Replace(n, initializer.Initializer.Clone()), default(CancellationToken));
script.Remove(node); script.Remove(node);
}); });
} }

2
ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/MoveToOuterScopeAction.cs

@ -105,7 +105,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
bool referenceFound = false; bool referenceFound = false;
var variable = localResolveResult.Variable; var variable = localResolveResult.Variable;
var syntaxTree = context.RootNode as SyntaxTree; var syntaxTree = context.RootNode as SyntaxTree;
referenceFinder.FindLocalReferences(localResolveResult.Variable, context.ParsedFile, syntaxTree, referenceFinder.FindLocalReferences(localResolveResult.Variable, context.UnresolvedFile, syntaxTree,
context.Compilation, (node, nodeResolveResult) => { context.Compilation, (node, nodeResolveResult) => {
if (node.StartLocation > firstSearchNode.StartLocation && node.EndLocation < targetNode.StartLocation) if (node.StartLocation > firstSearchNode.StartLocation && node.EndLocation < targetNode.StartLocation)
referenceFound = true; referenceFound = true;

2
ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/RemoveRedundantCatchTypeAction.cs

@ -66,7 +66,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{ {
int referencesFound = 0; int referencesFound = 0;
var findRef = new FindReferences(); var findRef = new FindReferences();
findRef.FindLocalReferences(variable, context.ParsedFile, syntaxTree, context.Compilation, (n, entity) => { findRef.FindLocalReferences(variable, context.UnresolvedFile, syntaxTree, context.Compilation, (n, entity) => {
referencesFound++; referencesFound++;
}, CancellationToken.None); }, CancellationToken.None);

2
ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/ValueParameterUnusedIssue.cs

@ -83,7 +83,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
bool referenceFound = false; bool referenceFound = false;
var findRef = new FindReferences(); var findRef = new FindReferences();
var syntaxTree = (SyntaxTree)context.RootNode; var syntaxTree = (SyntaxTree)context.RootNode;
findRef.FindLocalReferences(variable, context.ParsedFile, syntaxTree, context.Compilation, (n, entity) => { findRef.FindLocalReferences(variable, context.UnresolvedFile, syntaxTree, context.Compilation, (n, entity) => {
if (n.StartLocation >= node.StartLocation && n.EndLocation <= node.EndLocation) { if (n.StartLocation >= node.StartLocation && n.EndLocation <= node.EndLocation) {
referenceFound = true; referenceFound = true;
} }

44
ICSharpCode.NRefactory.CSharp/Resolver/CSharpAstResolver.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
readonly CSharpResolver initialResolverState; readonly CSharpResolver initialResolverState;
readonly AstNode rootNode; readonly AstNode rootNode;
readonly CSharpParsedFile parsedFile; readonly CSharpUnresolvedFile unresolvedFile;
readonly ResolveVisitor resolveVisitor; readonly ResolveVisitor resolveVisitor;
bool resolverInitialized; bool resolverInitialized;
@ -42,20 +42,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// Use this overload if you are resolving within a complete C# file. /// Use this overload if you are resolving within a complete C# file.
/// </summary> /// </summary>
/// <param name="compilation">The current compilation.</param> /// <param name="compilation">The current compilation.</param>
/// <param name="syntaxTree">The syntax tree corresponding to the specified parsed file.</param> /// <param name="syntaxTree">The syntax tree to be resolved.</param>
/// <param name="parsedFile"> /// <param name="unresolvedFile">
/// Optional: Result of the <see cref="TypeSystemConvertVisitor"/> for the file being resolved. /// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
/// <para> /// <para>
/// This is used for setting up the context on the resolver. The parsed file must be registered in the compilation. /// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
/// </para> /// </para>
/// <para> /// <para>
/// When a parsedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify /// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
/// member declarations in the AST with members in the type system. /// member declarations in the AST with members in the type system.
/// When no parsedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the /// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
/// member's signature in the AST with the signature in the type system. /// member's signature in the AST with the signature in the type system.
/// </para> /// </para>
/// </param> /// </param>
public CSharpAstResolver(ICompilation compilation, SyntaxTree syntaxTree, CSharpParsedFile parsedFile = null) public CSharpAstResolver(ICompilation compilation, SyntaxTree syntaxTree, CSharpUnresolvedFile unresolvedFile = null)
{ {
if (compilation == null) if (compilation == null)
throw new ArgumentNullException("compilation"); throw new ArgumentNullException("compilation");
@ -63,8 +63,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
throw new ArgumentNullException("syntaxTree"); throw new ArgumentNullException("syntaxTree");
this.initialResolverState = new CSharpResolver(compilation); this.initialResolverState = new CSharpResolver(compilation);
this.rootNode = syntaxTree; this.rootNode = syntaxTree;
this.parsedFile = parsedFile; this.unresolvedFile = unresolvedFile;
this.resolveVisitor = new ResolveVisitor(initialResolverState, parsedFile); this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
} }
/// <summary> /// <summary>
@ -72,20 +72,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// Use this overload if you are resolving code snippets (not necessarily complete files). /// Use this overload if you are resolving code snippets (not necessarily complete files).
/// </summary> /// </summary>
/// <param name="resolver">The resolver state at the root node (to be more precise: just outside the root node).</param> /// <param name="resolver">The resolver state at the root node (to be more precise: just outside the root node).</param>
/// <param name="rootNode">The root node of the resolved tree.</param> /// <param name="rootNode">The root node of the tree to be resolved.</param>
/// <param name="parsedFile"> /// <param name="unresolvedFile">
/// Optional: Result of the <see cref="TypeSystemConvertVisitor"/> for the file being resolved. /// Optional: Result of <see cref="SyntaxTree.ToTypeSystem()"/> for the file being resolved.
/// <para> /// <para>
/// This is used for setting up the context on the resolver. The parsed file must be registered in the compilation. /// This is used for setting up the context on the resolver. The unresolved file must be registered in the compilation.
/// </para> /// </para>
/// <para> /// <para>
/// When a parsedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify /// When a unresolvedFile is specified, the resolver will use the member's StartLocation/EndLocation to identify
/// member declarations in the AST with members in the type system. /// member declarations in the AST with members in the type system.
/// When no parsedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the /// When no unresolvedFile is specified (<c>null</c> value for this parameter), the resolver will instead compare the
/// member's signature in the AST with the signature in the type system. /// member's signature in the AST with the signature in the type system.
/// </para> /// </para>
/// </param> /// </param>
public CSharpAstResolver(CSharpResolver resolver, AstNode rootNode, CSharpParsedFile parsedFile = null) public CSharpAstResolver(CSharpResolver resolver, AstNode rootNode, CSharpUnresolvedFile unresolvedFile = null)
{ {
if (resolver == null) if (resolver == null)
throw new ArgumentNullException("resolver"); throw new ArgumentNullException("resolver");
@ -93,8 +93,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
throw new ArgumentNullException("rootNode"); throw new ArgumentNullException("rootNode");
this.initialResolverState = resolver; this.initialResolverState = resolver;
this.rootNode = rootNode; this.rootNode = rootNode;
this.parsedFile = parsedFile; this.unresolvedFile = unresolvedFile;
this.resolveVisitor = new ResolveVisitor(initialResolverState, parsedFile); this.resolveVisitor = new ResolveVisitor(initialResolverState, unresolvedFile);
} }
/// <summary> /// <summary>
@ -119,11 +119,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
/// <summary> /// <summary>
/// Gets the parsed file used by this CSharpAstResolver. /// Gets the unresolved file used by this CSharpAstResolver.
/// Can return null. /// Can return null.
/// </summary> /// </summary>
public CSharpParsedFile ParsedFile { public CSharpUnresolvedFile UnresolvedFile {
get { return parsedFile; } get { return unresolvedFile; }
} }
/// <summary> /// <summary>

54
ICSharpCode.NRefactory.CSharp/Resolver/FindReferences.cs

@ -290,7 +290,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary> /// <summary>
/// Gets the file names that possibly contain references to the element being searched for. /// Gets the file names that possibly contain references to the element being searched for.
/// </summary> /// </summary>
public IEnumerable<CSharpParsedFile> GetInterestingFiles(IFindReferenceSearchScope searchScope, ICompilation compilation) public IEnumerable<CSharpUnresolvedFile> GetInterestingFiles(IFindReferenceSearchScope searchScope, ICompilation compilation)
{ {
if (searchScope == null) if (searchScope == null)
throw new ArgumentNullException("searchScope"); throw new ArgumentNullException("searchScope");
@ -303,47 +303,47 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ITypeDefinition topLevelTypeDef = compilation.Import(searchScope.TopLevelTypeDefinition); ITypeDefinition topLevelTypeDef = compilation.Import(searchScope.TopLevelTypeDefinition);
if (topLevelTypeDef == null) { if (topLevelTypeDef == null) {
// This compilation cannot have references to the target entity. // This compilation cannot have references to the target entity.
return EmptyList<CSharpParsedFile>.Instance; return EmptyList<CSharpUnresolvedFile>.Instance;
} }
switch (searchScope.Accessibility) { switch (searchScope.Accessibility) {
case Accessibility.None: case Accessibility.None:
case Accessibility.Private: case Accessibility.Private:
if (topLevelTypeDef.ParentAssembly == compilation.MainAssembly) if (topLevelTypeDef.ParentAssembly == compilation.MainAssembly)
return topLevelTypeDef.Parts.Select(p => p.ParsedFile).OfType<CSharpParsedFile>().Distinct(); return topLevelTypeDef.Parts.Select(p => p.UnresolvedFile).OfType<CSharpUnresolvedFile>().Distinct();
else else
return EmptyList<CSharpParsedFile>.Instance; return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.Protected: case Accessibility.Protected:
return GetInterestingFilesProtected(topLevelTypeDef); return GetInterestingFilesProtected(topLevelTypeDef);
case Accessibility.Internal: case Accessibility.Internal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly)) if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return pc.Files.OfType<CSharpParsedFile>(); return pc.Files.OfType<CSharpUnresolvedFile>();
else else
return EmptyList<CSharpParsedFile>.Instance; return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedAndInternal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly)) if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return GetInterestingFilesProtected(topLevelTypeDef); return GetInterestingFilesProtected(topLevelTypeDef);
else else
return EmptyList<CSharpParsedFile>.Instance; return EmptyList<CSharpUnresolvedFile>.Instance;
case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedOrInternal:
if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly)) if (topLevelTypeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly))
return pc.Files.OfType<CSharpParsedFile>(); return pc.Files.OfType<CSharpUnresolvedFile>();
else else
return GetInterestingFilesProtected(topLevelTypeDef); return GetInterestingFilesProtected(topLevelTypeDef);
default: default:
return pc.Files.OfType<CSharpParsedFile>(); return pc.Files.OfType<CSharpUnresolvedFile>();
} }
} else { } else {
return pc.Files.OfType<CSharpParsedFile>(); return pc.Files.OfType<CSharpUnresolvedFile>();
} }
} }
IEnumerable<CSharpParsedFile> GetInterestingFilesProtected(ITypeDefinition referencedTypeDefinition) IEnumerable<CSharpUnresolvedFile> GetInterestingFilesProtected(ITypeDefinition referencedTypeDefinition)
{ {
return (from typeDef in referencedTypeDefinition.Compilation.MainAssembly.GetAllTypeDefinitions() return (from typeDef in referencedTypeDefinition.Compilation.MainAssembly.GetAllTypeDefinitions()
where typeDef.IsDerivedFrom(referencedTypeDefinition) where typeDef.IsDerivedFrom(referencedTypeDefinition)
from part in typeDef.Parts from part in typeDef.Parts
select part.ParsedFile select part.UnresolvedFile
).OfType<CSharpParsedFile>().Distinct(); ).OfType<CSharpUnresolvedFile>().Distinct();
} }
#endregion #endregion
@ -352,35 +352,35 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// Finds all references in the given file. /// Finds all references in the given file.
/// </summary> /// </summary>
/// <param name="searchScope">The search scope for which to look.</param> /// <param name="searchScope">The search scope for which to look.</param>
/// <param name="parsedFile">The type system representation of the file being searched.</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="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="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="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param> /// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{ {
if (searchScope == null) if (searchScope == null)
throw new ArgumentNullException("searchScope"); throw new ArgumentNullException("searchScope");
FindReferencesInFile(new[] { searchScope }, parsedFile, syntaxTree, compilation, callback, cancellationToken); FindReferencesInFile(new[] { searchScope }, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
} }
/// <summary> /// <summary>
/// Finds all references in the given file. /// Finds all references in the given file.
/// </summary> /// </summary>
/// <param name="searchScopes">The search scopes for which to look.</param> /// <param name="searchScopes">The search scopes for which to look.</param>
/// <param name="parsedFile">The type system representation of the file being searched.</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="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="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="callback">Callback used to report the references that were found.</param>
/// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param> /// <param name="cancellationToken">CancellationToken that may be used to cancel the operation.</param>
public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{ {
if (searchScopes == null) if (searchScopes == null)
throw new ArgumentNullException("searchScopes"); throw new ArgumentNullException("searchScopes");
if (parsedFile == null) if (unresolvedFile == null)
throw new ArgumentNullException("parsedFile"); throw new ArgumentNullException("unresolvedFile");
if (syntaxTree == null) if (syntaxTree == null)
throw new ArgumentNullException("syntaxTree"); throw new ArgumentNullException("syntaxTree");
if (compilation == null) if (compilation == null)
@ -404,7 +404,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
combinedNavigator = new DetectSkippableNodesNavigator(combinedNavigator, syntaxTree); combinedNavigator = new DetectSkippableNodesNavigator(combinedNavigator, syntaxTree);
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, parsedFile); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
resolver.ApplyNavigator(combinedNavigator, cancellationToken); resolver.ApplyNavigator(combinedNavigator, cancellationToken);
foreach (var n in navigators) { foreach (var n in navigators) {
var frn = n as FindReferenceNavigator; var frn = n as FindReferenceNavigator;
@ -1171,19 +1171,19 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// Finds all references of a given variable. /// Finds all references of a given variable.
/// </summary> /// </summary>
/// <param name="variable">The variable for which to look.</param> /// <param name="variable">The variable for which to look.</param>
/// <param name="parsedFile">The type system representation of the file being searched.</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="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation.</param> /// <param name="compilation">The compilation.</param>
/// <param name="callback">Callback used to report the references that were found.</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> /// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
public void FindLocalReferences(IVariable variable, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, public void FindLocalReferences(IVariable variable, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{ {
if (variable == null) if (variable == null)
throw new ArgumentNullException("variable"); throw new ArgumentNullException("variable");
var searchScope = new SearchScope(c => new FindLocalReferencesNavigator(variable)); var searchScope = new SearchScope(c => new FindLocalReferencesNavigator(variable));
searchScope.declarationCompilation = compilation; searchScope.declarationCompilation = compilation;
FindReferencesInFile(searchScope, parsedFile, syntaxTree, compilation, callback, cancellationToken); FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
} }
class FindLocalReferencesNavigator : FindReferenceNavigator class FindLocalReferencesNavigator : FindReferenceNavigator
@ -1225,12 +1225,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// Finds all references of a given type parameter. /// Finds all references of a given type parameter.
/// </summary> /// </summary>
/// <param name="typeParameter">The type parameter for which to look.</param> /// <param name="typeParameter">The type parameter for which to look.</param>
/// <param name="parsedFile">The type system representation of the file being searched.</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="syntaxTree">The syntax tree of the file being searched.</param>
/// <param name="compilation">The compilation.</param> /// <param name="compilation">The compilation.</param>
/// <param name="callback">Callback used to report the references that were found.</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> /// <param name="cancellationToken">Cancellation token that may be used to cancel the operation.</param>
public void FindTypeParameterReferences(IType typeParameter, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, public void FindTypeParameterReferences(IType typeParameter, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree,
ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken) ICompilation compilation, FoundReferenceCallback callback, CancellationToken cancellationToken)
{ {
if (typeParameter == null) if (typeParameter == null)
@ -1240,7 +1240,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator((ITypeParameter)typeParameter)); var searchScope = new SearchScope(c => new FindTypeParameterReferencesNavigator((ITypeParameter)typeParameter));
searchScope.declarationCompilation = compilation; searchScope.declarationCompilation = compilation;
searchScope.accessibility = Accessibility.Private; searchScope.accessibility = Accessibility.Private;
FindReferencesInFile(searchScope, parsedFile, syntaxTree, compilation, callback, cancellationToken); FindReferencesInFile(searchScope, unresolvedFile, syntaxTree, compilation, callback, cancellationToken);
} }
class FindTypeParameterReferencesNavigator : FindReferenceNavigator class FindTypeParameterReferencesNavigator : FindReferenceNavigator

107
ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolution.cs

@ -118,7 +118,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public void AddError(OverloadResolutionErrors newError) public void AddError(OverloadResolutionErrors newError)
{ {
this.Errors |= newError; this.Errors |= newError;
this.ErrorCount++; if (!IsApplicable(newError))
this.ErrorCount++;
} }
} }
@ -130,6 +131,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Candidate bestCandidate; Candidate bestCandidate;
Candidate bestCandidateAmbiguousWith; Candidate bestCandidateAmbiguousWith;
IType[] explicitlyGivenTypeArguments; IType[] explicitlyGivenTypeArguments;
bool bestCandidateWasValidated;
OverloadResolutionErrors bestCandidateValidationResult;
#region Constructor #region Constructor
public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null) public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null)
@ -155,6 +158,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
#endregion #endregion
#region Input Properties
/// <summary> /// <summary>
/// Gets/Sets whether the methods are extension methods that are being called using extension method syntax. /// Gets/Sets whether the methods are extension methods that are being called using extension method syntax.
/// </summary> /// </summary>
@ -183,21 +187,36 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public IList<ResolveResult> Arguments { public IList<ResolveResult> Arguments {
get { return arguments; } get { return arguments; }
} }
#endregion
#region AddCandidate #region AddCandidate
/// <summary>
/// Adds a candidate to overload resolution.
/// </summary>
/// <param name="member">The candidate member to add.</param>
/// <returns>The errors that prevent the member from being applicable, if any.
/// Note: this method does not return errors that do not affect applicability.</returns>
public OverloadResolutionErrors AddCandidate(IParameterizedMember member) public OverloadResolutionErrors AddCandidate(IParameterizedMember member)
{ {
return AddCandidate(member, OverloadResolutionErrors.None); return AddCandidate(member, OverloadResolutionErrors.None);
} }
/// <summary>
/// Adds a candidate to overload resolution.
/// </summary>
/// <param name="member">The candidate member to add.</param>
/// <param name="additionalErrors">Additional errors that apply to the candidate.
/// This is used to represent errors during member lookup (e.g. OverloadResolutionErrors.Inaccessible)
/// in overload resolution.</param>
/// <returns>The errors that prevent the member from being applicable, if any.
/// Note: this method does not return errors that do not affect applicability.</returns>
public OverloadResolutionErrors AddCandidate(IParameterizedMember member, OverloadResolutionErrors additionalErrors) public OverloadResolutionErrors AddCandidate(IParameterizedMember member, OverloadResolutionErrors additionalErrors)
{ {
if (member == null) if (member == null)
throw new ArgumentNullException("member"); throw new ArgumentNullException("member");
Candidate c = new Candidate(member, false); Candidate c = new Candidate(member, false);
if (additionalErrors != OverloadResolutionErrors.None) c.AddError(additionalErrors);
c.AddError(additionalErrors);
if (CalculateCandidate(c)) { if (CalculateCandidate(c)) {
//candidates.Add(c); //candidates.Add(c);
} }
@ -206,8 +225,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
&& member.Parameters[member.Parameters.Count - 1].IsParams) && member.Parameters[member.Parameters.Count - 1].IsParams)
{ {
Candidate expandedCandidate = new Candidate(member, true); Candidate expandedCandidate = new Candidate(member, true);
if (additionalErrors != OverloadResolutionErrors.None) expandedCandidate.AddError(additionalErrors);
expandedCandidate.AddError(additionalErrors);
// consider expanded form only if it isn't obviously wrong // consider expanded form only if it isn't obviously wrong
if (CalculateCandidate(expandedCandidate)) { if (CalculateCandidate(expandedCandidate)) {
//candidates.Add(expandedCandidate); //candidates.Add(expandedCandidate);
@ -219,11 +237,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return c.Errors; return c.Errors;
} }
public static bool IsApplicable(OverloadResolutionErrors errors)
{
return (errors & ~OverloadResolutionErrors.AmbiguousMatch) == OverloadResolutionErrors.None;
}
/// <summary> /// <summary>
/// Calculates applicability etc. for the candidate. /// Calculates applicability etc. for the candidate.
/// </summary> /// </summary>
@ -236,6 +249,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
RunTypeInference(candidate); RunTypeInference(candidate);
CheckApplicability(candidate); CheckApplicability(candidate);
ConsiderIfNewCandidateIsBest(candidate); ConsiderIfNewCandidateIsBest(candidate);
ValidateMethodConstraints(candidate);
return true; return true;
} }
@ -432,20 +446,36 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
#endregion #endregion
#region Validate Constraints #region Validate Constraints
OverloadResolutionErrors ValidateMethodConstraints(Candidate candidate)
{
// If type inference already failed, we won't check the constraints:
if ((candidate.Errors & OverloadResolutionErrors.TypeInferenceFailed) != 0)
return OverloadResolutionErrors.None;
IMethod method = candidate.Member as IMethod;
if (method == null || method.TypeParameters.Count == 0)
return OverloadResolutionErrors.None; // the method isn't generic
var substitution = GetSubstitution(candidate);
for (int i = 0; i < method.TypeParameters.Count; i++) {
if (!ValidateConstraints(method.TypeParameters[i], substitution.MethodTypeArguments[i], substitution))
return OverloadResolutionErrors.MethodConstraintsNotSatisfied;
}
return OverloadResolutionErrors.None;
}
/// <summary> /// <summary>
/// Validates whether the given type argument satisfies the constraints for the given type parameter. /// Validates whether the given type argument satisfies the constraints for the given type parameter.
/// </summary> /// </summary>
/// <param name="typeParameter">The type parameter.</param> /// <param name="typeParameter">The type parameter.</param>
/// <param name="typeArgument">The type argument.</param> /// <param name="typeArgument">The type argument.</param>
/// <param name="substitution">The substitution that defines how type parameters are replaced with type arguments. /// <param name="substitution">The substitution that defines how type parameters are replaced with type arguments.
/// The substitution is used to check constraints that depend on other type parameters (or recursively on the same type parameter).</param> /// The substitution is used to check constraints that depend on other type parameters (or recursively on the same type parameter).
/// May be null if no substitution should be used.</param>
/// <returns>True if the constraints are satisfied; false otherwise.</returns> /// <returns>True if the constraints are satisfied; false otherwise.</returns>
public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution) public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution = null)
{ {
if (typeParameter == null) if (typeParameter == null)
throw new ArgumentNullException("typeParameter"); throw new ArgumentNullException("typeParameter");
if (typeParameter.Owner == null)
throw new ArgumentNullException("typeParameter.Owner");
if (typeArgument == null) if (typeArgument == null)
throw new ArgumentNullException("typeArgument"); throw new ArgumentNullException("typeArgument");
return ValidateConstraints(typeParameter, typeArgument, substitution, CSharpConversions.Get(typeParameter.Owner.Compilation)); return ValidateConstraints(typeParameter, typeArgument, substitution, CSharpConversions.Get(typeParameter.Owner.Compilation));
@ -490,6 +520,16 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
#endregion #endregion
#region CheckApplicability #region CheckApplicability
/// <summary>
/// Returns whether a candidate with the given errors is still considered to be applicable.
/// </summary>
public static bool IsApplicable(OverloadResolutionErrors errors)
{
const OverloadResolutionErrors errorsThatDoNotMatterForApplicability =
OverloadResolutionErrors.AmbiguousMatch | OverloadResolutionErrors.MethodConstraintsNotSatisfied;
return (errors & ~errorsThatDoNotMatterForApplicability) == OverloadResolutionErrors.None;
}
void CheckApplicability(Candidate candidate) void CheckApplicability(Candidate candidate)
{ {
// C# 4.0 spec: §7.5.3.1 Applicable function member // C# 4.0 spec: §7.5.3.1 Applicable function member
@ -697,6 +737,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
if (bestCandidate == null) { if (bestCandidate == null) {
bestCandidate = candidate; bestCandidate = candidate;
bestCandidateWasValidated = false;
} else { } else {
switch (BetterFunctionMember(candidate, bestCandidate)) { switch (BetterFunctionMember(candidate, bestCandidate)) {
case 0: case 0:
@ -707,6 +748,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
break; break;
case 1: case 1:
bestCandidate = candidate; bestCandidate = candidate;
bestCandidateWasValidated = false;
bestCandidateAmbiguousWith = null; bestCandidateAmbiguousWith = null;
break; break;
// case 2: best candidate stays best // case 2: best candidate stays best
@ -715,15 +757,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
#endregion #endregion
#region Output Properties
public IParameterizedMember BestCandidate { public IParameterizedMember BestCandidate {
get { return bestCandidate != null ? bestCandidate.Member : null; } get { return bestCandidate != null ? bestCandidate.Member : null; }
} }
/// <summary>
/// Returns the errors that apply to the best candidate.
/// This includes additional errors that do not affect applicability (e.g. AmbiguousMatch, MethodConstraintsNotSatisfied)
/// </summary>
public OverloadResolutionErrors BestCandidateErrors { public OverloadResolutionErrors BestCandidateErrors {
get { get {
if (bestCandidate == null) if (bestCandidate == null)
return OverloadResolutionErrors.None; return OverloadResolutionErrors.None;
OverloadResolutionErrors err = bestCandidate.Errors; if (!bestCandidateWasValidated) {
bestCandidateValidationResult = ValidateMethodConstraints(bestCandidate);
bestCandidateWasValidated = true;
}
OverloadResolutionErrors err = bestCandidate.Errors | bestCandidateValidationResult;
if (bestCandidateAmbiguousWith != null) if (bestCandidateAmbiguousWith != null)
err |= OverloadResolutionErrors.AmbiguousMatch; err |= OverloadResolutionErrors.AmbiguousMatch;
return err; return err;
@ -731,7 +782,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
public bool FoundApplicableCandidate { public bool FoundApplicableCandidate {
get { return bestCandidate != null && bestCandidate.Errors == OverloadResolutionErrors.None; } get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); }
} }
public IParameterizedMember BestCandidateAmbiguousWith { public IParameterizedMember BestCandidateAmbiguousWith {
@ -848,21 +899,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return null; return null;
IMethod method = bestCandidate.Member as IMethod; IMethod method = bestCandidate.Member as IMethod;
if (method != null && method.TypeParameters.Count > 0) { if (method != null && method.TypeParameters.Count > 0) {
SpecializedMethod sm = method as SpecializedMethod; return new SpecializedMethod((IMethod)method.MemberDefinition, GetSubstitution(bestCandidate));
if (sm != null) {
// Do not compose the substitutions, but merge them.
// This is required for InvocationTests.SubstituteClassAndMethodTypeParametersAtOnce
return new SpecializedMethod(
(IMethod)method.MemberDefinition,
new TypeParameterSubstitution(sm.Substitution.ClassTypeArguments, bestCandidate.InferredTypes));
} else {
return new SpecializedMethod(method, new TypeParameterSubstitution(null, bestCandidate.InferredTypes));
}
} else { } else {
return bestCandidate.Member; return bestCandidate.Member;
} }
} }
TypeParameterSubstitution GetSubstitution(Candidate candidate)
{
SpecializedMethod sm = candidate.Member as SpecializedMethod;
if (sm != null) {
// Do not compose the substitutions, but merge them.
// This is required for InvocationTests.SubstituteClassAndMethodTypeParametersAtOnce
return new TypeParameterSubstitution(sm.Substitution.ClassTypeArguments, candidate.InferredTypes);
} else {
return new TypeParameterSubstitution(null, candidate.InferredTypes);
}
}
/// <summary> /// <summary>
/// Creates a ResolveResult representing the result of overload resolution. /// Creates a ResolveResult representing the result of overload resolution.
/// </summary> /// </summary>
@ -890,5 +944,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
argumentToParameterMap: this.GetArgumentToParameterMap(), argumentToParameterMap: this.GetArgumentToParameterMap(),
initializerStatements: initializerStatements); initializerStatements: initializerStatements);
} }
#endregion
} }
} }

15
ICSharpCode.NRefactory.CSharp/Resolver/OverloadResolutionErrors.cs

@ -65,10 +65,23 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// There is no unique best overload. /// There is no unique best overload.
/// This error does not apply to any single candidate, but only to the overall result of overload resolution. /// This error does not apply to any single candidate, but only to the overall result of overload resolution.
/// </summary> /// </summary>
/// <remarks>
/// This error does not prevent a candidate from being applicable.
/// </remarks>
AmbiguousMatch = 0x0200, AmbiguousMatch = 0x0200,
/// <summary> /// <summary>
/// The member is not accessible. /// The member is not accessible.
/// </summary> /// </summary>
Inaccessible = 0x0400 /// <remarks>
/// This error is generated by member lookup; not by overload resolution.
/// </remarks>
Inaccessible = 0x0400,
/// <summary>
/// A generic method
/// </summary>
/// <remarks>
/// This error does not prevent a candidate from being applicable.
/// </remarks>
MethodConstraintsNotSatisfied = 0x0800
} }
} }

16
ICSharpCode.NRefactory.CSharp/Resolver/ResolveAtLocation.cs

@ -30,24 +30,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary> /// </summary>
public static class ResolveAtLocation public static class ResolveAtLocation
{ {
public static ResolveResult Resolve (ICompilation compilation, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, TextLocation location, public static ResolveResult Resolve (ICompilation compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))
{ {
return Resolve (new Lazy<ICompilation>(() => compilation), parsedFile, syntaxTree, location, cancellationToken); return Resolve (new Lazy<ICompilation>(() => compilation), unresolvedFile, syntaxTree, location, cancellationToken);
} }
public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, TextLocation location, public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))
{ {
AstNode node; AstNode node;
return Resolve(compilation, parsedFile, syntaxTree, location, out node, cancellationToken); return Resolve(compilation, unresolvedFile, syntaxTree, location, out node, cancellationToken);
} }
public static ResolveResult Resolve (ICompilation compilation, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node, public static ResolveResult Resolve (ICompilation compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))
{ {
return Resolve (new Lazy<ICompilation>(() => compilation), parsedFile, syntaxTree, location, out node, cancellationToken); return Resolve (new Lazy<ICompilation>(() => compilation), unresolvedFile, syntaxTree, location, out node, cancellationToken);
} }
public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpParsedFile parsedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node, public static ResolveResult Resolve(Lazy<ICompilation> compilation, CSharpUnresolvedFile unresolvedFile, SyntaxTree syntaxTree, TextLocation location, out AstNode node,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))
{ {
node = syntaxTree.GetNodeAt(location); node = syntaxTree.GetNodeAt(location);
@ -96,7 +96,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} }
// TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused // TODO: I think we should provide an overload so that an existing CSharpAstResolver can be reused
CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, syntaxTree, parsedFile); CSharpAstResolver resolver = new CSharpAstResolver(compilation.Value, syntaxTree, unresolvedFile);
ResolveResult rr = resolver.Resolve(node, cancellationToken); ResolveResult rr = resolver.Resolve(node, cancellationToken);
if (rr is MethodGroupResolveResult && parentInvocation != null) if (rr is MethodGroupResolveResult && parentInvocation != null)
return resolver.Resolve(parentInvocation); return resolver.Resolve(parentInvocation);

40
ICSharpCode.NRefactory.CSharp/Resolver/ResolveVisitor.cs

@ -64,7 +64,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <remarks>We do not have to put this into the stored state (resolver) because /// <remarks>We do not have to put this into the stored state (resolver) because
/// query expressions are always resolved in a single operation.</remarks> /// query expressions are always resolved in a single operation.</remarks>
ResolveResult currentQueryResult; ResolveResult currentQueryResult;
readonly CSharpParsedFile parsedFile; readonly CSharpUnresolvedFile unresolvedFile;
readonly Dictionary<AstNode, ResolveResult> resolveResultCache = new Dictionary<AstNode, ResolveResult>(); readonly Dictionary<AstNode, ResolveResult> resolveResultCache = new Dictionary<AstNode, ResolveResult>();
readonly Dictionary<AstNode, CSharpResolver> resolverBeforeDict = new Dictionary<AstNode, CSharpResolver>(); readonly Dictionary<AstNode, CSharpResolver> resolverBeforeDict = new Dictionary<AstNode, CSharpResolver>();
readonly Dictionary<AstNode, CSharpResolver> resolverAfterDict = new Dictionary<AstNode, CSharpResolver>(); readonly Dictionary<AstNode, CSharpResolver> resolverAfterDict = new Dictionary<AstNode, CSharpResolver>();
@ -93,12 +93,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary> /// <summary>
/// Creates a new ResolveVisitor instance. /// Creates a new ResolveVisitor instance.
/// </summary> /// </summary>
public ResolveVisitor(CSharpResolver resolver, CSharpParsedFile parsedFile) public ResolveVisitor(CSharpResolver resolver, CSharpUnresolvedFile unresolvedFile)
{ {
if (resolver == null) if (resolver == null)
throw new ArgumentNullException("resolver"); throw new ArgumentNullException("resolver");
this.resolver = resolver; this.resolver = resolver;
this.parsedFile = parsedFile; this.unresolvedFile = unresolvedFile;
this.navigator = skipAllNavigator; this.navigator = skipAllNavigator;
} }
@ -534,12 +534,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
CSharpResolver previousResolver = resolver; CSharpResolver previousResolver = resolver;
try { try {
if (parsedFile != null) { if (unresolvedFile != null) {
resolver = resolver.WithCurrentUsingScope(parsedFile.RootUsingScope.Resolve(resolver.Compilation)); resolver = resolver.WithCurrentUsingScope(unresolvedFile.RootUsingScope.Resolve(resolver.Compilation));
} else { } else {
var cv = new TypeSystemConvertVisitor(unit.FileName ?? string.Empty); var cv = new TypeSystemConvertVisitor(unit.FileName ?? string.Empty);
ApplyVisitorToUsings(cv, unit.Children); ApplyVisitorToUsings(cv, unit.Children);
PushUsingScope(cv.ParsedFile.RootUsingScope); PushUsingScope(cv.UnresolvedFile.RootUsingScope);
} }
ScanChildren(unit); ScanChildren(unit);
return voidResult; return voidResult;
@ -567,8 +567,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
CSharpResolver previousResolver = resolver; CSharpResolver previousResolver = resolver;
try { try {
if (parsedFile != null) { if (unresolvedFile != null) {
resolver = resolver.WithCurrentUsingScope(parsedFile.GetUsingScope(namespaceDeclaration.StartLocation).Resolve(resolver.Compilation)); resolver = resolver.WithCurrentUsingScope(unresolvedFile.GetUsingScope(namespaceDeclaration.StartLocation).Resolve(resolver.Compilation));
} else { } else {
string fileName = namespaceDeclaration.GetRegion().FileName ?? string.Empty; string fileName = namespaceDeclaration.GetRegion().FileName ?? string.Empty;
// Fetch parent using scope // Fetch parent using scope
@ -589,7 +589,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// Last using scope: // Last using scope:
usingScope = new UsingScope(resolver.CurrentUsingScope.UnresolvedUsingScope, identifiers.Last().Name); usingScope = new UsingScope(resolver.CurrentUsingScope.UnresolvedUsingScope, identifiers.Last().Name);
usingScope.Region = region; usingScope.Region = region;
var cv = new TypeSystemConvertVisitor(new CSharpParsedFile(region.FileName ?? string.Empty), usingScope); var cv = new TypeSystemConvertVisitor(new CSharpUnresolvedFile(region.FileName ?? string.Empty), usingScope);
ApplyVisitorToUsings(cv, namespaceDeclaration.Children); ApplyVisitorToUsings(cv, namespaceDeclaration.Children);
PushUsingScope(usingScope); PushUsingScope(usingScope);
} }
@ -673,7 +673,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
for (AstNode node = fieldOrEventDeclaration.FirstChild; node != null; node = node.NextSibling) { for (AstNode node = fieldOrEventDeclaration.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == Roles.Variable) { if (node.Role == Roles.Variable) {
IMember member; IMember member;
if (parsedFile != null) { if (unresolvedFile != null) {
member = GetMemberFromLocation(node); member = GetMemberFromLocation(node);
} else { } else {
string name = ((VariableInitializer)node).Name; string name = ((VariableInitializer)node).Name;
@ -699,7 +699,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
TextLocation location = TypeSystemConvertVisitor.GetStartLocationAfterAttributes(node); TextLocation location = TypeSystemConvertVisitor.GetStartLocationAfterAttributes(node);
return typeDef.GetMembers( return typeDef.GetMembers(
delegate (IUnresolvedMember m) { delegate (IUnresolvedMember m) {
if (m.ParsedFile != parsedFile) if (m.UnresolvedFile != unresolvedFile)
return false; return false;
DomRegion region = m.Region; DomRegion region = m.Region;
return !region.IsEmpty && region.Begin <= location && region.End > location; return !region.IsEmpty && region.Begin <= location && region.End > location;
@ -792,7 +792,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
CSharpResolver oldResolver = resolver; CSharpResolver oldResolver = resolver;
try { try {
IMember member; IMember member;
if (parsedFile != null) { if (unresolvedFile != null) {
member = GetMemberFromLocation(memberDeclaration); member = GetMemberFromLocation(memberDeclaration);
} else { } else {
// Re-discover the method: // Re-discover the method:
@ -855,7 +855,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
CSharpResolver oldResolver = resolver; CSharpResolver oldResolver = resolver;
try { try {
IMember member; IMember member;
if (parsedFile != null) { if (unresolvedFile != null) {
member = GetMemberFromLocation(propertyOrIndexerDeclaration); member = GetMemberFromLocation(propertyOrIndexerDeclaration);
} else { } else {
// Re-discover the property: // Re-discover the property:
@ -911,7 +911,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
CSharpResolver oldResolver = resolver; CSharpResolver oldResolver = resolver;
try { try {
IMember member; IMember member;
if (parsedFile != null) { if (unresolvedFile != null) {
member = GetMemberFromLocation(eventDeclaration); member = GetMemberFromLocation(eventDeclaration);
} else { } else {
string name = eventDeclaration.Name; string name = eventDeclaration.Name;
@ -1034,7 +1034,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Scan(attributeSection); Scan(attributeSection);
IMember member = null; IMember member = null;
if (parsedFile != null) { if (unresolvedFile != null) {
member = GetMemberFromLocation(enumMemberDeclaration); member = GetMemberFromLocation(enumMemberDeclaration);
} else if (resolver.CurrentTypeDefinition != null) { } else if (resolver.CurrentTypeDefinition != null) {
string name = enumMemberDeclaration.Name; string name = enumMemberDeclaration.Name;
@ -1958,8 +1958,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
DomRegion MakeRegion(AstNode node) DomRegion MakeRegion(AstNode node)
{ {
if (parsedFile != null) if (unresolvedFile != null)
return new DomRegion(parsedFile.FileName, node.StartLocation, node.EndLocation); return new DomRegion(unresolvedFile.FileName, node.StartLocation, node.EndLocation);
else else
return node.GetRegion(); return node.GetRegion();
} }
@ -2148,7 +2148,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
readonly QuerySelectClause selectClause; readonly QuerySelectClause selectClause;
readonly CSharpResolver storedContext; readonly CSharpResolver storedContext;
readonly CSharpParsedFile parsedFile; readonly CSharpUnresolvedFile unresolvedFile;
readonly List<LambdaTypeHypothesis> hypotheses = new List<LambdaTypeHypothesis>(); readonly List<LambdaTypeHypothesis> hypotheses = new List<LambdaTypeHypothesis>();
internal IList<IParameter> parameters = new List<IParameter>(); internal IList<IParameter> parameters = new List<IParameter>();
@ -2186,7 +2186,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
this.parentVisitor = parentVisitor; this.parentVisitor = parentVisitor;
this.storedContext = parentVisitor.resolver; this.storedContext = parentVisitor.resolver;
this.parsedFile = parentVisitor.parsedFile; this.unresolvedFile = parentVisitor.unresolvedFile;
this.bodyResult = parentVisitor.voidResult; this.bodyResult = parentVisitor.voidResult;
} }
@ -2254,7 +2254,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (ok) if (ok)
return h; return h;
} }
ResolveVisitor visitor = new ResolveVisitor(storedContext, parsedFile); ResolveVisitor visitor = new ResolveVisitor(storedContext, unresolvedFile);
var newHypothesis = new LambdaTypeHypothesis(this, parameterTypes, visitor, lambda != null ? lambda.Parameters : null); var newHypothesis = new LambdaTypeHypothesis(this, parameterTypes, visitor, lambda != null ? lambda.Parameters : null);
hypotheses.Add(newHypothesis); hypotheses.Add(newHypothesis);
return newHypothesis; return newHypothesis;

6
ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpAssembly.cs

@ -73,9 +73,9 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
return result; return result;
} else { } else {
result = new List<IAttribute>(); result = new List<IAttribute>();
foreach (var parsedFile in projectContent.Files.OfType<CSharpParsedFile>()) { foreach (var unresolvedFile in projectContent.Files.OfType<CSharpUnresolvedFile>()) {
var attributes = assemblyAttributes ? parsedFile.AssemblyAttributes : parsedFile.ModuleAttributes; var attributes = assemblyAttributes ? unresolvedFile.AssemblyAttributes : unresolvedFile.ModuleAttributes;
var context = new CSharpTypeResolveContext(this, parsedFile.RootUsingScope.Resolve(compilation)); var context = new CSharpTypeResolveContext(this, unresolvedFile.RootUsingScope.Resolve(compilation));
foreach (var unresolvedAttr in attributes) { foreach (var unresolvedAttr in attributes) {
result.Add(unresolvedAttr.CreateResolvedAttribute(context)); result.Add(unresolvedAttr.CreateResolvedAttribute(context));
} }

8
ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpParsedFile.cs → ICSharpCode.NRefactory.CSharp/TypeSystem/CSharpUnresolvedFile.cs

@ -30,7 +30,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
/// Represents a file that was parsed and converted for the type system. /// Represents a file that was parsed and converted for the type system.
/// </summary> /// </summary>
[Serializable] [Serializable]
public sealed class CSharpParsedFile : AbstractFreezable, IParsedFile, IUnresolvedDocumentationProvider public sealed class CSharpUnresolvedFile : AbstractFreezable, IUnresolvedFile, IUnresolvedDocumentationProvider
{ {
readonly string fileName; readonly string fileName;
readonly UsingScope rootUsingScope; readonly UsingScope rootUsingScope;
@ -51,7 +51,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
usingScopes = FreezableHelper.FreezeListAndElements(usingScopes); usingScopes = FreezableHelper.FreezeListAndElements(usingScopes);
} }
public CSharpParsedFile(string fileName) public CSharpUnresolvedFile(string fileName)
{ {
if (fileName == null) if (fileName == null)
throw new ArgumentNullException("fileName"); throw new ArgumentNullException("fileName");
@ -59,7 +59,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
this.rootUsingScope = new UsingScope(); this.rootUsingScope = new UsingScope();
} }
public CSharpParsedFile(string fileName, UsingScope rootUsingScope) public CSharpUnresolvedFile(string fileName, UsingScope rootUsingScope)
{ {
if (fileName == null) if (fileName == null)
throw new ArgumentNullException("fileName"); throw new ArgumentNullException("fileName");
@ -178,7 +178,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
return rctx; return rctx;
} }
ITypeResolveContext IParsedFile.GetTypeResolveContext (ICompilation compilation, TextLocation loc) ITypeResolveContext IUnresolvedFile.GetTypeResolveContext (ICompilation compilation, TextLocation loc)
{ {
return GetTypeResolveContext (compilation, loc); return GetTypeResolveContext (compilation, loc);
} }

38
ICSharpCode.NRefactory.CSharp/TypeSystem/TypeSystemConvertVisitor.cs

@ -34,7 +34,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
/// </summary> /// </summary>
public class TypeSystemConvertVisitor : DepthFirstAstVisitor<IUnresolvedEntity> public class TypeSystemConvertVisitor : DepthFirstAstVisitor<IUnresolvedEntity>
{ {
readonly CSharpParsedFile parsedFile; readonly CSharpUnresolvedFile unresolvedFile;
UsingScope usingScope; UsingScope usingScope;
CSharpUnresolvedTypeDefinition currentTypeDefinition; CSharpUnresolvedTypeDefinition currentTypeDefinition;
DefaultUnresolvedMethod currentMethod; DefaultUnresolvedMethod currentMethod;
@ -64,32 +64,32 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{ {
if (fileName == null) if (fileName == null)
throw new ArgumentNullException("fileName"); throw new ArgumentNullException("fileName");
this.parsedFile = new CSharpParsedFile(fileName); this.unresolvedFile = new CSharpUnresolvedFile(fileName);
this.usingScope = parsedFile.RootUsingScope; this.usingScope = unresolvedFile.RootUsingScope;
} }
/// <summary> /// <summary>
/// Creates a new TypeSystemConvertVisitor and initializes it with a given context. /// Creates a new TypeSystemConvertVisitor and initializes it with a given context.
/// </summary> /// </summary>
/// <param name="parsedFile">The parsed file to which members should be added.</param> /// <param name="unresolvedFile">The parsed file to which members should be added.</param>
/// <param name="currentUsingScope">The current using scope.</param> /// <param name="currentUsingScope">The current using scope.</param>
/// <param name="currentTypeDefinition">The current type definition.</param> /// <param name="currentTypeDefinition">The current type definition.</param>
public TypeSystemConvertVisitor(CSharpParsedFile parsedFile, UsingScope currentUsingScope = null, CSharpUnresolvedTypeDefinition currentTypeDefinition = null) public TypeSystemConvertVisitor(CSharpUnresolvedFile unresolvedFile, UsingScope currentUsingScope = null, CSharpUnresolvedTypeDefinition currentTypeDefinition = null)
{ {
if (parsedFile == null) if (unresolvedFile == null)
throw new ArgumentNullException("parsedFile"); throw new ArgumentNullException("unresolvedFile");
this.parsedFile = parsedFile; this.unresolvedFile = unresolvedFile;
this.usingScope = currentUsingScope ?? parsedFile.RootUsingScope; this.usingScope = currentUsingScope ?? unresolvedFile.RootUsingScope;
this.currentTypeDefinition = currentTypeDefinition; this.currentTypeDefinition = currentTypeDefinition;
} }
public CSharpParsedFile ParsedFile { public CSharpUnresolvedFile UnresolvedFile {
get { return parsedFile; } get { return unresolvedFile; }
} }
DomRegion MakeRegion(TextLocation start, TextLocation end) DomRegion MakeRegion(TextLocation start, TextLocation end)
{ {
return new DomRegion(parsedFile.FileName, start.Line, start.Column, end.Line, end.Column); return new DomRegion(unresolvedFile.FileName, start.Line, start.Column, end.Line, end.Column);
} }
DomRegion MakeRegion(AstNode node) DomRegion MakeRegion(AstNode node)
@ -122,7 +122,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
#region Compilation Unit #region Compilation Unit
public override IUnresolvedEntity VisitSyntaxTree (SyntaxTree unit) public override IUnresolvedEntity VisitSyntaxTree (SyntaxTree unit)
{ {
parsedFile.Errors = unit.Errors; unresolvedFile.Errors = unit.Errors;
return base.VisitSyntaxTree (unit); return base.VisitSyntaxTree (unit);
} }
#endregion #endregion
@ -167,7 +167,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
usingScope.Region = region; usingScope.Region = region;
} }
base.VisitNamespaceDeclaration(namespaceDeclaration); base.VisitNamespaceDeclaration(namespaceDeclaration);
parsedFile.UsingScopes.Add(usingScope); // add after visiting children so that nested scopes come first unresolvedFile.UsingScopes.Add(usingScope); // add after visiting children so that nested scopes come first
usingScope = previousUsingScope; usingScope = previousUsingScope;
return null; return null;
} }
@ -184,9 +184,9 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
currentTypeDefinition.NestedTypes.Add(newType); currentTypeDefinition.NestedTypes.Add(newType);
} else { } else {
newType = new CSharpUnresolvedTypeDefinition(usingScope, name); newType = new CSharpUnresolvedTypeDefinition(usingScope, name);
parsedFile.TopLevelTypeDefinitions.Add(newType); unresolvedFile.TopLevelTypeDefinitions.Add(newType);
} }
newType.ParsedFile = parsedFile; newType.UnresolvedFile = unresolvedFile;
newType.HasExtensionMethods = false; // gets set to true when an extension method is added newType.HasExtensionMethods = false; // gets set to true when an extension method is added
return newType; return newType;
} }
@ -868,9 +868,9 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{ {
// non-assembly attributes are handled by their parent entity // non-assembly attributes are handled by their parent entity
if (attributeSection.AttributeTarget == "assembly") { if (attributeSection.AttributeTarget == "assembly") {
ConvertAttributes(parsedFile.AssemblyAttributes, attributeSection); ConvertAttributes(unresolvedFile.AssemblyAttributes, attributeSection);
} else if (attributeSection.AttributeTarget == "module") { } else if (attributeSection.AttributeTarget == "module") {
ConvertAttributes(parsedFile.ModuleAttributes, attributeSection); ConvertAttributes(unresolvedFile.ModuleAttributes, attributeSection);
} }
return null; return null;
} }
@ -1197,7 +1197,7 @@ namespace ICSharpCode.NRefactory.CSharp.TypeSystem
} }
if (documentation != null) { if (documentation != null) {
documentation.Reverse(); // bring documentation in correct order documentation.Reverse(); // bring documentation in correct order
parsedFile.AddDocumentation(entity, string.Join(Environment.NewLine, documentation)); unresolvedFile.AddDocumentation(entity, string.Join(Environment.NewLine, documentation));
} }
} }

3
ICSharpCode.NRefactory.ConsistencyCheck/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

68
ICSharpCode.NRefactory.ConsistencyCheck/CSharpFile.cs

@ -0,0 +1,68 @@
// Copyright (c) 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.IO;
using System.Linq;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Editor;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.ConsistencyCheck
{
public class CSharpFile
{
public readonly CSharpProject Project;
public readonly string FileName;
public readonly string OriginalText;
public SyntaxTree SyntaxTree;
public CSharpUnresolvedFile UnresolvedTypeSystemForFile;
public CSharpFile(CSharpProject project, string fileName)
{
this.Project = project;
this.FileName = fileName;
CSharpParser p = new CSharpParser(project.CompilerSettings);
// using (var stream = File.OpenRead(fileName)) {
// this.CompilationUnit = p.Parse(stream, fileName);
// }
// Keep the original text around; we might use it for a refactoring later
this.OriginalText = File.ReadAllText(fileName);
this.SyntaxTree = p.Parse(this.OriginalText, fileName);
if (p.HasErrors) {
Console.WriteLine("Error parsing " + fileName + ":");
foreach (var error in p.ErrorsAndWarnings) {
Console.WriteLine(" " + error.Region + " " + error.Message);
}
}
this.UnresolvedTypeSystemForFile = this.SyntaxTree.ToTypeSystem();
}
public CSharpAstResolver CreateResolver()
{
return new CSharpAstResolver(Project.Compilation, SyntaxTree, UnresolvedTypeSystemForFile);
}
}
}

197
ICSharpCode.NRefactory.ConsistencyCheck/CSharpProject.cs

@ -20,163 +20,128 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Editor;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging;
namespace ICSharpCode.NRefactory.ConsistencyCheck namespace ICSharpCode.NRefactory.ConsistencyCheck
{ {
/// <summary>
/// Represents a C# project (.csproj file)
/// </summary>
public class CSharpProject public class CSharpProject
{ {
/// <summary>
/// Parent solution.
/// </summary>
public readonly Solution Solution; public readonly Solution Solution;
/// <summary>
/// Title is the project name as specified in the .sln file.
/// </summary>
public readonly string Title; public readonly string Title;
/// <summary>
/// Name of the output assembly.
/// </summary>
public readonly string AssemblyName; public readonly string AssemblyName;
/// <summary>
/// Full path to the .csproj file.
/// </summary>
public readonly string FileName; public readonly string FileName;
public readonly List<CSharpFile> Files = new List<CSharpFile>(); public readonly List<CSharpFile> Files = new List<CSharpFile>();
public readonly CompilerSettings CompilerSettings = new CompilerSettings(); public readonly CompilerSettings CompilerSettings = new CompilerSettings();
public IProjectContent ProjectContent; /// <summary>
/// The unresolved type system for this project.
/// </summary>
public readonly IProjectContent ProjectContent;
public ICompilation Compilation { /// <summary>
get { /// The resolved type system for this project.
return Solution.SolutionSnapshot.GetCompilation(ProjectContent); /// This field is initialized once all projects have been loaded (in Solution constructor).
} /// </summary>
} public ICompilation Compilation;
public CSharpProject(Solution solution, string title, string fileName) public CSharpProject(Solution solution, string title, string fileName)
{ {
// Normalize the file name
fileName = Path.GetFullPath(fileName);
this.Solution = solution; this.Solution = solution;
this.Title = title; this.Title = title;
this.FileName = fileName; this.FileName = fileName;
var p = new Microsoft.Build.Evaluation.Project(fileName); // Use MSBuild to open the .csproj
this.AssemblyName = p.GetPropertyValue("AssemblyName"); var msbuildProject = new Microsoft.Build.Evaluation.Project(fileName);
this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false; // Figure out some compiler settings
this.CompilerSettings.CheckForOverflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false; this.AssemblyName = msbuildProject.GetPropertyValue("AssemblyName");
foreach (string symbol in p.GetPropertyValue("DefineConstants").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { this.CompilerSettings.AllowUnsafeBlocks = GetBoolProperty(msbuildProject, "AllowUnsafeBlocks") ?? false;
this.CompilerSettings.CheckForOverflow = GetBoolProperty(msbuildProject, "CheckForOverflowUnderflow") ?? false;
string defineConstants = msbuildProject.GetPropertyValue("DefineConstants");
foreach (string symbol in defineConstants.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim()); this.CompilerSettings.ConditionalSymbols.Add(symbol.Trim());
// Initialize the unresolved type system
IProjectContent pc = new CSharpProjectContent();
pc = pc.SetAssemblyName(this.AssemblyName);
pc = pc.SetProjectFileName(fileName);
pc = pc.SetCompilerSettings(this.CompilerSettings);
// Parse the C# code files
foreach (var item in msbuildProject.GetItems("Compile")) {
var file = new CSharpFile(this, Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude));
Files.Add(file);
} }
foreach (var item in p.GetItems("Compile")) { // Add parsed files to the type system
Files.Add(new CSharpFile(this, Path.Combine(p.DirectoryPath, item.EvaluatedInclude))); pc = pc.AddOrUpdateFiles(Files.Select(f => f.UnresolvedTypeSystemForFile));
}
List<IAssemblyReference> references = new List<IAssemblyReference>(); // Add referenced assemblies:
string mscorlib = FindAssembly(Program.AssemblySearchPaths, "mscorlib"); foreach (string assemblyFile in ResolveAssemblyReferences(msbuildProject)) {
if (mscorlib != null) { IUnresolvedAssembly assembly = solution.LoadAssembly(assemblyFile);
references.Add(Program.LoadAssembly(mscorlib)); pc = pc.AddAssemblyReferences(new [] { assembly });
} else {
Console.WriteLine("Could not find mscorlib");
}
bool hasSystemCore = false;
foreach (var item in p.GetItems("Reference")) {
string assemblyFileName = null;
if (item.HasMetadata("HintPath")) {
assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath"));
if (!File.Exists(assemblyFileName))
assemblyFileName = null;
}
if (assemblyFileName == null) {
assemblyFileName = FindAssembly(Program.AssemblySearchPaths, item.EvaluatedInclude);
}
if (assemblyFileName != null) {
if (Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
hasSystemCore = true;
references.Add(Program.LoadAssembly(assemblyFileName));
} else {
Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
}
} }
if (!hasSystemCore && FindAssembly(Program.AssemblySearchPaths, "System.Core") != null)
references.Add(Program.LoadAssembly(FindAssembly(Program.AssemblySearchPaths, "System.Core"))); // Add project references:
foreach (var item in p.GetItems("ProjectReference")) { foreach (var item in msbuildProject.GetItems("ProjectReference")) {
references.Add(new ProjectReference(solution, item.GetMetadataValue("Name"))); string referencedFileName = Path.Combine(msbuildProject.DirectoryPath, item.EvaluatedInclude);
// Normalize the path; this is required to match the name with the referenced project's file name
referencedFileName = Path.GetFullPath(referencedFileName);
pc = pc.AddAssemblyReferences(new[] { new ProjectReference(referencedFileName) });
} }
this.ProjectContent = new CSharpProjectContent() this.ProjectContent = pc;
.SetAssemblyName(this.AssemblyName)
.SetCompilerSettings(this.CompilerSettings)
.AddAssemblyReferences(references)
.UpdateProjectContent(null, Files.Select(f => f.ParsedFile));
} }
string FindAssembly(IEnumerable<string> assemblySearchPaths, string evaluatedInclude) IEnumerable<string> ResolveAssemblyReferences(Microsoft.Build.Evaluation.Project project)
{ {
if (evaluatedInclude.IndexOf(',') >= 0) // Use MSBuild to figure out the full path of the referenced assemblies
evaluatedInclude = evaluatedInclude.Substring(0, evaluatedInclude.IndexOf(',')); var projectInstance = project.CreateProjectInstance();
foreach (string searchPath in assemblySearchPaths) { projectInstance.SetProperty("BuildingProject", "false");
string assemblyFile = Path.Combine(searchPath, evaluatedInclude + ".dll"); project.SetProperty("DesignTimeBuild", "true");
if (File.Exists(assemblyFile))
return assemblyFile; projectInstance.Build("ResolveAssemblyReferences", new [] { new ConsoleLogger(LoggerVerbosity.Minimal) });
} var items = projectInstance.GetItems("_ResolveAssemblyReferenceResolvedFiles");
return null; string baseDirectory = Path.GetDirectoryName(this.FileName);
return items.Select(i => Path.Combine(baseDirectory, i.GetMetadataValue("Identity")));
} }
static bool? GetBoolProperty(Microsoft.Build.Evaluation.Project p, string propertyName) static bool? GetBoolProperty(Microsoft.Build.Evaluation.Project p, string propertyName)
{ {
string val = p.GetPropertyValue(propertyName); string val = p.GetPropertyValue(propertyName);
if (val.Equals("true", StringComparison.OrdinalIgnoreCase)) bool result;
return true; if (bool.TryParse(val, out result))
if (val.Equals("false", StringComparison.OrdinalIgnoreCase)) return result;
return false; else
return null; return null;
} }
public override string ToString() public override string ToString()
{ {
return string.Format("[CSharpProject AssemblyName={0}]", AssemblyName); return string.Format("[CSharpProject AssemblyName={0}]", AssemblyName);
} }
public CSharpFile GetFile(string fileName)
{
return Files.Single(f => f.FileName == fileName);
}
}
public class ProjectReference : IAssemblyReference
{
readonly Solution solution;
readonly string projectTitle;
public ProjectReference(Solution solution, string projectTitle)
{
this.solution = solution;
this.projectTitle = projectTitle;
}
public IAssembly Resolve(ITypeResolveContext context)
{
var project = solution.Projects.Single(p => string.Equals(p.Title, projectTitle, StringComparison.OrdinalIgnoreCase));
return project.ProjectContent.Resolve(context);
}
}
public class CSharpFile
{
public readonly CSharpProject Project;
public readonly string FileName;
public readonly ITextSource Content;
public readonly int LinesOfCode;
public SyntaxTree SyntaxTree;
public CSharpParsedFile ParsedFile;
public CSharpFile(CSharpProject project, string fileName)
{
this.Project = project;
this.FileName = fileName;
this.Content = new StringTextSource(File.ReadAllText(FileName));
this.LinesOfCode = 1 + this.Content.Text.Count(c => c == '\n');
CSharpParser p = new CSharpParser(project.CompilerSettings);
this.SyntaxTree = p.Parse(Content, fileName);
if (p.HasErrors) {
Console.WriteLine("Error parsing " + fileName + ":");
foreach (var error in p.ErrorsAndWarnings) {
Console.WriteLine(" " + error.Region + " " + error.Message);
}
}
this.ParsedFile = this.SyntaxTree.ToTypeSystem();
}
} }
} }

13
ICSharpCode.NRefactory.ConsistencyCheck/FindReferencesConsistencyCheck.cs

@ -59,8 +59,7 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
} }
} }
); );
var resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.ParsedFile); file.CreateResolver().ApplyNavigator(navigator);
resolver.ApplyNavigator(navigator);
} }
} }
Console.WriteLine("For each entity, find all references..."); Console.WriteLine("For each entity, find all references...");
@ -102,19 +101,19 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
HashSet<AstNode> foundReferences = new HashSet<AstNode>(); HashSet<AstNode> foundReferences = new HashSet<AstNode>();
var interestingFiles = new HashSet<CSharpFile>(); var interestingFiles = new HashSet<CSharpFile>();
foreach (var searchScope in searchScopes) { foreach (var searchScope in searchScopes) {
foreach (var parsedFile in fr.GetInterestingFiles(searchScope, project.Compilation)) { foreach (var unresolvedFile in fr.GetInterestingFiles(searchScope, project.Compilation)) {
var file = project.GetFile(parsedFile.FileName); var file = project.Files.Single(f => f.FileName == unresolvedFile.FileName);
Debug.Assert(file.ParsedFile == parsedFile); Debug.Assert(file.UnresolvedTypeSystemForFile == unresolvedFile);
// Skip file if it doesn't contain the search term // Skip file if it doesn't contain the search term
if (searchScope.SearchTerm != null && file.Content.IndexOf(searchScope.SearchTerm, 0, file.Content.TextLength, StringComparison.Ordinal) < 0) if (searchScope.SearchTerm != null && file.OriginalText.IndexOf(searchScope.SearchTerm, StringComparison.Ordinal) < 0)
continue; continue;
interestingFiles.Add(file); interestingFiles.Add(file);
} }
} }
foreach (var file in interestingFiles) { foreach (var file in interestingFiles) {
fr.FindReferencesInFile(searchScopes, file.ParsedFile, file.SyntaxTree, project.Compilation, fr.FindReferencesInFile(searchScopes, file.UnresolvedTypeSystemForFile, file.SyntaxTree, project.Compilation,
delegate(AstNode node, ResolveResult result) { delegate(AstNode node, ResolveResult result) {
foundReferences.Add(node); foundReferences.Add(node);
}, CancellationToken.None); }, CancellationToken.None);

13
ICSharpCode.NRefactory.ConsistencyCheck/ICSharpCode.NRefactory.ConsistencyCheck.csproj

@ -15,12 +15,12 @@
<NoStdLib>False</NoStdLib> <NoStdLib>False</NoStdLib>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<OutputPath>bin\$(Configuration)\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' "> <PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType> <DebugType>Full</DebugType>
<Optimize>False</Optimize> <Optimize>False</Optimize>
@ -28,9 +28,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath> <DebugType>PdbOnly</DebugType>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
@ -39,7 +37,6 @@
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType> <DebugType>Full</DebugType>
<Optimize>False</Optimize> <Optimize>False</Optimize>
@ -48,9 +45,7 @@
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath> <DebugType>PdbOnly</DebugType>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
@ -58,6 +53,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Build" /> <Reference Include="Microsoft.Build" />
<Reference Include="Microsoft.Build.Framework" />
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core"> <Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework> <RequiredTargetFramework>3.5</RequiredTargetFramework>
@ -75,6 +71,7 @@
<Compile Include="..\ICSharpCode.NRefactory\Properties\GlobalAssemblyInfo.cs"> <Compile Include="..\ICSharpCode.NRefactory\Properties\GlobalAssemblyInfo.cs">
<Link>Properties\GlobalAssemblyInfo.cs</Link> <Link>Properties\GlobalAssemblyInfo.cs</Link>
</Compile> </Compile>
<Compile Include="CSharpFile.cs" />
<Compile Include="CSharpProject.cs" /> <Compile Include="CSharpProject.cs" />
<Compile Include="FindReferencesConsistencyCheck.cs" /> <Compile Include="FindReferencesConsistencyCheck.cs" />
<Compile Include="TypeSystemTests.cs" /> <Compile Include="TypeSystemTests.cs" />

6
ICSharpCode.NRefactory.ConsistencyCheck/Program.cs

@ -52,8 +52,8 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
} }
Console.WriteLine("Loaded {0} lines of code ({1:f1} MB) in {2} files in {3} projects.", Console.WriteLine("Loaded {0} lines of code ({1:f1} MB) in {2} files in {3} projects.",
solution.AllFiles.Sum(f => f.LinesOfCode), solution.AllFiles.Sum(f => 1 + f.OriginalText.Count(c => c == '\n')),
solution.AllFiles.Sum(f => f.Content.TextLength) / 1024.0 / 1024.0, solution.AllFiles.Sum(f => f.OriginalText.Length) / 1024.0 / 1024.0,
solution.AllFiles.Count(), solution.AllFiles.Count(),
solution.Projects.Count); solution.Projects.Count);
@ -63,7 +63,7 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
using (new Timer("Resolve unresolved members... ")) TypeSystemTests.ResolvedUnresolvedMembers(solution); using (new Timer("Resolve unresolved members... ")) TypeSystemTests.ResolvedUnresolvedMembers(solution);
//RunTestOnAllFiles("Roundtripping test", RoundtripTest.RunTest); //RunTestOnAllFiles("Roundtripping test", RoundtripTest.RunTest);
RunTestOnAllFiles("Resolver test", ResolverTest.RunTest); RunTestOnAllFiles("Resolver test", ResolverTest.RunTest);
RunTestOnAllFiles("Resolver test (no parsed file)", ResolverTest.RunTestWithoutParsedFile); RunTestOnAllFiles("Resolver test (no parsed file)", ResolverTest.RunTestWithoutUnresolvedFile);
RunTestOnAllFiles("Resolver test (randomized order)", RandomizedOrderResolverTest.RunTest); RunTestOnAllFiles("Resolver test (randomized order)", RandomizedOrderResolverTest.RunTest);
new FindReferencesConsistencyCheck(solution).Run(); new FindReferencesConsistencyCheck(solution).Run();

4
ICSharpCode.NRefactory.ConsistencyCheck/RandomizedOrderResolverTest.cs

@ -45,9 +45,9 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
Random rnd = new Random(seed); Random rnd = new Random(seed);
var test = new RandomizedOrderResolverTest(); var test = new RandomizedOrderResolverTest();
// Resolve all nodes, but in a random order without using a navigator. // Resolve all nodes, but in a random order without using a navigator.
test.resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.ParsedFile); test.resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);
// For comparing whether the results are equivalent, we also use a normal 'resolve all' resolver: // For comparing whether the results are equivalent, we also use a normal 'resolve all' resolver:
test.resolveAllResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.ParsedFile); test.resolveAllResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);
test.resolveAllResolver.ApplyNavigator(new ResolveAllNavigator(), CancellationToken.None); test.resolveAllResolver.ApplyNavigator(new ResolveAllNavigator(), CancellationToken.None);
// Prepare list of actions that we need to verify: // Prepare list of actions that we need to verify:
var actions = new List<Func<bool>>(); var actions = new List<Func<bool>>();

8
ICSharpCode.NRefactory.ConsistencyCheck/ResolverTest.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
{ {
public static void RunTest(CSharpFile file) public static void RunTest(CSharpFile file)
{ {
CSharpAstResolver resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.ParsedFile); CSharpAstResolver resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);
var navigator = new ValidatingResolveAllNavigator(file.FileName); var navigator = new ValidatingResolveAllNavigator(file.FileName);
resolver.ApplyNavigator(navigator, CancellationToken.None); resolver.ApplyNavigator(navigator, CancellationToken.None);
navigator.Validate(resolver, file.SyntaxTree); navigator.Validate(resolver, file.SyntaxTree);
@ -102,19 +102,19 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
} }
} }
public static void RunTestWithoutParsedFile(CSharpFile file) public static void RunTestWithoutUnresolvedFile(CSharpFile file)
{ {
CSharpAstResolver resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree); CSharpAstResolver resolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree);
var navigator = new ValidatingResolveAllNavigator(file.FileName); var navigator = new ValidatingResolveAllNavigator(file.FileName);
resolver.ApplyNavigator(navigator, CancellationToken.None); resolver.ApplyNavigator(navigator, CancellationToken.None);
navigator.Validate(resolver, file.SyntaxTree); navigator.Validate(resolver, file.SyntaxTree);
CSharpAstResolver originalResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.ParsedFile); CSharpAstResolver originalResolver = new CSharpAstResolver(file.Project.Compilation, file.SyntaxTree, file.UnresolvedTypeSystemForFile);
foreach (var node in file.SyntaxTree.DescendantsAndSelf) { foreach (var node in file.SyntaxTree.DescendantsAndSelf) {
var originalResult = originalResolver.Resolve(node); var originalResult = originalResolver.Resolve(node);
var result = resolver.Resolve(node); var result = resolver.Resolve(node);
if (!RandomizedOrderResolverTest.IsEqualResolveResult(result, originalResult)) { if (!RandomizedOrderResolverTest.IsEqualResolveResult(result, originalResult)) {
Console.WriteLine("Got different without IParsedFile at " + file.FileName + ":" + node.StartLocation); Console.WriteLine("Got different without IUnresolvedFile at " + file.FileName + ":" + node.StartLocation);
} }
} }
} }

2
ICSharpCode.NRefactory.ConsistencyCheck/RoundtripTest.cs

@ -34,7 +34,7 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
{ {
public static void RunTest(CSharpFile file) public static void RunTest(CSharpFile file)
{ {
string code = file.Content.Text.Replace("\r\n", "\n"); string code = file.OriginalText.Replace("\r\n", "\n");
Debug.Assert(code.IndexOf('\r') < 0); Debug.Assert(code.IndexOf('\r') < 0);
if (code.Contains("#pragma")) if (code.Contains("#pragma"))
return; // skip code with preprocessor directives return; // skip code with preprocessor directives

23
ICSharpCode.NRefactory.ConsistencyCheck/Solution.cs

@ -17,12 +17,14 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using ICSharpCode.NRefactory.TypeSystem; using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation; using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.ConsistencyCheck namespace ICSharpCode.NRefactory.ConsistencyCheck
{ {
@ -62,6 +64,25 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
} }
} }
} }
// Create compilations (resolved type systems) after all projects have been loaded.
// (we can't do this earlier because project A might have a reference to project B, where A is loaded before B)
// To allow NRefactory to resolve project references, we need to use a 'DefaultSolutionSnapshot'
// instead of calling CreateCompilation() on each project individually.
var solutionSnapshot = new DefaultSolutionSnapshot(this.Projects.Select(p => p.ProjectContent));
foreach (CSharpProject project in this.Projects) {
project.Compilation = solutionSnapshot.GetCompilation(project.ProjectContent);
}
}
ConcurrentDictionary<string, IUnresolvedAssembly> assemblyDict = new ConcurrentDictionary<string, IUnresolvedAssembly>(Platform.FileNameComparer);
/// <summary>
/// Loads a referenced assembly from a .dll.
/// Returns the existing instance if the assembly was already loaded.
/// </summary>
public IUnresolvedAssembly LoadAssembly(string assemblyFileName)
{
return assemblyDict.GetOrAdd(assemblyFileName, file => new CecilLoader().LoadAssemblyFile(file));
} }
} }
} }

5
ICSharpCode.NRefactory.ConsistencyCheck/VisitorBenchmark.cs

@ -50,11 +50,6 @@ namespace ICSharpCode.NRefactory.ConsistencyCheck
visitor.EnterIdentifierExpression += list.Add; visitor.EnterIdentifierExpression += list.Add;
syntaxTree.AcceptVisitor(visitor); syntaxTree.AcceptVisitor(visitor);
}); });
RunTest("ObservableAstVisitor<object, object>", files, (syntaxTree, list) => {
var visitor = new ObservableAstVisitor<object, object>();
visitor.IdentifierExpressionVisited += (id, data) => list.Add(id);
syntaxTree.AcceptVisitor(visitor, null);
});
} }
static void WalkTreeForEach(AstNode node, List<IdentifierExpression> list) static void WalkTreeForEach(AstNode node, List<IdentifierExpression> list)

3
ICSharpCode.NRefactory.Demo/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

16
ICSharpCode.NRefactory.Demo/CSDemo.cs

@ -204,8 +204,8 @@ namespace ICSharpCode.NRefactory.Demo
void ResolveButtonClick(object sender, EventArgs e) void ResolveButtonClick(object sender, EventArgs e)
{ {
IProjectContent project = new CSharpProjectContent(); IProjectContent project = new CSharpProjectContent();
var parsedFile = syntaxTree.ToTypeSystem(); var unresolvedFile = syntaxTree.ToTypeSystem();
project = project.UpdateProjectContent(null, parsedFile); project = project.AddOrUpdateFiles(unresolvedFile);
project = project.AddAssemblyReferences(builtInLibs.Value); project = project.AddAssemblyReferences(builtInLibs.Value);
ICompilation compilation = project.CreateCompilation(); ICompilation compilation = project.CreateCompilation();
@ -213,12 +213,12 @@ namespace ICSharpCode.NRefactory.Demo
ResolveResult result; ResolveResult result;
if (csharpTreeView.SelectedNode != null) { if (csharpTreeView.SelectedNode != null) {
var selectedNode = (AstNode)csharpTreeView.SelectedNode.Tag; var selectedNode = (AstNode)csharpTreeView.SelectedNode.Tag;
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, parsedFile); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
result = resolver.Resolve(selectedNode); result = resolver.Resolve(selectedNode);
// CSharpAstResolver.Resolve() never returns null // CSharpAstResolver.Resolve() never returns null
} else { } else {
TextLocation location = GetTextLocation(csharpCodeTextBox, csharpCodeTextBox.SelectionStart); TextLocation location = GetTextLocation(csharpCodeTextBox, csharpCodeTextBox.SelectionStart);
result = ResolveAtLocation.Resolve(compilation, parsedFile, syntaxTree, location); result = ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, location);
if (result == null) { if (result == null) {
MessageBox.Show("Could not find a resolvable node at the caret location."); MessageBox.Show("Could not find a resolvable node at the caret location.");
return; return;
@ -248,12 +248,12 @@ namespace ICSharpCode.NRefactory.Demo
return; return;
IProjectContent project = new CSharpProjectContent(); IProjectContent project = new CSharpProjectContent();
var parsedFile = syntaxTree.ToTypeSystem(); var unresolvedFile = syntaxTree.ToTypeSystem();
project = project.UpdateProjectContent(null, parsedFile); project = project.AddOrUpdateFiles(unresolvedFile);
project = project.AddAssemblyReferences(builtInLibs.Value); project = project.AddAssemblyReferences(builtInLibs.Value);
ICompilation compilation = project.CreateCompilation(); ICompilation compilation = project.CreateCompilation();
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, parsedFile); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag; AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag;
IEntity entity; IEntity entity;
@ -276,7 +276,7 @@ namespace ICSharpCode.NRefactory.Demo
var searchScopes = fr.GetSearchScopes(entity); var searchScopes = fr.GetSearchScopes(entity);
Debug.WriteLine("Find references to " + entity.ReflectionName); Debug.WriteLine("Find references to " + entity.ReflectionName);
fr.FindReferencesInFile(searchScopes, parsedFile, syntaxTree, compilation, callback, CancellationToken.None); fr.FindReferencesInFile(searchScopes, unresolvedFile, syntaxTree, compilation, callback, CancellationToken.None);
MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName); MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName);
} }

15
ICSharpCode.NRefactory.Demo/ICSharpCode.NRefactory.Demo.csproj

@ -10,12 +10,12 @@
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<ProductVersion>10.0.0</ProductVersion> <ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<OutputPath>..\bin\$(Configuration)\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' "> <PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>True</DebugSymbols> <DebugSymbols>True</DebugSymbols>
<DebugType>Full</DebugType> <DebugType>Full</DebugType>
<Optimize>False</Optimize> <Optimize>False</Optimize>
@ -23,9 +23,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath> <DebugType>PdbOnly</DebugType>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
@ -46,13 +44,12 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>True</DebugSymbols> <DebugSymbols>True</DebugSymbols>
<DebugType>Full</DebugType> <DebugType>Full</DebugType>
<Optimize>False</Optimize> <Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|x86' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|x86' ">
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
@ -61,13 +58,11 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath> <DebugType>PdbOnly</DebugType>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|x86' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|x86' ">
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>

3
ICSharpCode.NRefactory.GtkDemo/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

6
ICSharpCode.NRefactory.GtkDemo/MainWindow.cs

@ -223,14 +223,14 @@ namespace ICSharpCode.NRefactory.GtkDemo
var parser = new CSharpParser (); var parser = new CSharpParser ();
var unit = parser.Parse (textview1.Buffer.Text, "dummy.cs"); var unit = parser.Parse (textview1.Buffer.Text, "dummy.cs");
var parsedFile = unit.ToTypeSystem(); var unresolvedFile = unit.ToTypeSystem();
IProjectContent project = new CSharpProjectContent (); IProjectContent project = new CSharpProjectContent ();
project = project.UpdateProjectContent (null, parsedFile); project = project.AddOrUpdateFiles (unresolvedFile);
project = project.AddAssemblyReferences (builtInLibs.Value); project = project.AddAssemblyReferences (builtInLibs.Value);
CSharpAstResolver resolver = new CSharpAstResolver(project.CreateCompilation (), unit, parsedFile); CSharpAstResolver resolver = new CSharpAstResolver(project.CreateCompilation (), unit, unresolvedFile);
ShowUnit (unit, resolver); ShowUnit (unit, resolver);
} }

3
ICSharpCode.NRefactory.Tests/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

12
ICSharpCode.NRefactory.Tests/CSharp/CodeActions/TestRefactoringContext.cs

@ -158,7 +158,7 @@ namespace ICSharpCode.NRefactory.CSharp.CodeActions
{ {
FindReferences refFinder = new FindReferences (); FindReferences refFinder = new FindReferences ();
refFinder.FindReferencesInFile (refFinder.GetSearchScopes (entity), refFinder.FindReferencesInFile (refFinder.GetSearchScopes (entity),
context.ParsedFile, context.UnresolvedFile,
context.RootNode as SyntaxTree, context.RootNode as SyntaxTree,
context.Compilation, (n, r) => Rename (n, name), context.Compilation, (n, r) => Rename (n, name),
context.CancellationToken); context.CancellationToken);
@ -168,7 +168,7 @@ namespace ICSharpCode.NRefactory.CSharp.CodeActions
{ {
FindReferences refFinder = new FindReferences (); FindReferences refFinder = new FindReferences ();
refFinder.FindLocalReferences (variable, refFinder.FindLocalReferences (variable,
context.ParsedFile, context.UnresolvedFile,
context.RootNode as SyntaxTree, context.RootNode as SyntaxTree,
context.Compilation, (n, r) => Rename (n, name), context.Compilation, (n, r) => Rename (n, name),
context.CancellationToken); context.CancellationToken);
@ -178,7 +178,7 @@ namespace ICSharpCode.NRefactory.CSharp.CodeActions
{ {
FindReferences refFinder = new FindReferences (); FindReferences refFinder = new FindReferences ();
refFinder.FindTypeParameterReferences (type, refFinder.FindTypeParameterReferences (type,
context.ParsedFile, context.UnresolvedFile,
context.RootNode as SyntaxTree, context.RootNode as SyntaxTree,
context.Compilation, (n, r) => Rename (n, name), context.Compilation, (n, r) => Rename (n, name),
context.CancellationToken); context.CancellationToken);
@ -264,14 +264,14 @@ namespace ICSharpCode.NRefactory.CSharp.CodeActions
} }
unit.Freeze (); unit.Freeze ();
var parsedFile = unit.ToTypeSystem (); var unresolvedFile = unit.ToTypeSystem ();
IProjectContent pc = new CSharpProjectContent (); IProjectContent pc = new CSharpProjectContent ();
pc = pc.UpdateProjectContent (null, parsedFile); pc = pc.AddOrUpdateFiles (unresolvedFile);
pc = pc.AddAssemblyReferences (new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); pc = pc.AddAssemblyReferences (new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
var compilation = pc.CreateCompilation (); var compilation = pc.CreateCompilation ();
var resolver = new CSharpAstResolver (compilation, unit, parsedFile); var resolver = new CSharpAstResolver (compilation, unit, unresolvedFile);
TextLocation location = TextLocation.Empty; TextLocation location = TextLocation.Empty;
if (idx >= 0) if (idx >= 0)
location = doc.GetLocation (idx); location = doc.GetLocation (idx);

16
ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/CodeCompletionBugTests.cs

@ -225,16 +225,16 @@ namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs"); var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze(); syntaxTree.Freeze();
var parsedFile = syntaxTree.ToTypeSystem(); var unresolvedFile = syntaxTree.ToTypeSystem();
pctx = pctx.UpdateProjectContent(null, parsedFile); pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation(); var cmp = pctx.CreateCompilation();
var loc = cursorPosition > 0 ? doc.GetLocation(cursorPosition) : new TextLocation (1, 1); var loc = cursorPosition > 0 ? doc.GetLocation(cursorPosition) : new TextLocation (1, 1);
var rctx = new CSharpTypeResolveContext(cmp.MainAssembly); var rctx = new CSharpTypeResolveContext(cmp.MainAssembly);
rctx = rctx.WithUsingScope(parsedFile.GetUsingScope(loc).Resolve(cmp)); rctx = rctx.WithUsingScope(unresolvedFile.GetUsingScope(loc).Resolve(cmp));
var curDef = parsedFile.GetInnermostTypeDefinition(loc); var curDef = unresolvedFile.GetInnermostTypeDefinition(loc);
if (curDef != null) { if (curDef != null) {
var resolvedDef = curDef.Resolve(rctx).GetDefinition(); var resolvedDef = curDef.Resolve(rctx).GetDefinition();
rctx = rctx.WithCurrentTypeDefinition(resolvedDef); rctx = rctx.WithCurrentTypeDefinition(resolvedDef);
@ -243,7 +243,7 @@ namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
rctx = rctx.WithCurrentMember(curMember); rctx = rctx.WithCurrentMember(curMember);
} }
} }
var mb = new DefaultCompletionContextProvider(doc, parsedFile); var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var engine = new CSharpCompletionEngine(doc, mb, new TestFactory(), pctx, rctx); var engine = new CSharpCompletionEngine(doc, mb, new TestFactory(), pctx, rctx);
engine.EolMarker = Environment.NewLine; engine.EolMarker = Environment.NewLine;
@ -270,12 +270,12 @@ namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
var doc = new ReadOnlyDocument(text); var doc = new ReadOnlyDocument(text);
IProjectContent pctx = new CSharpProjectContent(); IProjectContent pctx = new CSharpProjectContent();
pctx = pctx.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); pctx = pctx.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
var parsedFile = syntaxTree.ToTypeSystem(); var unresolvedFile = syntaxTree.ToTypeSystem();
pctx = pctx.UpdateProjectContent(null, parsedFile); pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation(); var cmp = pctx.CreateCompilation();
var mb = new DefaultCompletionContextProvider(doc, parsedFile); var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var engine = new CSharpCompletionEngine (doc, mb, new TestFactory (), pctx, new CSharpTypeResolveContext (cmp.MainAssembly)); var engine = new CSharpCompletionEngine (doc, mb, new TestFactory (), pctx, new CSharpTypeResolveContext (cmp.MainAssembly));
engine.EolMarker = Environment.NewLine; engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono (); engine.FormattingPolicy = FormattingOptionsFactory.CreateMono ();

12
ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/ParameterCompletionTests.cs

@ -275,23 +275,23 @@ namespace ICSharpCode.NRefactory.CSharp.CodeCompletion
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs"); var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze(); syntaxTree.Freeze();
var parsedFile = syntaxTree.ToTypeSystem(); var unresolvedFile = syntaxTree.ToTypeSystem();
pctx = pctx.UpdateProjectContent(null, parsedFile); pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation(); var cmp = pctx.CreateCompilation();
var loc = doc.GetLocation(cursorPosition); var loc = doc.GetLocation(cursorPosition);
var rctx = new CSharpTypeResolveContext(cmp.MainAssembly); var rctx = new CSharpTypeResolveContext(cmp.MainAssembly);
rctx = rctx.WithUsingScope(parsedFile.GetUsingScope(loc).Resolve(cmp)); rctx = rctx.WithUsingScope(unresolvedFile.GetUsingScope(loc).Resolve(cmp));
var curDef = parsedFile.GetInnermostTypeDefinition(loc); var curDef = unresolvedFile.GetInnermostTypeDefinition(loc);
if (curDef != null) { if (curDef != null) {
rctx = rctx.WithCurrentTypeDefinition(curDef.Resolve(rctx).GetDefinition()); rctx = rctx.WithCurrentTypeDefinition(curDef.Resolve(rctx).GetDefinition());
var curMember = parsedFile.GetMember(loc); var curMember = unresolvedFile.GetMember(loc);
if (curMember != null) { if (curMember != null) {
rctx = rctx.WithCurrentMember(curMember.CreateResolved(rctx)); rctx = rctx.WithCurrentMember(curMember.CreateResolved(rctx));
} }
} }
var mb = new DefaultCompletionContextProvider(doc, parsedFile); var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var engine = new CSharpParameterCompletionEngine (doc, mb, new TestFactory (pctx), pctx, rctx); var engine = new CSharpParameterCompletionEngine (doc, mb, new TestFactory (pctx), pctx, rctx);
return engine.GetParameterDataProvider (cursorPosition, doc.GetCharAt (cursorPosition - 1)); return engine.GetParameterDataProvider (cursorPosition, doc.GetCharAt (cursorPosition - 1));
} }

12
ICSharpCode.NRefactory.Tests/CSharp/CodeDomConvertVisitorTests.cs

@ -34,15 +34,15 @@ namespace ICSharpCode.NRefactory.CSharp
public class CodeDomConvertVisitorTests : ResolverTestBase public class CodeDomConvertVisitorTests : ResolverTestBase
{ {
CodeDomConvertVisitor convertVisitor; CodeDomConvertVisitor convertVisitor;
CSharpParsedFile parsedFile; CSharpUnresolvedFile unresolvedFile;
public override void SetUp() public override void SetUp()
{ {
base.SetUp(); base.SetUp();
parsedFile = new CSharpParsedFile("test.cs"); unresolvedFile = new CSharpUnresolvedFile("test.cs");
parsedFile.RootUsingScope.Usings.Add(MakeReference("System")); unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System"));
parsedFile.RootUsingScope.Usings.Add(MakeReference("System.Collections.Generic")); unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System.Collections.Generic"));
parsedFile.RootUsingScope.Usings.Add(MakeReference("System.Linq")); unresolvedFile.RootUsingScope.Usings.Add(MakeReference("System.Linq"));
convertVisitor = new CodeDomConvertVisitor(); convertVisitor = new CodeDomConvertVisitor();
convertVisitor.AllowSnippetNodes = false; convertVisitor.AllowSnippetNodes = false;
@ -53,7 +53,7 @@ namespace ICSharpCode.NRefactory.CSharp
string ConvertHelper(AstNode node, Action<CSharpCodeProvider, CodeObject, TextWriter, CodeGeneratorOptions> action) string ConvertHelper(AstNode node, Action<CSharpCodeProvider, CodeObject, TextWriter, CodeGeneratorOptions> action)
{ {
CSharpResolver resolver = new CSharpResolver(compilation); CSharpResolver resolver = new CSharpResolver(compilation);
resolver = resolver.WithCurrentUsingScope(parsedFile.RootUsingScope.Resolve(compilation)); resolver = resolver.WithCurrentUsingScope(unresolvedFile.RootUsingScope.Resolve(compilation));
resolver = resolver.WithCurrentTypeDefinition(compilation.FindType(KnownTypeCode.Object).GetDefinition()); resolver = resolver.WithCurrentTypeDefinition(compilation.FindType(KnownTypeCode.Object).GetDefinition());
var codeObj = convertVisitor.Convert(node, new CSharpAstResolver(resolver, node)); var codeObj = convertVisitor.Convert(node, new CSharpAstResolver(resolver, node));

12
ICSharpCode.NRefactory.Tests/CSharp/Parser/ParseSelfTests.cs

@ -37,7 +37,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
[TestFixtureSetUp] [TestFixtureSetUp]
public void SetUp() public void SetUp()
{ {
string path = Path.GetFullPath (Path.Combine ("..", "..", "..")); string path = Path.GetFullPath (Path.Combine ("..", ".."));
if (!File.Exists(Path.Combine(path, "NRefactory.sln"))) if (!File.Exists(Path.Combine(path, "NRefactory.sln")))
throw new InvalidOperationException("Test cannot find the NRefactory source code in " + path); throw new InvalidOperationException("Test cannot find the NRefactory source code in " + path);
fileNames = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories); fileNames = Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories);
@ -54,15 +54,15 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) { using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
syntaxTree = parser.Parse(fs, fileName); syntaxTree = parser.Parse(fs, fileName);
} }
var parsedFile = syntaxTree.ToTypeSystem(); var unresolvedFile = syntaxTree.ToTypeSystem();
foreach (var td in parsedFile.GetAllTypeDefinitions()) { foreach (var td in unresolvedFile.GetAllTypeDefinitions()) {
Assert.AreSame(parsedFile, td.ParsedFile); Assert.AreSame(unresolvedFile, td.UnresolvedFile);
foreach (var member in td.Members) { foreach (var member in td.Members) {
Assert.AreSame(parsedFile, member.ParsedFile); Assert.AreSame(unresolvedFile, member.UnresolvedFile);
Assert.AreSame(td, member.DeclaringTypeDefinition); Assert.AreSame(td, member.DeclaringTypeDefinition);
} }
} }
pc = pc.UpdateProjectContent(null, parsedFile); pc = pc.AddOrUpdateFiles(unresolvedFile);
} }
} }

4
ICSharpCode.NRefactory.Tests/CSharp/Parser/TypeSystemConvertVisitorTests.cs

@ -47,9 +47,9 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
syntaxTree = parser.Parse(s, fileName); syntaxTree = parser.Parse(s, fileName);
} }
var parsedFile = syntaxTree.ToTypeSystem(); var unresolvedFile = syntaxTree.ToTypeSystem();
return new CSharpProjectContent() return new CSharpProjectContent()
.UpdateProjectContent(null, parsedFile) .AddOrUpdateFiles(unresolvedFile)
.AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }) .AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib })
.SetAssemblyName(typeof(TypeSystemTests).Assembly.GetName().Name); .SetAssemblyName(typeof(TypeSystemTests).Assembly.GetName().Name);
} }

8
ICSharpCode.NRefactory.Tests/CSharp/Refactoring/TypeSystemAstBuilderTests.cs

@ -56,15 +56,15 @@ namespace OtherNS {
IProjectContent pc; IProjectContent pc;
ICompilation compilation; ICompilation compilation;
ITypeDefinition baseClass, derivedClass, nestedClass, systemClass; ITypeDefinition baseClass, derivedClass, nestedClass, systemClass;
CSharpParsedFile parsedFile; CSharpUnresolvedFile unresolvedFile;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
pc = new CSharpProjectContent(); pc = new CSharpProjectContent();
pc = pc.SetAssemblyName("MyAssembly"); pc = pc.SetAssemblyName("MyAssembly");
parsedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem(); unresolvedFile = SyntaxTree.Parse(program, "program.cs").ToTypeSystem();
pc = pc.UpdateProjectContent(null, parsedFile); pc = pc.AddOrUpdateFiles(unresolvedFile);
pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib }); pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib });
compilation = pc.CreateCompilation(); compilation = pc.CreateCompilation();
@ -77,7 +77,7 @@ namespace OtherNS {
TypeSystemAstBuilder CreateBuilder(ITypeDefinition currentTypeDef = null) TypeSystemAstBuilder CreateBuilder(ITypeDefinition currentTypeDef = null)
{ {
UsingScope usingScope = currentTypeDef != null ? parsedFile.GetUsingScope(currentTypeDef.Region.Begin) : parsedFile.RootUsingScope; UsingScope usingScope = currentTypeDef != null ? unresolvedFile.GetUsingScope(currentTypeDef.Region.Begin) : unresolvedFile.RootUsingScope;
return new TypeSystemAstBuilder(new CSharpResolver( return new TypeSystemAstBuilder(new CSharpResolver(
new CSharpTypeResolveContext(compilation.MainAssembly, usingScope.Resolve(compilation), currentTypeDef))); new CSharpTypeResolveContext(compilation.MainAssembly, usingScope.Resolve(compilation), currentTypeDef)));
} }

1
ICSharpCode.NRefactory.Tests/CSharp/Resolver/ExplicitConversionsTest.cs

@ -194,6 +194,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
Assert.AreEqual(C.ExplicitReferenceConversion, ExplicitConversion(typeof(object[]), typeof(string[]))); Assert.AreEqual(C.ExplicitReferenceConversion, ExplicitConversion(typeof(object[]), typeof(string[])));
Assert.AreEqual(C.ExplicitReferenceConversion, ExplicitConversion(typeof(dynamic[]), typeof(string[]))); Assert.AreEqual(C.ExplicitReferenceConversion, ExplicitConversion(typeof(dynamic[]), typeof(string[])));
Assert.AreEqual(C.None, ExplicitConversion(typeof(object[]), typeof(object[,])));
Assert.AreEqual(C.None, ExplicitConversion(typeof(object[]), typeof(int[]))); Assert.AreEqual(C.None, ExplicitConversion(typeof(object[]), typeof(int[])));
Assert.AreEqual(C.None, ExplicitConversion(typeof(short[]), typeof(int[]))); Assert.AreEqual(C.None, ExplicitConversion(typeof(short[]), typeof(int[])));
Assert.AreEqual(C.ExplicitReferenceConversion, ExplicitConversion(typeof(Array), typeof(int[]))); Assert.AreEqual(C.ExplicitReferenceConversion, ExplicitConversion(typeof(Array), typeof(int[])));

8
ICSharpCode.NRefactory.Tests/CSharp/Resolver/FindReferencesTest.cs

@ -31,15 +31,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public class FindReferencesTest public class FindReferencesTest
{ {
SyntaxTree syntaxTree; SyntaxTree syntaxTree;
CSharpParsedFile parsedFile; CSharpUnresolvedFile unresolvedFile;
ICompilation compilation; ICompilation compilation;
FindReferences findReferences; FindReferences findReferences;
void Init(string code) void Init(string code)
{ {
syntaxTree = SyntaxTree.Parse(code, "test.cs"); syntaxTree = SyntaxTree.Parse(code, "test.cs");
parsedFile = syntaxTree.ToTypeSystem(); unresolvedFile = syntaxTree.ToTypeSystem();
compilation = TypeSystemHelper.CreateCompilation(parsedFile); compilation = TypeSystemHelper.CreateCompilation(unresolvedFile);
findReferences = new FindReferences(); findReferences = new FindReferences();
} }
@ -47,7 +47,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{ {
var result = new List<AstNode>(); var result = new List<AstNode>();
var searchScopes = findReferences.GetSearchScopes(entity); var searchScopes = findReferences.GetSearchScopes(entity);
findReferences.FindReferencesInFile(searchScopes, parsedFile, syntaxTree, compilation, findReferences.FindReferencesInFile(searchScopes, unresolvedFile, syntaxTree, compilation,
(node, rr) => result.Add(node), CancellationToken.None); (node, rr) => result.Add(node), CancellationToken.None);
return result.OrderBy(n => n.StartLocation).ToArray(); return result.OrderBy(n => n.StartLocation).ToArray();
} }

28
ICSharpCode.NRefactory.Tests/CSharp/Resolver/InvocationTests.cs

@ -598,7 +598,7 @@ class Test {
[Test] [Test]
public void NamedArgumentInMissingMethod() public void NamedArgumentInMissingMethod()
{ {
string program = @" string program = @"
class Test { class Test {
public void Test() { public void Test() {
Missing($x: 0$); Missing($x: 0$);
@ -609,5 +609,31 @@ class Test {
Assert.AreEqual("x", narr.ParameterName); Assert.AreEqual("x", narr.ParameterName);
Assert.IsNull(narr.Parameter); Assert.IsNull(narr.Parameter);
} }
[Test]
public void GenericMethodInvocationWithConstraintMismatch()
{
string program = @"
interface IA
{
}
class Test
{
void F()
{
string o = null;
$M(o)$;
}
void M<T>(T arg) where T : IA
{
}
void M(object arg) {
}
}";
var rr = Resolve<CSharpInvocationResolveResult>(program);
Assert.AreEqual(OverloadResolutionErrors.MethodConstraintsNotSatisfied, rr.OverloadResolutionErrors);
Assert.IsTrue(rr.IsError);
}
} }
} }

20
ICSharpCode.NRefactory.Tests/CSharp/Resolver/MemberLookupTests.cs

@ -38,13 +38,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
lookup = new MemberLookup(null, compilation.MainAssembly); lookup = new MemberLookup(null, compilation.MainAssembly);
} }
CSharpParsedFile Parse(string program) CSharpUnresolvedFile Parse(string program)
{ {
SyntaxTree syntaxTree = SyntaxTree.Parse(program, "test.cs"); SyntaxTree syntaxTree = SyntaxTree.Parse(program, "test.cs");
CSharpParsedFile parsedFile = syntaxTree.ToTypeSystem(); CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem();
project = project.UpdateProjectContent(null, parsedFile); project = project.AddOrUpdateFiles(unresolvedFile);
compilation = project.CreateCompilation(); compilation = project.CreateCompilation();
return parsedFile; return unresolvedFile;
} }
[Test] [Test]
@ -60,8 +60,8 @@ class Middle : Base {
class Derived : Middle { class Derived : Middle {
public override void Method() {} public override void Method() {}
}"; }";
var parsedFile = Parse(program); var unresolvedFile = Parse(program);
ITypeDefinition derived = compilation.MainAssembly.GetTypeDefinition(parsedFile.TopLevelTypeDefinitions[2]); ITypeDefinition derived = compilation.MainAssembly.GetTypeDefinition(unresolvedFile.TopLevelTypeDefinitions[2]);
var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult; var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
Assert.AreEqual(2, rr.MethodsGroupedByDeclaringType.Count()); Assert.AreEqual(2, rr.MethodsGroupedByDeclaringType.Count());
@ -87,8 +87,8 @@ class Derived : Base<int> {
public override void Method(int a) {} public override void Method(int a) {}
public override void Method(string a) {} public override void Method(string a) {}
}"; }";
var parsedFile = Parse(program); var unresolvedFile = Parse(program);
ITypeDefinition derived = compilation.MainAssembly.GetTypeDefinition(parsedFile.TopLevelTypeDefinitions[1]); ITypeDefinition derived = compilation.MainAssembly.GetTypeDefinition(unresolvedFile.TopLevelTypeDefinitions[1]);
var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult; var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
Assert.AreEqual(2, rr.MethodsGroupedByDeclaringType.Count()); Assert.AreEqual(2, rr.MethodsGroupedByDeclaringType.Count());
@ -115,8 +115,8 @@ class Base {
class Derived : Base { class Derived : Base {
public override void Method<S>(S a) {} public override void Method<S>(S a) {}
}"; }";
var parsedFile = Parse(program); var unresolvedFile = Parse(program);
ITypeDefinition derived = compilation.MainAssembly.GetTypeDefinition(parsedFile.TopLevelTypeDefinitions[1]); ITypeDefinition derived = compilation.MainAssembly.GetTypeDefinition(unresolvedFile.TopLevelTypeDefinitions[1]);
var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult; var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
Assert.AreEqual(1, rr.MethodsGroupedByDeclaringType.Count()); Assert.AreEqual(1, rr.MethodsGroupedByDeclaringType.Count());

12
ICSharpCode.NRefactory.Tests/CSharp/Resolver/ResolverTestBase.cs

@ -168,11 +168,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
SetUp(); SetUp();
CSharpParsedFile parsedFile = syntaxTree.ToTypeSystem(); CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem();
project = project.UpdateProjectContent(null, parsedFile); project = project.AddOrUpdateFiles(unresolvedFile);
compilation = project.CreateCompilation(); compilation = project.CreateCompilation();
CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, parsedFile); CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
return Tuple.Create(resolver, FindNode(syntaxTree, dollars[0], dollars[1])); return Tuple.Create(resolver, FindNode(syntaxTree, dollars[0], dollars[1]));
} }
@ -253,11 +253,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
SetUp(); SetUp();
CSharpParsedFile parsedFile = syntaxTree.ToTypeSystem(); CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem();
project = project.UpdateProjectContent(null, parsedFile); project = project.AddOrUpdateFiles(unresolvedFile);
compilation = project.CreateCompilation(); compilation = project.CreateCompilation();
ResolveResult rr = Resolver.ResolveAtLocation.Resolve(compilation, parsedFile, syntaxTree, dollars[0]); ResolveResult rr = Resolver.ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, dollars[0]);
return rr; return rr;
} }

2
ICSharpCode.NRefactory.Tests/Documentation/CSharpCrefLookupTests.cs

@ -56,7 +56,7 @@ class Impl<T> : IGeneric<List<string>[,], T> {
var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
var syntaxTree = SyntaxTree.Parse(program, "program.cs"); var syntaxTree = SyntaxTree.Parse(program, "program.cs");
var compilation = pc.UpdateProjectContent(null, syntaxTree.ToTypeSystem()).CreateCompilation(); var compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation();
var typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.First(); var typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.First();
IEntity entity = typeDefinition.Documentation.ResolveCref(cref); IEntity entity = typeDefinition.Documentation.ResolveCref(cref);
Assert.IsNotNull(entity, "ResolveCref() returned null."); Assert.IsNotNull(entity, "ResolveCref() returned null.");

2
ICSharpCode.NRefactory.Tests/Documentation/CSharpDocumentationTests.cs

@ -36,7 +36,7 @@ namespace ICSharpCode.NRefactory.Documentation
{ {
var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib }); var pc = new CSharpProjectContent().AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
var syntaxTree = SyntaxTree.Parse(program, "program.cs"); var syntaxTree = SyntaxTree.Parse(program, "program.cs");
compilation = pc.UpdateProjectContent(null, syntaxTree.ToTypeSystem()).CreateCompilation(); compilation = pc.AddOrUpdateFiles(syntaxTree.ToTypeSystem()).CreateCompilation();
typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault(); typeDefinition = compilation.MainAssembly.TopLevelTypeDefinitions.FirstOrDefault();
} }

60
ICSharpCode.NRefactory.Tests/ICSharpCode.NRefactory.Tests.csproj

@ -14,9 +14,9 @@
<NoStdLib>False</NoStdLib> <NoStdLib>False</NoStdLib>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<OutputPath>..\bin\$(Configuration)\</OutputPath>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType> <DebugType>Full</DebugType>
<Optimize>False</Optimize> <Optimize>False</Optimize>
@ -24,49 +24,26 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath> <DebugType>PdbOnly</DebugType>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop> <RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies> <GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress> <BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment> <FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' "> <PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<RegisterForComInterop>False</RegisterForComInterop> <RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies> <GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress> <BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment> <FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType> <DebugType>Full</DebugType>
<Optimize>False</Optimize> <Optimize>False</Optimize>
@ -74,39 +51,13 @@
<DefineConstants>DEBUG;TRACE;NET45</DefineConstants> <DefineConstants>DEBUG;TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|x86' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath> <DebugType>PdbOnly</DebugType>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;NET45</DefineConstants> <DefineConstants>TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|x86' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System" /> <Reference Include="System" />
@ -234,6 +185,7 @@
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TypeSystem\BlobLoaderTests.cs" /> <Compile Include="TypeSystem\BlobLoaderTests.cs" />
<Compile Include="TypeSystem\CecilLoaderTests.cs" /> <Compile Include="TypeSystem\CecilLoaderTests.cs" />
<Compile Include="TypeSystem\CyclicProjectDependency.cs" />
<Compile Include="TypeSystem\GetAllBaseTypesTest.cs" /> <Compile Include="TypeSystem\GetAllBaseTypesTest.cs" />
<Compile Include="TypeSystem\GetMembersTests.cs" /> <Compile Include="TypeSystem\GetMembersTests.cs" />
<Compile Include="TypeSystem\LazyLoadedCecilLoaderTests.cs" /> <Compile Include="TypeSystem\LazyLoadedCecilLoaderTests.cs" />

64
ICSharpCode.NRefactory.Tests/TypeSystem/CyclicProjectDependency.cs

@ -0,0 +1,64 @@
// Copyright (c) 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.Linq;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.TypeSystem
{
[TestFixture]
public class CyclicProjectDependency
{
IProjectContent pc1;
IProjectContent pc2;
ISolutionSnapshot solution;
[SetUp]
public void Setup()
{
pc1 = new CSharpProjectContent()
.SetAssemblyName("PC1")
.SetProjectFileName("PC1.csproj")
.AddAssemblyReferences(new IAssemblyReference[] { CecilLoaderTests.Mscorlib, new ProjectReference("PC2.csproj") });
pc2 = new CSharpProjectContent()
.SetAssemblyName("PC2")
.SetProjectFileName("PC2.csproj")
.AddAssemblyReferences(new IAssemblyReference[] { CecilLoaderTests.Mscorlib, new ProjectReference("PC1.csproj") });
solution = new DefaultSolutionSnapshot(new[] { pc1, pc2 });
}
[Test]
public void CreateCompilation1()
{
ICompilation c = solution.GetCompilation(pc1);
Assert.AreEqual(new string[] { "PC1", "mscorlib", "PC2" }, c.Assemblies.Select(asm => asm.AssemblyName).ToArray());
}
[Test]
public void CreateCompilation2()
{
ICompilation c = solution.GetCompilation(pc2);
Assert.AreEqual(new string[] { "PC2", "mscorlib", "PC1" }, c.Assemblies.Select(asm => asm.AssemblyName).ToArray());
}
}
}

4
ICSharpCode.NRefactory.Tests/TypeSystem/GetAllBaseTypesTest.cs

@ -67,8 +67,8 @@ namespace System.Collections.Generic {
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
var parsedFile = new CSharpParser().Parse(corlib, "corlib.cs").ToTypeSystem(); var unresolvedFile = new CSharpParser().Parse(corlib, "corlib.cs").ToTypeSystem();
compilation = new CSharpProjectContent().SetAssemblyName("mscorlib").UpdateProjectContent(null, parsedFile).CreateCompilation(); compilation = new CSharpProjectContent().SetAssemblyName("mscorlib").AddOrUpdateFiles(unresolvedFile).CreateCompilation();
} }
IType[] GetAllBaseTypes(Type type) IType[] GetAllBaseTypes(Type type)

12
ICSharpCode.NRefactory.Tests/TypeSystem/TypeSystemHelper.cs

@ -27,20 +27,20 @@ namespace ICSharpCode.NRefactory.TypeSystem
{ {
public static ICompilation CreateCompilation() public static ICompilation CreateCompilation()
{ {
return CreateCompilation(new IParsedFile[0]); return CreateCompilation(new IUnresolvedFile[0]);
} }
public static ICompilation CreateCompilation(params IUnresolvedTypeDefinition[] unresolvedTypeDefinitions) public static ICompilation CreateCompilation(params IUnresolvedTypeDefinition[] unresolvedTypeDefinitions)
{ {
var parsedFile = new CSharpParsedFile("dummy.cs"); var unresolvedFile = new CSharpUnresolvedFile("dummy.cs");
foreach (var typeDef in unresolvedTypeDefinitions) foreach (var typeDef in unresolvedTypeDefinitions)
parsedFile.TopLevelTypeDefinitions.Add(typeDef); unresolvedFile.TopLevelTypeDefinitions.Add(typeDef);
return CreateCompilation(parsedFile); return CreateCompilation(unresolvedFile);
} }
public static ICompilation CreateCompilation(params IParsedFile[] parsedFiles) public static ICompilation CreateCompilation(params IUnresolvedFile[] unresolvedFiles)
{ {
var pc = new CSharpProjectContent().UpdateProjectContent(null, parsedFiles); var pc = new CSharpProjectContent().AddOrUpdateFiles(unresolvedFiles);
pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore }); pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
return pc.CreateCompilation(); return pc.CreateCompilation();
} }

3
ICSharpCode.NRefactory.VB.Tests/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

3
ICSharpCode.NRefactory.VB/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

3
ICSharpCode.NRefactory.Xml/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

11
ICSharpCode.NRefactory.Xml/ICSharpCode.NRefactory.Xml.csproj

@ -12,13 +12,14 @@
<NoStdLib>False</NoStdLib> <NoStdLib>False</NoStdLib>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors> <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<DocumentationFile>..\ICSharpCode.NRefactory\bin\$(Configuration)\ICSharpCode.NRefactory.Xml.xml</DocumentationFile>
<SignAssembly>true</SignAssembly> <SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile>
<DelaySign>False</DelaySign> <DelaySign>False</DelaySign>
<AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode> <AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode>
<ProductVersion>10.0.0</ProductVersion> <ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<OutputPath>..\bin\$(Configuration)\</OutputPath>
<DocumentationFile>..\bin\$(Configuration)\ICSharpCode.NRefactory.Xml.xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' "> <PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -28,13 +29,11 @@
<FileAlignment>4096</FileAlignment> <FileAlignment>4096</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<Optimize>False</Optimize> <Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
@ -48,22 +47,20 @@
<DebugSymbols>false</DebugSymbols> <DebugSymbols>false</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Debug\</OutputPath>
<Optimize>False</Optimize> <Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE;NET45</DefineConstants> <DefineConstants>DEBUG;TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Debug|AnyCPU' ">
<DebugType>full</DebugType> <DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>..\ICSharpCode.NRefactory\bin\Release\</OutputPath>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE;NET45</DefineConstants> <DefineConstants>TRACE;NET45</DefineConstants>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<DebugType>PdbOnly</DebugType> <DebugType>PdbOnly</DebugType>

3
ICSharpCode.NRefactory/.gitignore vendored

@ -1,3 +0,0 @@
bin/
obj/

10
ICSharpCode.NRefactory/Editor/ITextSource.cs

@ -94,6 +94,16 @@ namespace ICSharpCode.NRefactory.Editor
/// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception> /// <exception cref="ArgumentOutOfRangeException">offset or length is outside the valid range.</exception>
string GetText(ISegment segment); string GetText(ISegment segment);
/// <summary>
/// Writes the text from this document into the TextWriter.
/// </summary>
void WriteTextTo(TextWriter writer);
/// <summary>
/// Writes the text from this document into the TextWriter.
/// </summary>
void WriteTextTo(TextWriter writer, int offset, int length);
/// <summary> /// <summary>
/// Gets the index of the first occurrence of the character in the specified array. /// Gets the index of the first occurrence of the character in the specified array.
/// </summary> /// </summary>

12
ICSharpCode.NRefactory/Editor/ReadOnlyDocument.cs

@ -359,6 +359,18 @@ namespace ICSharpCode.NRefactory.Editor
return textSource.CreateReader(offset, length); return textSource.CreateReader(offset, length);
} }
/// <inheritdoc/>
public void WriteTextTo(System.IO.TextWriter writer)
{
textSource.WriteTextTo(writer);
}
/// <inheritdoc/>
public void WriteTextTo(System.IO.TextWriter writer, int offset, int length)
{
textSource.WriteTextTo(writer, offset, length);
}
/// <inheritdoc/> /// <inheritdoc/>
public char GetCharAt(int offset) public char GetCharAt(int offset)
{ {

34
ICSharpCode.NRefactory/Editor/StringBuilderDocument.cs

@ -41,11 +41,27 @@ namespace ICSharpCode.NRefactory.Editor
b = new StringBuilder(); b = new StringBuilder();
} }
/// <summary>
/// Creates a new StringBuilderDocument with the specified initial text.
/// </summary>
public StringBuilderDocument(string text) public StringBuilderDocument(string text)
{ {
if (text == null)
throw new ArgumentNullException("text");
b = new StringBuilder(text); b = new StringBuilder(text);
} }
/// <summary>
/// Creates a new StringBuilderDocument with the initial text copied from the specified text source.
/// </summary>
public StringBuilderDocument(ITextSource textSource)
{
if (textSource == null)
throw new ArgumentNullException("textSource");
b = new StringBuilder(textSource.TextLength);
textSource.WriteTextTo(new StringWriter(b));
}
/// <inheritdoc/> /// <inheritdoc/>
public event EventHandler<TextChangeEventArgs> TextChanging; public event EventHandler<TextChangeEventArgs> TextChanging;
@ -273,6 +289,22 @@ namespace ICSharpCode.NRefactory.Editor
{ {
return new StringReader(GetText(offset, length)); return new StringReader(GetText(offset, length));
} }
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
writer.Write(this.Text);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
if (writer == null)
throw new ArgumentNullException("writer");
writer.Write(GetText(offset, length));
}
#endregion #endregion
#region GetText / IndexOf #region GetText / IndexOf
@ -310,6 +342,8 @@ namespace ICSharpCode.NRefactory.Editor
/// <inheritdoc/> /// <inheritdoc/>
public string GetText(ISegment segment) public string GetText(ISegment segment)
{ {
if (segment == null)
throw new ArgumentNullException("segment");
return b.ToString(segment.Offset, segment.Length); return b.ToString(segment.Offset, segment.Length);
} }

12
ICSharpCode.NRefactory/Editor/StringTextSource.cs

@ -95,6 +95,18 @@ namespace ICSharpCode.NRefactory.Editor
return new StringReader(text.Substring(offset, length)); return new StringReader(text.Substring(offset, length));
} }
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer)
{
writer.Write(text);
}
/// <inheritdoc/>
public void WriteTextTo(TextWriter writer, int offset, int length)
{
writer.Write(text.Substring(offset, length));
}
/// <inheritdoc/> /// <inheritdoc/>
public char GetCharAt(int offset) public char GetCharAt(int offset)
{ {

16
ICSharpCode.NRefactory/ICSharpCode.NRefactory.csproj

@ -19,9 +19,10 @@
<AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>..\ICSharpCode.NRefactory.snk</AssemblyOriginatorKeyFile>
<DelaySign>False</DelaySign> <DelaySign>False</DelaySign>
<AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode> <AssemblyOriginatorKeyMode>File</AssemblyOriginatorKeyMode>
<DocumentationFile>bin\$(Configuration)\ICSharpCode.NRefactory.xml</DocumentationFile>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<NoWarn>1591</NoWarn> <NoWarn>1591</NoWarn>
<OutputPath>..\bin\$(Configuration)\</OutputPath>
<DocumentationFile>..\bin\$(Configuration)\ICSharpCode.NRefactory.xml</DocumentationFile>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' "> <PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -31,14 +32,12 @@
<FileAlignment>4096</FileAlignment> <FileAlignment>4096</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<Optimize>False</Optimize> <Optimize>False</Optimize>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<StartAction>Project</StartAction> <StartAction>Project</StartAction>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
@ -48,10 +47,9 @@
<DebugSymbols>True</DebugSymbols> <DebugSymbols>True</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType> <DebugType>PdbOnly</DebugType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<Optimize>False</Optimize> <Optimize>False</Optimize>
<DefineConstants>DEBUG;TRACE;NET45</DefineConstants> <DefineConstants>DEBUG;TRACE;NET45</DefineConstants>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
@ -63,14 +61,13 @@
<DebugSymbols>True</DebugSymbols> <DebugSymbols>True</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' "> <PropertyGroup Condition=" '$(Configuration)' == 'net_4_5_Release' ">
<OutputPath>bin\Release\</OutputPath>
<Optimize>True</Optimize> <Optimize>True</Optimize>
<DefineConstants>TRACE;NET45</DefineConstants> <DefineConstants>TRACE;NET45</DefineConstants>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow> <CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'net_4_5_Release|AnyCPU' ">
<DebugType>none</DebugType> <DebugType>PdbOnly</DebugType>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
@ -136,6 +133,7 @@
<Compile Include="TypeSystem\ByReferenceType.cs" /> <Compile Include="TypeSystem\ByReferenceType.cs" />
<Compile Include="TypeSystem\CecilLoader.cs" /> <Compile Include="TypeSystem\CecilLoader.cs" />
<Compile Include="TypeSystem\ComHelper.cs" /> <Compile Include="TypeSystem\ComHelper.cs" />
<Compile Include="TypeSystem\DefaultSolutionSnapshot.cs" />
<Compile Include="TypeSystem\DomRegion.cs" /> <Compile Include="TypeSystem\DomRegion.cs" />
<Compile Include="TypeSystem\EntityType.cs" /> <Compile Include="TypeSystem\EntityType.cs" />
<Compile Include="TypeSystem\ExtensionMethods.cs" /> <Compile Include="TypeSystem\ExtensionMethods.cs" />
@ -170,7 +168,6 @@
<Compile Include="TypeSystem\Implementation\DefaultResolvedProperty.cs" /> <Compile Include="TypeSystem\Implementation\DefaultResolvedProperty.cs" />
<Compile Include="TypeSystem\Implementation\DefaultResolvedTypeDefinition.cs" /> <Compile Include="TypeSystem\Implementation\DefaultResolvedTypeDefinition.cs" />
<Compile Include="TypeSystem\Implementation\DefaultResolvedTypeParameter.cs" /> <Compile Include="TypeSystem\Implementation\DefaultResolvedTypeParameter.cs" />
<Compile Include="TypeSystem\Implementation\DefaultSolutionSnapshot.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedAssembly.cs" /> <Compile Include="TypeSystem\Implementation\DefaultUnresolvedAssembly.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedAttribute.cs" /> <Compile Include="TypeSystem\Implementation\DefaultUnresolvedAttribute.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedEvent.cs" /> <Compile Include="TypeSystem\Implementation\DefaultUnresolvedEvent.cs" />
@ -209,7 +206,7 @@
<Compile Include="TypeSystem\IntersectionType.cs" /> <Compile Include="TypeSystem\IntersectionType.cs" />
<Compile Include="TypeSystem\IParameter.cs" /> <Compile Include="TypeSystem\IParameter.cs" />
<Compile Include="TypeSystem\IParameterizedMember.cs" /> <Compile Include="TypeSystem\IParameterizedMember.cs" />
<Compile Include="TypeSystem\IParsedFile.cs" /> <Compile Include="TypeSystem\IUnresolvedFile.cs" />
<Compile Include="TypeSystem\IProjectContent.cs" /> <Compile Include="TypeSystem\IProjectContent.cs" />
<Compile Include="TypeSystem\IProperty.cs" /> <Compile Include="TypeSystem\IProperty.cs" />
<Compile Include="TypeSystem\ISolutionSnapshot.cs" /> <Compile Include="TypeSystem\ISolutionSnapshot.cs" />
@ -222,6 +219,7 @@
<Compile Include="TypeSystem\NullableType.cs" /> <Compile Include="TypeSystem\NullableType.cs" />
<Compile Include="TypeSystem\ParameterizedType.cs" /> <Compile Include="TypeSystem\ParameterizedType.cs" />
<Compile Include="TypeSystem\ParameterListComparer.cs" /> <Compile Include="TypeSystem\ParameterListComparer.cs" />
<Compile Include="TypeSystem\ProjectReference.cs" />
<Compile Include="TypeSystem\ReflectionNameParseException.cs" /> <Compile Include="TypeSystem\ReflectionNameParseException.cs" />
<Compile Include="TypeSystem\SimpleTypeResolveContext.cs" /> <Compile Include="TypeSystem\SimpleTypeResolveContext.cs" />
<Compile Include="TypeSystem\TypeKind.cs" /> <Compile Include="TypeSystem\TypeKind.cs" />

33
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultSolutionSnapshot.cs → ICSharpCode.NRefactory/TypeSystem/DefaultSolutionSnapshot.cs

@ -18,16 +18,47 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.TypeSystem
{ {
/// <summary> /// <summary>
/// Default implementation of ISolutionSnapshot. /// Default implementation of ISolutionSnapshot.
/// </summary> /// </summary>
public class DefaultSolutionSnapshot : ISolutionSnapshot public class DefaultSolutionSnapshot : ISolutionSnapshot
{ {
readonly Dictionary<string, IProjectContent> projectDictionary = new Dictionary<string, IProjectContent>(Platform.FileNameComparer);
ConcurrentDictionary<IProjectContent, ICompilation> dictionary = new ConcurrentDictionary<IProjectContent, ICompilation>(); ConcurrentDictionary<IProjectContent, ICompilation> dictionary = new ConcurrentDictionary<IProjectContent, ICompilation>();
/// <summary>
/// Creates a new DefaultSolutionSnapshot with the specified projects.
/// </summary>
public DefaultSolutionSnapshot(IEnumerable<IProjectContent> projects)
{
foreach (var project in projects) {
if (project.ProjectFileName != null)
projectDictionary.Add(project.ProjectFileName, project);
}
}
/// <summary>
/// Creates a new DefaultSolutionSnapshot that does not support <see cref="ProjectReference"/>s.
/// </summary>
public DefaultSolutionSnapshot()
{
}
public IProjectContent GetProjectContent(string projectFileName)
{
IProjectContent pc;
if (projectDictionary.TryGetValue(projectFileName, out pc))
return pc;
else
return null;
}
public ICompilation GetCompilation(IProjectContent project) public ICompilation GetCompilation(IProjectContent project)
{ {
if (project == null) if (project == null)

6
ICSharpCode.NRefactory/TypeSystem/ExtensionMethods.cs

@ -268,7 +268,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Gets all unresolved type definitions from the file. /// Gets all unresolved type definitions from the file.
/// For partial classes, each part is returned. /// For partial classes, each part is returned.
/// </summary> /// </summary>
public static IEnumerable<IUnresolvedTypeDefinition> GetAllTypeDefinitions (this IParsedFile file) public static IEnumerable<IUnresolvedTypeDefinition> GetAllTypeDefinitions (this IUnresolvedFile file)
{ {
return TreeTraversal.PreOrder(file.TopLevelTypeDefinitions, t => t.NestedTypes); return TreeTraversal.PreOrder(file.TopLevelTypeDefinitions, t => t.NestedTypes);
} }
@ -300,7 +300,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Gets the type (potentially a nested type) defined at the specified location. /// Gets the type (potentially a nested type) defined at the specified location.
/// Returns null if no type is defined at that location. /// Returns null if no type is defined at that location.
/// </summary> /// </summary>
public static IUnresolvedTypeDefinition GetInnermostTypeDefinition (this IParsedFile file, int line, int column) public static IUnresolvedTypeDefinition GetInnermostTypeDefinition (this IUnresolvedFile file, int line, int column)
{ {
return file.GetInnermostTypeDefinition (new TextLocation (line, column)); return file.GetInnermostTypeDefinition (new TextLocation (line, column));
} }
@ -309,7 +309,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Gets the member defined at the specified location. /// Gets the member defined at the specified location.
/// Returns null if no member is defined at that location. /// Returns null if no member is defined at that location.
/// </summary> /// </summary>
public static IUnresolvedMember GetMember (this IParsedFile file, int line, int column) public static IUnresolvedMember GetMember (this IUnresolvedFile file, int line, int column)
{ {
return file.GetMember (new TextLocation (line, column)); return file.GetMember (new TextLocation (line, column));
} }

2
ICSharpCode.NRefactory/TypeSystem/IEntity.cs

@ -54,7 +54,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Gets the parsed file in which this entity is defined. /// Gets the parsed file in which this entity is defined.
/// Returns null if this entity wasn't parsed from source code (e.g. loaded from a .dll with CecilLoader). /// Returns null if this entity wasn't parsed from source code (e.g. loaded from a .dll with CecilLoader).
/// </summary> /// </summary>
IParsedFile ParsedFile { get; } IUnresolvedFile UnresolvedFile { get; }
/// <summary> /// <summary>
/// Gets the attributes on this entity. /// Gets the attributes on this entity.

70
ICSharpCode.NRefactory/TypeSystem/IProjectContent.cs

@ -27,15 +27,20 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
public interface IProjectContent : IUnresolvedAssembly public interface IProjectContent : IUnresolvedAssembly
{ {
/// <summary>
/// Gets the path to the project file (e.g. .csproj).
/// </summary>
string ProjectFileName { get; }
/// <summary> /// <summary>
/// Gets a parsed file by its file name. /// Gets a parsed file by its file name.
/// </summary> /// </summary>
IParsedFile GetFile(string fileName); IUnresolvedFile GetFile(string fileName);
/// <summary> /// <summary>
/// Gets the list of all parsed files in the project content. /// Gets the list of all files in the project content.
/// </summary> /// </summary>
IEnumerable<IParsedFile> Files { get; } IEnumerable<IUnresolvedFile> Files { get; }
/// <summary> /// <summary>
/// Gets the referenced assemblies. /// Gets the referenced assemblies.
@ -52,7 +57,8 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Creates a new <see cref="ICompilation"/> that allows resolving within this project. /// Creates a new <see cref="ICompilation"/> that allows resolving within this project.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// An ICompilation is immutable, it operates on a snapshot of this project. /// This method does not support <see cref="ProjectReference"/>s. When dealing with a solution
/// containing multiple projects, consider using <see cref="ISolutionSnapshot.GetCompilation"/> instead.
/// </remarks> /// </remarks>
ICompilation CreateCompilation(); ICompilation CreateCompilation();
@ -61,7 +67,10 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
/// <param name="solutionSnapshot">The parent solution snapshot to use for the compilation.</param> /// <param name="solutionSnapshot">The parent solution snapshot to use for the compilation.</param>
/// <remarks> /// <remarks>
/// An ICompilation is immutable, it operates on a snapshot of this project. /// This method is intended to be called by ISolutionSnapshot implementations. Other code should
/// call <see cref="ISolutionSnapshot.GetCompilation"/> instead.
/// This method always creates a new compilation, even if the solution snapshot already contains
/// one for this project.
/// </remarks> /// </remarks>
ICompilation CreateCompilation(ISolutionSnapshot solutionSnapshot); ICompilation CreateCompilation(ISolutionSnapshot solutionSnapshot);
@ -71,7 +80,12 @@ namespace ICSharpCode.NRefactory.TypeSystem
IProjectContent SetAssemblyName(string newAssemblyName); IProjectContent SetAssemblyName(string newAssemblyName);
/// <summary> /// <summary>
/// Changes the location of this project content. /// Changes the project file name of this project content.
/// </summary>
IProjectContent SetProjectFileName(string newProjectFileName);
/// <summary>
/// Changes the path to the assembly location (the output path where the project compiles to).
/// </summary> /// </summary>
IProjectContent SetLocation(string newLocation); IProjectContent SetLocation(string newLocation);
@ -80,20 +94,60 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references); IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references);
/// <summary>
/// Add assembly references to this project content.
/// </summary>
IProjectContent AddAssemblyReferences(params IAssemblyReference[] references);
/// <summary> /// <summary>
/// Removes assembly references from this project content. /// Removes assembly references from this project content.
/// </summary> /// </summary>
IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references); IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references);
/// <summary>
/// Removes assembly references from this project content.
/// </summary>
IProjectContent RemoveAssemblyReferences(params IAssemblyReference[] references);
/// <summary>
/// Adds the specified files to the project content.
/// If a file with the same name already exists, updated the existing file.
/// </summary>
/// <remarks>
/// You can create an unresolved file by calling <c>ToTypeSystem()</c> on a syntax tree.
/// </remarks>
IProjectContent AddOrUpdateFiles(IEnumerable<IUnresolvedFile> newFiles);
/// <summary>
/// Adds the specified files to the project content.
/// If a file with the same name already exists, this method updates the existing file.
/// </summary>
/// <remarks>
/// You can create an unresolved file by calling <c>ToTypeSystem()</c> on a syntax tree.
/// </remarks>
IProjectContent AddOrUpdateFiles(params IUnresolvedFile[] newFiles);
/// <summary>
/// Removes the files with the specified names.
/// </summary>
IProjectContent RemoveFiles(IEnumerable<string> fileNames);
/// <summary>
/// Removes the files with the specified names.
/// </summary>
IProjectContent RemoveFiles(params string[] fileNames);
/// <summary> /// <summary>
/// Removes types and attributes from oldFile from the project, and adds those from newFile. /// Removes types and attributes from oldFile from the project, and adds those from newFile.
/// </summary> /// </summary>
IProjectContent UpdateProjectContent(IParsedFile oldFile, IParsedFile newFile); [Obsolete("Use RemoveFiles()/AddOrUpdateFiles() instead")]
IProjectContent UpdateProjectContent(IUnresolvedFile oldFile, IUnresolvedFile newFile);
/// <summary> /// <summary>
/// Removes types and attributes from oldFiles from the project, and adds those from newFiles. /// Removes types and attributes from oldFiles from the project, and adds those from newFiles.
/// </summary> /// </summary>
IProjectContent UpdateProjectContent(IEnumerable<IParsedFile> oldFiles, IEnumerable<IParsedFile> newFiles); [Obsolete("Use RemoveFiles()/AddOrUpdateFiles() instead")]
IProjectContent UpdateProjectContent(IEnumerable<IUnresolvedFile> oldFiles, IEnumerable<IUnresolvedFile> newFiles);
/// <summary> /// <summary>
/// Sets the compiler settings object. /// Sets the compiler settings object.

10
ICSharpCode.NRefactory/TypeSystem/ISolutionSnapshot.cs

@ -25,8 +25,18 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary> /// </summary>
public interface ISolutionSnapshot public interface ISolutionSnapshot
{ {
/// <summary>
/// Gets the project content with the specified file name.
/// Returns null if no such project exists in the solution.
/// </summary>
/// <remarks>
/// This method is used by the <see cref="ProjectReference"/> class.
/// </remarks>
IProjectContent GetProjectContent(string projectFileName);
/// <summary> /// <summary>
/// Gets the compilation for the specified project. /// Gets the compilation for the specified project.
/// The project must be a part of the solution (passed to the solution snapshot's constructor).
/// </summary> /// </summary>
ICompilation GetCompilation(IProjectContent project); ICompilation GetCompilation(IProjectContent project);
} }

5
ICSharpCode.NRefactory/TypeSystem/IParsedFile.cs → ICSharpCode.NRefactory/TypeSystem/IUnresolvedFile.cs

@ -21,10 +21,13 @@ using System.Collections.Generic;
namespace ICSharpCode.NRefactory.TypeSystem namespace ICSharpCode.NRefactory.TypeSystem
{ {
[Obsolete("IParsedFile was renamed to IUnresolvedFile", true)]
public interface IParsedFile {}
/// <summary> /// <summary>
/// Represents a single file that was parsed. /// Represents a single file that was parsed.
/// </summary> /// </summary>
public interface IParsedFile public interface IUnresolvedFile
{ {
/// <summary> /// <summary>
/// Returns the full path of the file. /// Returns the full path of the file.

9
ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractFreezable.cs

@ -87,14 +87,5 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
protected virtual void FreezeInternal() protected virtual void FreezeInternal()
{ {
} }
/*
protected static IList<T> CopyList<T>(IList<T> inputList)
{
if (inputList == null || inputList.Count == 0)
return null;
else
return new List<T>(inputList);
}*/
} }
} }

2
ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractResolvedMember.cs

@ -92,7 +92,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
public override DocumentationComment Documentation { public override DocumentationComment Documentation {
get { get {
IUnresolvedDocumentationProvider docProvider = unresolved.ParsedFile as IUnresolvedDocumentationProvider; IUnresolvedDocumentationProvider docProvider = unresolved.UnresolvedFile as IUnresolvedDocumentationProvider;
if (docProvider != null) { if (docProvider != null) {
var doc = docProvider.GetDocumentation(unresolved, this); var doc = docProvider.GetDocumentation(unresolved, this);
if (doc != null) if (doc != null)

8
ICSharpCode.NRefactory/TypeSystem/Implementation/AbstractUnresolvedEntity.cs

@ -101,7 +101,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
{ {
internal DomRegion region; internal DomRegion region;
internal DomRegion bodyRegion; internal DomRegion bodyRegion;
internal IParsedFile parsedFile; internal IUnresolvedFile unresolvedFile;
protected internal virtual void FreezeInternal() protected internal virtual void FreezeInternal()
{ {
@ -148,11 +148,11 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
} }
} }
public IParsedFile ParsedFile { public IUnresolvedFile UnresolvedFile {
get { return rareFields != null ? rareFields.parsedFile : null; } get { return rareFields != null ? rareFields.unresolvedFile : null; }
set { set {
if (value != null || rareFields != null) if (value != null || rareFields != null)
WriteRareFields().parsedFile = value; WriteRareFields().unresolvedFile = value;
} }
} }

2
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultAssemblyReference.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
public DefaultAssemblyReference(string assemblyName) public DefaultAssemblyReference(string assemblyName)
{ {
int pos = assemblyName.IndexOf(','); int pos = assemblyName != null ? assemblyName.IndexOf(',') : -1;
if (pos >= 0) if (pos >= 0)
shortName = assemblyName.Substring(0, pos); shortName = assemblyName.Substring(0, pos);
else else

2
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultResolvedTypeDefinition.cs

@ -589,7 +589,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
public virtual DocumentationComment Documentation { public virtual DocumentationComment Documentation {
get { get {
foreach (var part in parts) { foreach (var part in parts) {
var unresolvedProvider = part.ParsedFile as IUnresolvedDocumentationProvider; var unresolvedProvider = part.UnresolvedFile as IUnresolvedDocumentationProvider;
if (unresolvedProvider != null) { if (unresolvedProvider != null) {
var doc = unresolvedProvider.GetDocumentation(part, this); var doc = unresolvedProvider.GetDocumentation(part, this);
if (doc != null) if (doc != null)

2
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedEvent.cs

@ -55,7 +55,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
this.DeclaringTypeDefinition = declaringType; this.DeclaringTypeDefinition = declaringType;
this.Name = name; this.Name = name;
if (declaringType != null) if (declaringType != null)
this.ParsedFile = declaringType.ParsedFile; this.UnresolvedFile = declaringType.UnresolvedFile;
} }
public bool CanAdd { public bool CanAdd {

2
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedField.cs

@ -51,7 +51,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
this.DeclaringTypeDefinition = declaringType; this.DeclaringTypeDefinition = declaringType;
this.Name = name; this.Name = name;
if (declaringType != null) if (declaringType != null)
this.ParsedFile = declaringType.ParsedFile; this.UnresolvedFile = declaringType.UnresolvedFile;
} }
public bool IsConst { public bool IsConst {

2
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedMethod.cs

@ -63,7 +63,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
this.DeclaringTypeDefinition = declaringType; this.DeclaringTypeDefinition = declaringType;
this.Name = name; this.Name = name;
if (declaringType != null) if (declaringType != null)
this.ParsedFile = declaringType.ParsedFile; this.UnresolvedFile = declaringType.UnresolvedFile;
} }
public IList<IUnresolvedAttribute> ReturnTypeAttributes { public IList<IUnresolvedAttribute> ReturnTypeAttributes {

2
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedProperty.cs

@ -58,7 +58,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
this.DeclaringTypeDefinition = declaringType; this.DeclaringTypeDefinition = declaringType;
this.Name = name; this.Name = name;
if (declaringType != null) if (declaringType != null)
this.ParsedFile = declaringType.ParsedFile; this.UnresolvedFile = declaringType.UnresolvedFile;
} }
public bool IsIndexer { public bool IsIndexer {

2
ICSharpCode.NRefactory/TypeSystem/Implementation/DefaultUnresolvedTypeDefinition.cs

@ -72,7 +72,7 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
this.DeclaringTypeDefinition = declaringTypeDefinition; this.DeclaringTypeDefinition = declaringTypeDefinition;
this.namespaceName = declaringTypeDefinition.Namespace; this.namespaceName = declaringTypeDefinition.Namespace;
this.Name = name; this.Name = name;
this.ParsedFile = declaringTypeDefinition.ParsedFile; this.UnresolvedFile = declaringTypeDefinition.UnresolvedFile;
} }
public TypeKind Kind { public TypeKind Kind {

3
ICSharpCode.NRefactory/TypeSystem/Implementation/MinimalCorlib.cs

@ -17,9 +17,6 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation namespace ICSharpCode.NRefactory.TypeSystem.Implementation
{ {

3
ICSharpCode.NRefactory/TypeSystem/Implementation/SimpleCompilation.cs

@ -18,8 +18,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using ICSharpCode.NRefactory.Utils; using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.TypeSystem.Implementation namespace ICSharpCode.NRefactory.TypeSystem.Implementation
@ -95,7 +93,6 @@ namespace ICSharpCode.NRefactory.TypeSystem.Implementation
} }
} }
[ObsoleteAttribute("Use compilation.Assemblies.Where(asm != compilation.MainAssembly) instead.")]
public IList<IAssembly> ReferencedAssemblies { public IList<IAssembly> ReferencedAssemblies {
get { get {
if (referencedAssemblies == null) if (referencedAssemblies == null)

56
ICSharpCode.NRefactory/TypeSystem/ProjectReference.cs

@ -0,0 +1,56 @@
// Copyright (c) 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;
namespace ICSharpCode.NRefactory.TypeSystem
{
/// <summary>
/// References another project content in the same solution.
/// Using the <see cref="ProjectReference"/> class requires that you
/// </summary>
[Serializable]
public class ProjectReference : IAssemblyReference
{
readonly string projectFileName;
/// <summary>
/// Creates a new reference to the specified project (must be part of the same solution).
/// </summary>
/// <param name="projectFileName">Full path to the file name. Must be identical to <see cref="IProjectContent.ProjectFileName"/> of the target project; do not use a relative path.</param>
public ProjectReference(string projectFileName)
{
this.projectFileName = projectFileName;
}
public IAssembly Resolve(ITypeResolveContext context)
{
var solution = context.Compilation.SolutionSnapshot;
var pc = solution.GetProjectContent(projectFileName);
if (pc != null)
return pc.Resolve(context);
else
return null;
}
public override string ToString()
{
return string.Format("[ProjectReference {0}]", projectFileName);
}
}
}

2
doc/XML Documentation.html

@ -20,7 +20,7 @@
property is accessed.<br/> property is accessed.<br/>
For this purpose, the type system casts the parsed file to <code>IUnresolvedDocumentationProvider</code> For this purpose, the type system casts the parsed file to <code>IUnresolvedDocumentationProvider</code>
and tries to get the documentation. and tries to get the documentation.
This way, the <code>CSharpParsedFile</code> can provide the documentation from the XML comments.<br/> This way, the <code>CSharpUnresolvedFile</code> can provide the documentation from the XML comments.<br/>
If this fails, the type system casts the unresolved assembly/project content to <code>IDocumentationProvider</code>. If this fails, the type system casts the unresolved assembly/project content to <code>IDocumentationProvider</code>.
This is the way the request for documentation gets to the <code>CecilLoader</code>, This is the way the request for documentation gets to the <code>CecilLoader</code>,
which in turn forwards it to the user-provided <code>IDocumentationProvider</code>. which in turn forwards it to the user-provided <code>IDocumentationProvider</code>.

Loading…
Cancel
Save