Type system refactoring: split unresolved/resolved type systems.

This commit is contained in:
Daniel Grunwald 2011-10-29 02:21:46 +02:00
Родитель 18e088e688
Коммит f631199013
182 изменённых файлов: 8061 добавлений и 7696 удалений

Просмотреть файл

@ -159,16 +159,14 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
Dictionary<string, ControlFlowNode> labels;
List<ControlFlowNode> gotoStatements;
public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, ITypeResolveContext context)
public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement)
{
return BuildControlFlowGraph(statement, context, CancellationToken.None);
return BuildControlFlowGraph(statement, CancellationToken.None);
}
public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, ITypeResolveContext context, CancellationToken cancellationToken)
public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, CancellationToken cancellationToken)
{
return BuildControlFlowGraph(statement, new ResolveVisitor(
new CSharpResolver(context, cancellationToken),
null));
throw new NotImplementedException();
}
public IList<ControlFlowNode> BuildControlFlowGraph(Statement statement, ResolveVisitor resolveVisitor)
@ -308,9 +306,10 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
{
if (c1 == null || c2 == null)
return false;
CSharpResolver r = new CSharpResolver(resolveVisitor.TypeResolveContext, resolveVisitor.CancellationToken);
throw new NotImplementedException();
/*CSharpResolver r = new CSharpResolver(resolveVisitor.TypeResolveContext, resolveVisitor.CancellationToken);
ResolveResult c = r.ResolveBinaryOperator(BinaryOperatorType.Equality, c1, c2);
return c.IsCompileTimeConstant && (c.ConstantValue as bool?) == true;
return c.IsCompileTimeConstant && (c.ConstantValue as bool?) == true;*/
}
#endregion

Просмотреть файл

@ -98,26 +98,22 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
Queue<DefiniteAssignmentNode> nodesWithModifiedInput = new Queue<DefiniteAssignmentNode>();
public DefiniteAssignmentAnalysis(Statement rootStatement)
: this(rootStatement, null, CancellationToken.None)
: this(rootStatement, CancellationToken.None)
{
}
[ObsoleteAttribute]
public DefiniteAssignmentAnalysis(params object[] args)
{
throw new NotImplementedException();
}
public DefiniteAssignmentAnalysis(Statement rootStatement, CancellationToken cancellationToken)
: this(rootStatement, null, cancellationToken)
{
}
public DefiniteAssignmentAnalysis(Statement rootStatement, ITypeResolveContext context)
: this(rootStatement, context, CancellationToken.None)
{
}
public DefiniteAssignmentAnalysis(Statement rootStatement, ITypeResolveContext context, CancellationToken cancellationToken)
: this(rootStatement, new ResolveVisitor(new CSharpResolver(context ?? MinimalResolveContext.Instance, cancellationToken),
null))
{
throw new NotImplementedException();
}
/*
public DefiniteAssignmentAnalysis(Statement rootStatement, ResolveVisitor resolveVisitor)
{
if (rootStatement == null)
@ -157,7 +153,7 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
this.analyzedRangeStart = 0;
this.analyzedRangeEnd = allNodes.Count - 1;
}
}*/
void InsertAnonymousMethods(int insertPos, AstNode node)
{
@ -416,10 +412,6 @@ namespace ICSharpCode.NRefactory.CSharp.Analysis
/// <returns>The constant value of the expression; or null if the expression is not a constant.</returns>
ConstantResolveResult EvaluateConstant(Expression expr)
{
if (resolveVisitor.TypeResolveContext is MinimalResolveContext) {
if (!(expr is PrimitiveExpression || expr is NullReferenceExpression))
return null;
}
return resolveVisitor.Resolve(expr) as ConstantResolveResult;
}

Просмотреть файл

@ -18,6 +18,7 @@
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
{

Просмотреть файл

@ -25,6 +25,7 @@
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
@ -87,6 +88,14 @@ namespace ICSharpCode.NRefactory.CSharp
{
return visitor.VisitCompilationUnit (this, data);
}
/// <summary>
/// Converts this compilation unit into a parsed file that can be stored in the type system.
/// </summary>
public CSharpParsedFile ToTypeSystem(string fileName)
{
return new TypeSystemConvertVisitor(fileName).Convert(this);
}
}
}

Просмотреть файл

@ -32,7 +32,7 @@ namespace ICSharpCode.NRefactory.CSharp
{
Unknown,
/// <summary>
/// DomType
/// AstType
/// </summary>
TypeReference,
/// <summary>

Просмотреть файл

@ -116,7 +116,6 @@ namespace ICSharpCode.NRefactory.CSharp
return o != null && !o.IsNull && this.Statements.DoMatch(o.Statements, match);
}
#region Builder methods
public void Add(Statement statement)
{
AddChild(statement, StatementRole);
@ -124,26 +123,9 @@ namespace ICSharpCode.NRefactory.CSharp
public void Add(Expression expression)
{
AddChild(new ExpressionStatement { Expression = expression }, StatementRole);
AddChild(new ExpressionStatement(expression), StatementRole);
}
public void AddRange(IEnumerable<Statement> statements)
{
foreach (Statement st in statements)
AddChild(st, StatementRole);
}
public void AddAssignment(Expression left, Expression right)
{
Add(new AssignmentExpression { Left = left, Operator = AssignmentOperatorType.Assign, Right = right });
}
public void AddReturnStatement(Expression expression)
{
Add(new ReturnStatement { Expression = expression });
}
#endregion
IEnumerator<Statement> IEnumerable<Statement>.GetEnumerator()
{
return this.Statements.GetEnumerator();

Просмотреть файл

@ -0,0 +1,82 @@
/*
* Created by SharpDevelop.
* User: Daniel
* Date: 10/30/2011
* Time: 01:02
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp
{
public class CSharpProjectContent : IProjectContent
{
public IEnumerable<IParsedFile> Files {
get {
throw new NotImplementedException();
}
}
public IEnumerable<IAssemblyReference> AssemblyReferences {
get {
throw new NotImplementedException();
}
}
public string AssemblyName {
get {
throw new NotImplementedException();
}
}
public IList<IUnresolvedAttribute> AssemblyAttributes {
get {
throw new NotImplementedException();
}
}
public IList<IUnresolvedAttribute> ModuleAttributes {
get {
throw new NotImplementedException();
}
}
public IParsedFile GetFile(string fileName)
{
throw new NotImplementedException();
}
public ICompilation CreateCompilation()
{
throw new NotImplementedException();
}
public IProjectContent AddAssemblyReferences(IEnumerable<IAssemblyReference> references)
{
throw new NotImplementedException();
}
public IProjectContent RemoveAssemblyReferences(IEnumerable<IAssemblyReference> references)
{
throw new NotImplementedException();
}
public IProjectContent UpdateProjectContent(IParsedFile oldFile, IParsedFile newFile)
{
throw new NotImplementedException();
}
public IProjectContent UpdateProjectContent(IEnumerable<IParsedFile> oldFiles, IEnumerable<IParsedFile> newFiles)
{
throw new NotImplementedException();
}
public IAssembly Resolve(ICompilation compilation)
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -1,4 +1,4 @@
//
//
// CSharpCompletionEngine.cs
//
// Author:
@ -317,14 +317,14 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var evt = mrr.Member as IEvent;
if (evt == null)
return null;
var delegateType = evt.ReturnType.Resolve (ctx);
if (!delegateType.IsDelegate ())
var delegateType = evt.ReturnType;
if (delegateType.Kind != TypeKind.Delegate)
return null;
var wrapper = new CompletionDataWrapper (this);
if (currentType != null) {
// bool includeProtected = DomType.IncludeProtected (dom, typeFromDatabase, resolver.CallingType);
foreach (var method in currentType.GetMethods (ctx)) {
foreach (var method in currentType.GetMethods ()) {
if (MatchDelegate (delegateType, method) /*&& method.IsAccessibleFrom (dom, resolver.CallingType, resolver.CallingMember, includeProtected) &&*/) {
wrapper.AddMember (method);
// data.SetText (data.CompletionText + ";");
@ -380,7 +380,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var contextList = new CompletionDataWrapper (this);
if (n != null/* && !(identifierStart.Item2 is TypeDeclaration)*/) {
csResolver = new CSharpResolver (ctx, System.Threading.CancellationToken.None);
csResolver = new CSharpResolver (compilation);
var nodes = new List<AstNode> ();
nodes.Add (n);
if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute)
@ -393,10 +393,10 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (n.Parent is ICSharpCode.NRefactory.CSharp.Attribute) {
var resolved = visitor.GetResolveResult (n.Parent);
if (resolved != null && resolved.Type != null) {
foreach (var property in resolved.Type.GetProperties (ctx).Where (p => p.Accessibility == Accessibility.Public)) {
foreach (var property in resolved.Type.GetProperties (p => p.Accessibility == Accessibility.Public)) {
contextList.AddMember (property);
}
foreach (var field in resolved.Type.GetFields (ctx).Where (p => p.Accessibility == Accessibility.Public)) {
foreach (var field in resolved.Type.GetFields (p => p.Accessibility == Accessibility.Public)) {
contextList.AddMember (field);
}
}
@ -556,7 +556,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
}
foreach (var member in currentType.Resolve (ctx).GetMembers (ctx)) {
foreach (var member in currentType.GetMembers ()) {
if (memberPred == null || memberPred (member))
wrapper.AddMember (member);
}
@ -572,22 +572,24 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
foreach (var u in n.Usings) {
var ns = u.ResolveNamespace (ctx);
if (ns == null)
var importedNamespace = u.ResolveNamespace (compilation);
if (importedNamespace == null)
continue;
foreach (var type in ctx.GetTypes (ns.NamespaceName, StringComparer.Ordinal)) {
foreach (var type in importedNamespace.Types) {
if (typePred == null || typePred (type))
wrapper.AddType (type, type.Name);
}
}
foreach (var type in ctx.GetTypes (n.NamespaceName, StringComparer.Ordinal)) {
INamespace ns = null /* compilation.GetNamespace(n.NamespaceName) */; throw new NotImplementedException();
foreach (var type in ns.Types) {
if (typePred == null || typePred (type))
wrapper.AddType (type, type.Name);
}
foreach (var curNs in ctx.GetNamespaces ().Where (sn => sn.StartsWith (n.NamespaceName) && sn != n.NamespaceName)) {
wrapper.AddNamespace (n.NamespaceName, curNs);
foreach (var curNs in ns.ChildNamespaces) {
wrapper.AddNamespace (n.NamespaceName, curNs.FullName);
}
}
}
@ -683,7 +685,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
}
var isAsWrapper = new CompletionDataWrapper (this);
AddTypesAndNamespaces (isAsWrapper, GetState (), t => isAsType == null || t.IsDerivedFrom (isAsType.GetDefinition (), ctx));
AddTypesAndNamespaces (isAsWrapper, GetState (), t => isAsType == null || t.IsDerivedFrom (isAsType.GetDefinition ()));
return isAsWrapper.Result;
// {
// CompletionDataList completionList = new ProjectDomCompletionDataList ();
@ -904,7 +906,7 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
var wrapper = new CompletionDataWrapper (this);
var state = GetState ();
Predicate<ITypeDefinition> pred = null;
if (hintType != null && !hintType.Equals (SharedTypes.UnknownType)) {
if (hintType != null && !hintType.Equals (SpecialType.UnknownType)) {
var lookup = new MemberLookup (ctx, currentType, ProjectContent);
pred = t => {
// check if type is in inheritance tree.
@ -1032,8 +1034,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
if (delegateMethod == null || delegateMethod.Parameters.Count != method.Parameters.Count)
return false;
// TODO: add support for covariant/contravariant method group conversions
for (int i = 0; i < delegateMethod.Parameters.Count; i++) {
if (!delegateMethod.Parameters [i].Type.Resolve (ctx).Equals (method.Parameters [i].Type.Resolve (ctx)))
if (!delegateMethod.Parameters [i].Type.Equals (method.Parameters [i].Type))
return false;
}
return true;

Просмотреть файл

@ -1,4 +1,4 @@
//
//
// CSharpCompletionEngineBase.cs
//
// Author:
@ -45,11 +45,12 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
protected int offset;
protected TextLocation location;
protected ICompilation compilation;
protected ITypeDefinition currentType;
protected IMember currentMember;
#region Input properties
public ITypeResolveContext ctx { get; set; }
//public ITypeResolveContext ctx { get; set; }
public CompilationUnit Unit { get; set; }
public CSharpParsedFile CSharpParsedFile { get; set; }
public IProjectContent ProjectContent { get; set; }
@ -60,8 +61,9 @@ namespace ICSharpCode.NRefactory.CSharp.Completion
this.offset = offset;
this.location = document.GetLocation (offset);
this.currentType = CSharpParsedFile.GetInnermostTypeDefinition (location);
this.currentMember = CSharpParsedFile.GetMember (location);
throw new NotImplementedException();
//this.currentType = CSharpParsedFile.GetInnermostTypeDefinition (location);
//this.currentMember = CSharpParsedFile.GetMember (location);
}
#region Context helper methods

Просмотреть файл

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{53DCA265-3C3C-42F9-B647-F72BA678122B}</ProjectGuid>
@ -165,6 +165,7 @@
<Compile Include="Ast\TypeMembers\ParameterDeclaration.cs" />
<Compile Include="Ast\TypeMembers\PropertyDeclaration.cs" />
<Compile Include="Ast\TypeMembers\VariableInitializer.cs" />
<Compile Include="CSharpProjectContent.cs" />
<Compile Include="Formatter\AstFormattingVisitor.cs" />
<Compile Include="Formatter\CSharpFormattingOptions.cs" />
<Compile Include="Formatter\Indent.cs" />
@ -234,8 +235,6 @@
<Compile Include="Parser\mcs\typemanager.cs" />
<Compile Include="Parser\mcs\typespec.cs" />
<Compile Include="Parser\mcs\visit.cs" />
<Compile Include="Parser\ParsedFile.cs" />
<Compile Include="Parser\TypeSystemConvertVisitor.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Refactoring\Action.cs" />
<Compile Include="Refactoring\ContextAction\AddAnotherAccessor.cs" />
@ -271,26 +270,20 @@
<Compile Include="Refactoring\Script.cs" />
<Compile Include="Refactoring\TextReplaceAction.cs" />
<Compile Include="Refactoring\TypeSystemAstBuilder.cs" />
<Compile Include="Resolver\AliasNamespaceReference.cs" />
<Compile Include="Resolver\CompositeResolveVisitorNavigator.cs" />
<Compile Include="Resolver\ConstantValues.cs" />
<Compile Include="Resolver\ConversionResolveResult.cs" />
<Compile Include="Resolver\Conversions.cs" />
<Compile Include="Resolver\CSharpAttribute.cs" />
<Compile Include="Resolver\CSharpInvocationResolveResult.cs" />
<Compile Include="Resolver\CSharpOperators.cs" />
<Compile Include="Resolver\CSharpResolver.cs" />
<Compile Include="Resolver\DetectSkippableNodesNavigator.cs" />
<Compile Include="Resolver\ErrorResolveResult.cs" />
<Compile Include="Resolver\FindReferencedEntities.cs" />
<Compile Include="Resolver\FindReferences.cs" />
<Compile Include="Resolver\FindReferenceSearchScope.cs" />
<Compile Include="Resolver\IResolveVisitorNavigator.cs" />
<Compile Include="Resolver\ITypeOrNamespaceReference.cs" />
<Compile Include="Resolver\LambdaResolveResult.cs" />
<Compile Include="Resolver\Log.cs" />
<Compile Include="Resolver\MapTypeIntoNewContext.cs" />
<Compile Include="Resolver\MemberLookup.cs" />
<Compile Include="Resolver\MemberTypeOrNamespaceReference.cs" />
<Compile Include="Resolver\MethodGroupResolveResult.cs" />
<Compile Include="Resolver\NodeListResolveVisitorNavigator.cs" />
<Compile Include="Resolver\OverloadResolution.cs" />
@ -298,15 +291,21 @@
<Compile Include="Resolver\ResolveAtLocation.cs" />
<Compile Include="Resolver\ResolveVisitor.cs" />
<Compile Include="Resolver\SimpleNameLookupMode.cs" />
<Compile Include="Resolver\SimpleTypeOrNamespaceReference.cs" />
<Compile Include="Resolver\TypeInference.cs" />
<Compile Include="Resolver\UsingScope.cs" />
<Compile Include="Completion\CompletionDataWrapper.cs" />
<Compile Include="Completion\CSharpCompletionEngine.cs" />
<Compile Include="Completion\CSharpCompletionEngineBase.cs" />
<Compile Include="Completion\CSharpParameterCompletionEngine.cs" />
<Compile Include="Completion\ICompletionDataFactory.cs" />
<Compile Include="Completion\IParameterCompletionDataFactory.cs" />
<Compile Include="TypeSystem\AliasNamespaceReference.cs" />
<Compile Include="TypeSystem\AttributeTypeReference.cs" />
<Compile Include="TypeSystem\ConstantValues.cs" />
<Compile Include="TypeSystem\CSharpAssembly.cs" />
<Compile Include="TypeSystem\CSharpAttribute.cs" />
<Compile Include="TypeSystem\CSharpParsedFile.cs" />
<Compile Include="TypeSystem\TypeOrNamespaceReference.cs" />
<Compile Include="TypeSystem\MemberTypeOrNamespaceReference.cs" />
<Compile Include="TypeSystem\SimpleTypeOrNamespaceReference.cs" />
<Compile Include="TypeSystem\MethodTypeParameterWithInheritedConstraints.cs" />
<Compile Include="TypeSystem\TypeSystemConvertVisitor.cs" />
<Compile Include="TypeSystem\UsingScope.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory\ICSharpCode.NRefactory.csproj">
@ -317,5 +316,6 @@
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
<ItemGroup>
<Folder Include="Completion\" />
<Folder Include="TypeSystem" />
</ItemGroup>
</Project>

Просмотреть файл

@ -32,24 +32,22 @@ namespace ICSharpCode.NRefactory.CSharp
public ConversionFlags ConversionFlags { get; set; }
#region ConvertEntity
public string ConvertEntity(IEntity e, ITypeResolveContext context)
public string ConvertEntity(IEntity e)
{
using (var ctx = context.Synchronize()) {
StringWriter writer = new StringWriter();
if (e.EntityType == EntityType.TypeDefinition) {
ConvertTypeDeclaration((ITypeDefinition)e, ctx, writer);
} else {
ConvertMember((IMember)e, ctx, writer);
}
return writer.ToString().TrimEnd();
StringWriter writer = new StringWriter();
if (e.EntityType == EntityType.TypeDefinition) {
ConvertTypeDeclaration((ITypeDefinition)e, writer);
} else {
ConvertMember((IMember)e, writer);
}
return writer.ToString().TrimEnd();
}
void ConvertMember(IMember member, ISynchronizedTypeResolveContext ctx, StringWriter writer)
void ConvertMember(IMember member, StringWriter writer)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder(ctx);
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
astBuilder.ShowParameterNames = (ConversionFlags & ConversionFlags.ShowParameterNames) == ConversionFlags.ShowParameterNames;
AttributedNode node = (AttributedNode)astBuilder.ConvertEntity(member);
@ -63,7 +61,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
WriteMemberDeclarationName(member, ctx, writer);
WriteMemberDeclarationName(member, writer);
if ((ConversionFlags & ConversionFlags.ShowParameterList) == ConversionFlags.ShowParameterList
&& member is IParameterizedMember && member.EntityType != EntityType.Property) {
@ -80,18 +78,18 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
TypeSystemAstBuilder CreateAstBuilder(ITypeResolveContext ctx)
TypeSystemAstBuilder CreateAstBuilder()
{
TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder(ctx);
TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder();
astBuilder.ShowModifiers = (ConversionFlags & ConversionFlags.ShowModifiers) == ConversionFlags.ShowModifiers;
astBuilder.ShowAccessibility = (ConversionFlags & ConversionFlags.ShowAccessibility) == ConversionFlags.ShowAccessibility;
astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedTypeNames) != ConversionFlags.UseFullyQualifiedTypeNames;
return astBuilder;
}
void ConvertTypeDeclaration(ITypeDefinition typeDef, ITypeResolveContext ctx, StringWriter writer)
void ConvertTypeDeclaration(ITypeDefinition typeDef, StringWriter writer)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder(ctx);
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
TypeDeclaration typeDeclaration = (TypeDeclaration)astBuilder.ConvertEntity(typeDef);
PrintModifiers(typeDeclaration.Modifiers, writer);
if ((ConversionFlags & ConversionFlags.ShowDefinitionKeyWord) == ConversionFlags.ShowDefinitionKeyWord) {
@ -113,14 +111,14 @@ namespace ICSharpCode.NRefactory.CSharp
}
writer.Write(' ');
}
WriteTypeDeclarationName(typeDef, ctx, writer);
WriteTypeDeclarationName(typeDef, writer);
}
void WriteTypeDeclarationName(ITypeDefinition typeDef, ITypeResolveContext ctx, StringWriter writer)
void WriteTypeDeclarationName(ITypeDefinition typeDef, StringWriter writer)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder(ctx);
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
if (typeDef.DeclaringTypeDefinition != null) {
WriteTypeDeclarationName(typeDef.DeclaringTypeDefinition, ctx, writer);
WriteTypeDeclarationName(typeDef.DeclaringTypeDefinition, writer);
writer.Write('.');
} else if ((ConversionFlags & ConversionFlags.UseFullyQualifiedMemberNames) == ConversionFlags.UseFullyQualifiedMemberNames) {
writer.Write(typeDef.Namespace);
@ -132,9 +130,9 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
void WriteMemberDeclarationName(IMember member, ITypeResolveContext ctx, StringWriter writer)
void WriteMemberDeclarationName(IMember member, StringWriter writer)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder(ctx);
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
if ((ConversionFlags & ConversionFlags.UseFullyQualifiedMemberNames) == ConversionFlags.UseFullyQualifiedMemberNames) {
writer.Write(ConvertType(member.DeclaringType));
writer.Write('.');
@ -154,11 +152,11 @@ namespace ICSharpCode.NRefactory.CSharp
switch (member.Name) {
case "op_Implicit":
writer.Write("implicit operator ");
writer.Write(ConvertType(member.ReturnType, ctx));
writer.Write(ConvertType(member.ReturnType));
break;
case "op_Explicit":
writer.Write("explicit operator ");
writer.Write(ConvertType(member.ReturnType, ctx));
writer.Write(ConvertType(member.ReturnType));
break;
default:
writer.Write("operator ");
@ -195,21 +193,19 @@ namespace ICSharpCode.NRefactory.CSharp
}
#endregion
public string ConvertVariable(IVariable v, ITypeResolveContext context)
public string ConvertVariable(IVariable v)
{
using (var ctx = context.Synchronize()) {
TypeSystemAstBuilder astBuilder = CreateAstBuilder(ctx);
AstNode astNode = astBuilder.ConvertVariable(v);
CSharpFormattingOptions formatting = new CSharpFormattingOptions();
StringWriter writer = new StringWriter();
astNode.AcceptVisitor(new CSharpOutputVisitor(writer, formatting), null);
return writer.ToString().TrimEnd(';', '\r', '\n');
}
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
AstNode astNode = astBuilder.ConvertVariable(v);
CSharpFormattingOptions formatting = new CSharpFormattingOptions();
StringWriter writer = new StringWriter();
astNode.AcceptVisitor(new CSharpOutputVisitor(writer, formatting), null);
return writer.ToString().TrimEnd(';', '\r', '\n');
}
public string ConvertType(IType type)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder(MinimalResolveContext.Instance);
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
AstType astType = astBuilder.ConvertType(type);
CSharpFormattingOptions formatting = new CSharpFormattingOptions();
StringWriter writer = new StringWriter();
@ -217,18 +213,6 @@ namespace ICSharpCode.NRefactory.CSharp
return writer.ToString();
}
public string ConvertType(ITypeReference type, ITypeResolveContext context)
{
using (var ctx = context.Synchronize()) {
TypeSystemAstBuilder astBuilder = CreateAstBuilder(ctx);
AstType astType = astBuilder.ConvertTypeReference(type);
CSharpFormattingOptions formatting = new CSharpFormattingOptions();
StringWriter writer = new StringWriter();
astType.AcceptVisitor(new CSharpOutputVisitor(writer, formatting), null);
return writer.ToString();
}
}
public string WrapAttribute(string attribute)
{
return "[" + attribute + "]";

Просмотреть файл

@ -21,8 +21,8 @@ using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.PatternMatching;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
@ -38,7 +38,7 @@ namespace ICSharpCode.NRefactory.CSharp
/// </remarks>
public class CodeDomConvertVisitor : IAstVisitor<object, CodeObject>
{
ITypeResolveContext context = MinimalResolveContext.Instance;
//ICompilation compilation = MinimalResolveContext.Instance;
ResolveVisitor resolveVisitor;
bool useFullyQualifiedTypeNames;
@ -60,21 +60,23 @@ namespace ICSharpCode.NRefactory.CSharp
/// <remarks>
/// This conversion process requires a resolver because it needs to distinguish field/property/event references etc.
/// </remarks>
public CodeCompileUnit Convert(CompilationUnit compilationUnit, ITypeResolveContext context, CSharpParsedFile parsedFile)
public CodeCompileUnit Convert(CompilationUnit compilationUnit, ICompilation compilation)
{
if (compilationUnit == null)
throw new ArgumentNullException("compilationUnit");
if (context == null)
throw new ArgumentNullException("context");
if (parsedFile == null)
throw new ArgumentNullException("parsedFile");
if (compilation == null)
throw new ArgumentNullException("compilation");
throw new NotImplementedException();
/*
using (var ctx = context.Synchronize()) {
ResolveVisitor resolveVisitor = new ResolveVisitor(new CSharpResolver(ctx), parsedFile);
resolveVisitor.Scan(compilationUnit);
return (CodeCompileUnit)Convert(compilationUnit, resolveVisitor);
}
}*/
}
/*
/// <summary>
/// Converts a C# AST node to CodeDom.
/// </summary>
@ -100,6 +102,7 @@ namespace ICSharpCode.NRefactory.CSharp
this.context = MinimalResolveContext.Instance;
}
}
*/
ResolveResult Resolve(AstNode node)
{
@ -298,7 +301,7 @@ namespace ICSharpCode.NRefactory.CSharp
case BinaryOperatorType.Equality:
case BinaryOperatorType.InEquality:
OperatorResolveResult rr = Resolve(binaryOperatorExpression) as OperatorResolveResult;
if (rr != null && rr.GetChildResults().Any(cr => cr.Type.IsReferenceType(context) == true)) {
if (rr != null && rr.GetChildResults().Any(cr => cr.Type.IsReferenceType == true)) {
if (binaryOperatorExpression.Operator == BinaryOperatorType.Equality)
op = CodeBinaryOperatorType.IdentityEquality;
else
@ -1240,11 +1243,12 @@ namespace ICSharpCode.NRefactory.CSharp
CodeObject IAstVisitor<object, CodeObject>.VisitPrimitiveType(PrimitiveType primitiveType, object data)
{
string keyword = primitiveType.Keyword;
for (TypeCode c = TypeCode.Empty; c <= TypeCode.String; c++) {
if (ReflectionHelper.GetCSharpNameByTypeCode(c) == keyword)
return new CodeTypeReference("System." + ReflectionHelper.GetShortNameByTypeCode(c));
KnownTypeCode typeCode = TypeSystemConvertVisitor.GetTypeCodeForPrimitiveType(keyword);
if (typeCode != KnownTypeCode.None) {
KnownTypeReference ktr = KnownTypeReference.Get(typeCode);
return new CodeTypeReference(ktr.Namespace + "." + ktr.Name);
}
return new CodeTypeReference(primitiveType.Keyword);
return new CodeTypeReference(keyword);
}
CodeObject IAstVisitor<object, CodeObject>.VisitComment(Comment comment, object data)

Просмотреть файл

@ -1,4 +1,4 @@
//
//
// CreateEventInvocator.cs
//
// Author:
@ -84,7 +84,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
};
foreach (var par in pars) {
var typeName = context.CreateShortType (par.Type.Resolve (context.TypeResolveContext));
var typeName = context.CreateShortType (par.Type);
var decl = new ParameterDeclaration (typeName, par.Name);
methodDeclaration.Parameters.Add (decl);
}

Просмотреть файл

@ -1,4 +1,4 @@
//
//
// CreateLocalVariable.cs
//
// Author:
@ -120,7 +120,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
if (result.Parameters.Count < i)
return null;
return context.CreateShortType (result.Parameters[i].Type.Resolve (context.TypeResolveContext));
return context.CreateShortType (result.Parameters[i].Type);
}
return null;
}

Просмотреть файл

@ -49,8 +49,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
var type = result.Type;
var newSwitch = (SwitchStatement)switchStatement.Clone ();
var target = new TypeReferenceExpression (context.CreateShortType (result.Type.Resolve (context.TypeResolveContext)));
foreach (var field in type.GetFields (context.TypeResolveContext)) {
var target = new TypeReferenceExpression (context.CreateShortType (result.Type));
foreach (var field in type.GetFields ()) {
if (field.IsSynthetic || !field.IsConst)
continue;
newSwitch.SwitchSections.Add (new SwitchSection () {

Просмотреть файл

@ -1,4 +1,4 @@
//
//
// UseExplicitType.cs
//
// Author:
@ -39,7 +39,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
if (varDecl == null)
return false;
var type = context.Resolve (varDecl.Variables.First ().Initializer).Type;
return !type.Equals (SharedTypes.Null) && !type.Equals (SharedTypes.UnknownType);
return !type.Equals (SpecialType.NullType) && !type.Equals (SpecialType.UnknownType);
}
public void Run (RefactoringContext context)

Просмотреть файл

@ -39,12 +39,6 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
protected set;
}
public virtual ITypeResolveContext TypeResolveContext {
get {
return null;
}
}
public TextLocation Location {
get;
protected set;
@ -62,12 +56,14 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public AstType CreateShortType (string ns, string typeName)
{
return CreateShortType (TypeResolveContext.GetTypeDefinition (ns, typeName, 0, StringComparer.Ordinal));
throw new NotImplementedException();
//return CreateShortType (TypeResolveContext.GetTypeDefinition (ns, typeName, 0, StringComparer.Ordinal));
}
public virtual AstType CreateShortType (AstType fullType)
{
return CreateShortType (Resolve (fullType).Type.Resolve (TypeResolveContext));
throw new NotImplementedException();
//return CreateShortType (Resolve (fullType).Type.Resolve (TypeResolveContext));
}
// public abstract IType GetDefinition (AstType resolvedType);
@ -133,7 +129,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
#region ConvertTypes
public static ICSharpCode.NRefactory.CSharp.AstType ConvertToAstType (this IType type)
{
var builder = new TypeSystemAstBuilder (MinimalResolveContext.Instance);
var builder = new TypeSystemAstBuilder ();
return builder.ConvertType (type);
}
#endregion

Просмотреть файл

@ -5,8 +5,8 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
@ -20,7 +20,6 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
public class TypeSystemAstBuilder
{
readonly CSharpResolver resolver;
readonly ITypeResolveContext context;
#region Constructor
/// <summary>
@ -34,7 +33,6 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
if (resolver == null)
throw new ArgumentNullException("resolver");
this.resolver = resolver;
this.context = resolver.Context;
InitProperties();
}
@ -44,11 +42,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
/// <param name="context">
/// Context used for resolving types.
/// </param>
public TypeSystemAstBuilder(ITypeResolveContext context)
public TypeSystemAstBuilder()
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
InitProperties();
}
#endregion
@ -136,7 +131,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
// Unbound type
IType[] typeArguments = new IType[typeDef.TypeParameterCount];
for (int i = 0; i < typeArguments.Length; i++) {
typeArguments[i] = SharedTypes.UnboundTypeArgument;
typeArguments[i] = SpecialType.UnboundTypeArgument;
}
return ConvertTypeHelper(typeDef, typeArguments);
} else {
@ -146,62 +141,13 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
return new SimpleType(type.Name);
}
public AstType ConvertTypeReference(ITypeReference typeRef)
{
ArrayTypeReference array = typeRef as ArrayTypeReference;
if (array != null) {
return ConvertTypeReference(array.ElementType).MakeArrayType(array.Dimensions);
}
PointerTypeReference pointer = typeRef as PointerTypeReference;
if (pointer != null) {
return ConvertTypeReference(pointer.ElementType).MakePointerType();
}
ByReferenceType brt = typeRef as ByReferenceType;
if (brt != null) {
return ConvertTypeReference(brt.ElementType);
}
IType type = typeRef.Resolve(context);
if (type.Kind != TypeKind.Unknown)
return ConvertType(type);
// Unknown type, let's try if we can find an appropriate type
// (anything is better than displaying a question mark)
KnownTypeReference knownType = typeRef as KnownTypeReference;
if (knownType != null) {
string keyword = ReflectionHelper.GetCSharpNameByTypeCode(knownType.TypeCode);
if (keyword != null)
return new PrimitiveType(keyword);
}
SimpleTypeOrNamespaceReference str = typeRef as SimpleTypeOrNamespaceReference;
if (str != null) {
return new SimpleType(str.Identifier, str.TypeArguments.Select(ConvertTypeReference));
}
MemberTypeOrNamespaceReference mtr = typeRef as MemberTypeOrNamespaceReference;
if (mtr != null) {
return new MemberType(ConvertTypeReference(mtr.Target), mtr.Identifier, mtr.TypeArguments.Select(ConvertTypeReference)) {
IsDoubleColon = mtr.Target is AliasNamespaceReference
};
}
AliasNamespaceReference alias = typeRef as AliasNamespaceReference;
if (alias != null) {
return new SimpleType(alias.Identifier);
}
// Unknown type reference that couldn't be resolved
return new SimpleType("?");
}
AstType ConvertTypeHelper(ITypeDefinition typeDef, IList<IType> typeArguments)
{
Debug.Assert(typeArguments.Count >= typeDef.TypeParameterCount);
TypeCode typeCode = ReflectionHelper.GetTypeCode(typeDef);
if (typeCode != TypeCode.Empty) {
string keyword = ReflectionHelper.GetCSharpNameByTypeCode(typeCode);
if (keyword != null)
return new PrimitiveType(keyword);
}
// There is no type code for System.Void
if (typeDef.Kind == TypeKind.Void)
return new PrimitiveType("void");
string keyword = KnownTypeReference.GetCSharpNameByTypeCode(typeDef.KnownTypeCode);
if (keyword != null)
return new PrimitiveType(keyword);
// The number of type parameters belonging to outer classes
int outerTypeParameterCount;
@ -214,7 +160,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
// Look if there's an alias to the target type
for (UsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent) {
foreach (var pair in usingScope.UsingAliases) {
IType type = pair.Value.Resolve(resolver.Context);
IType type = pair.Value.ResolveType(resolver);
if (TypeMatches(type, typeDef, typeArguments))
return new SimpleType(pair.Key);
}
@ -306,8 +252,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
for (UsingScope usingScope = resolver.CurrentUsingScope; usingScope != null; usingScope = usingScope.Parent) {
foreach (var pair in usingScope.UsingAliases) {
// maybe add some caching? we're resolving all aliases N times when converting a namespace name with N parts
NamespaceResolveResult nrr = pair.Value.ResolveNamespace(resolver.Context);
if (nrr != null && nrr.NamespaceName == ns)
INamespace nrr = pair.Value.ResolveNamespace(resolver);
if (nrr != null && nrr.FullName == ns)
return new SimpleType(pair.Key);
}
}
@ -344,15 +290,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
#endregion
#region Convert Constant Value
public Expression ConvertConstantValue(IConstantValue constantValue)
{
if (constantValue == null)
throw new ArgumentNullException("constantValue");
return ConvertConstantValue(constantValue.Resolve(context));
}
Expression ConvertConstantValue(ResolveResult rr)
public Expression ConvertConstantValue(ResolveResult rr)
{
if (rr == null)
throw new ArgumentNullException("rr");
if (rr is TypeOfResolveResult) {
return new TypeOfExpression(ConvertType(((TypeOfResolveResult)rr).Type));
} else if (rr is ArrayCreateResolveResult) {
@ -360,21 +301,27 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
AstType type = ConvertType(acrr.Type);
throw new NotImplementedException();
} else if (rr.IsCompileTimeConstant) {
object val = rr.ConstantValue;
if (val == null) {
if (rr.Type.IsReferenceType(context) == true)
return new NullReferenceExpression();
else
return new DefaultValueExpression(ConvertType(rr.Type));
} else if (rr.Type.Kind == TypeKind.Enum) {
throw new NotImplementedException();
} else {
return new PrimitiveExpression(val);
}
return ConvertConstantValue(rr.Type, rr.ConstantValue);
} else {
return new EmptyExpression();
}
}
public Expression ConvertConstantValue(IType type, object constantValue)
{
if (type == null)
throw new ArgumentNullException("type");
if (constantValue == null) {
if (type.IsReferenceType == true)
return new NullReferenceExpression();
else
return new DefaultValueExpression(ConvertType(type));
} else if (type.Kind == TypeKind.Enum) {
throw new NotImplementedException();
} else {
return new PrimitiveExpression(constantValue);
}
}
#endregion
#region Convert Parameter
@ -390,12 +337,12 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
} else if (parameter.IsParams) {
decl.ParameterModifier = ParameterModifier.Params;
}
decl.Type = ConvertTypeReference(parameter.Type);
decl.Type = ConvertType(parameter.Type);
if (this.ShowParameterNames) {
decl.Name = parameter.Name;
}
if (parameter.IsOptional && this.ShowConstantValues) {
decl.DefaultExpression = ConvertConstantValue(parameter.DefaultValue);
decl.DefaultExpression = ConvertConstantValue(parameter.Type, parameter.ConstantValue);
}
return decl;
}
@ -482,8 +429,8 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
if (this.ShowBaseTypes) {
foreach (ITypeReference baseType in typeDefinition.BaseTypes) {
decl.BaseTypes.Add(ConvertTypeReference(baseType));
foreach (IType baseType in typeDefinition.DirectBaseTypes) {
decl.BaseTypes.Add(ConvertType(baseType));
}
}
@ -503,7 +450,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
DelegateDeclaration decl = new DelegateDeclaration();
decl.Modifiers = modifiers;
decl.ReturnType = ConvertTypeReference(invokeMethod.ReturnType);
decl.ReturnType = ConvertType(invokeMethod.ReturnType);
decl.Name = d.Name;
if (this.ShowTypeParameters) {
@ -541,10 +488,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
}
decl.Modifiers = m;
}
decl.ReturnType = ConvertTypeReference(field.ReturnType);
decl.ReturnType = ConvertType(field.ReturnType);
Expression initializer = null;
if (field.IsConst && this.ShowConstantValues)
initializer = ConvertConstantValue(field.ConstantValue);
initializer = ConvertConstantValue(field.Type, field.ConstantValue);
decl.Variables.Add(new VariableInitializer(field.Name, initializer));
return decl;
}
@ -562,7 +509,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
PropertyDeclaration decl = new PropertyDeclaration();
decl.Modifiers = GetMemberModifiers(property);
decl.ReturnType = ConvertTypeReference(property.ReturnType);
decl.ReturnType = ConvertType(property.ReturnType);
decl.Name = property.Name;
decl.Getter = ConvertAccessor(property.Getter);
decl.Setter = ConvertAccessor(property.Setter);
@ -573,7 +520,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
IndexerDeclaration decl = new IndexerDeclaration();
decl.Modifiers = GetMemberModifiers(indexer);
decl.ReturnType = ConvertTypeReference(indexer.ReturnType);
decl.ReturnType = ConvertType(indexer.ReturnType);
foreach (IParameter p in indexer.Parameters) {
decl.Parameters.Add(ConvertParameter(p));
}
@ -586,7 +533,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
EventDeclaration decl = new EventDeclaration();
decl.Modifiers = GetMemberModifiers(ev);
decl.ReturnType = ConvertTypeReference(ev.ReturnType);
decl.ReturnType = ConvertType(ev.ReturnType);
decl.Variables.Add(new VariableInitializer(ev.Name));
return decl;
}
@ -595,7 +542,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
MethodDeclaration decl = new MethodDeclaration();
decl.Modifiers = GetMemberModifiers(method);
decl.ReturnType = ConvertTypeReference(method.ReturnType);
decl.ReturnType = ConvertType(method.ReturnType);
decl.Name = method.Name;
if (this.ShowTypeParameters) {
@ -608,7 +555,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
decl.Parameters.Add(ConvertParameter(p));
}
if (this.ShowTypeParameters && this.ShowTypeParameterConstraints && !method.IsOverride) {
if (this.ShowTypeParameters && this.ShowTypeParameterConstraints && !method.IsOverride && !method.IsExplicitInterfaceImplementation) {
foreach (ITypeParameter tp in method.TypeParameters) {
var constraint = ConvertTypeParameterConstraint(tp);
if (constraint != null)
@ -627,7 +574,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
OperatorDeclaration decl = new OperatorDeclaration();
decl.Modifiers = GetMemberModifiers(op);
decl.OperatorType = opType.Value;
decl.ReturnType = ConvertTypeReference(op.ReturnType);
decl.ReturnType = ConvertType(op.ReturnType);
foreach (IParameter p in op.Parameters) {
decl.Parameters.Add(ConvertParameter(p));
}
@ -709,25 +656,30 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
Constraint ConvertTypeParameterConstraint(ITypeParameter tp)
{
ITypeParameterConstraints constraints = tp.GetConstraints(context);
if (constraints.Count == 0 && !constraints.HasDefaultConstructorConstraint && !constraints.HasReferenceTypeConstraint && !constraints.HasValueTypeConstraint) {
if (!tp.HasDefaultConstructorConstraint && !tp.HasReferenceTypeConstraint && !tp.HasValueTypeConstraint && tp.DirectBaseTypes.All(IsObjectOrValueType)) {
return null;
}
Constraint c = new Constraint();
c.TypeParameter = tp.Name;
if (constraints.HasReferenceTypeConstraint) {
if (tp.HasReferenceTypeConstraint) {
c.BaseTypes.Add(new PrimitiveType("class"));
} else if (constraints.HasValueTypeConstraint) {
} else if (tp.HasValueTypeConstraint) {
c.BaseTypes.Add(new PrimitiveType("struct"));
}
foreach (IType t in constraints) {
c.BaseTypes.Add(ConvertType(t));
foreach (IType t in tp.DirectBaseTypes) {
if (!IsObjectOrValueType(t))
c.BaseTypes.Add(ConvertType(t));
}
if (constraints.HasDefaultConstructorConstraint) {
if (tp.HasDefaultConstructorConstraint) {
c.BaseTypes.Add(new PrimitiveType("new"));
}
return c;
}
static bool IsObjectOrValueType(IType type)
{
return type.Namespace == "System" && type.TypeParameterCount == 0 && (type.Name == "Object" || type.Name == "ValueType");
}
#endregion
#region Convert Variable
@ -735,10 +687,10 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
VariableDeclarationStatement decl = new VariableDeclarationStatement();
decl.Modifiers = v.IsConst ? Modifiers.Const : Modifiers.None;
decl.Type = ConvertTypeReference(v.Type);
decl.Type = ConvertType(v.Type);
Expression initializer = null;
if (v.IsConst)
initializer = ConvertConstantValue(v.ConstantValue);
initializer = ConvertConstantValue(v.Type, v.ConstantValue);
decl.Variables.Add(new VariableInitializer(v.Name, initializer));
return decl;
}

Просмотреть файл

@ -53,7 +53,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
readonly IList<int> argumentToParameterMap;
public CSharpInvocationResolveResult(
ResolveResult targetResult, IParameterizedMember member, IType returnType,
ResolveResult targetResult, IParameterizedMember member,
IList<ResolveResult> arguments,
OverloadResolutionErrors overloadResolutionErrors = OverloadResolutionErrors.None,
bool isExtensionMethodInvocation = false,
@ -61,7 +61,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
bool isLiftedOperatorInvocation = false,
bool isDelegateInvocation = false,
IList<int> argumentToParameterMap = null)
: base(targetResult, member, returnType, arguments)
: base(targetResult, member, arguments)
{
this.OverloadResolutionErrors = overloadResolutionErrors;
this.IsExtensionMethodInvocation = isExtensionMethodInvocation;

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -17,10 +17,10 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Utils;
@ -241,38 +241,38 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary>
/// Contains logic that determines whether an implicit conversion exists between two types.
/// </summary>
public class Conversions
/// <remarks>
/// Because this class internally uses a cache, it is NOT thread-safe!
/// </remarks>
public sealed class Conversions
{
readonly Dictionary<TypePair, Conversion> implicitConversionCache = new Dictionary<TypePair, Conversion>();
readonly ITypeResolveContext context;
readonly ICompilation compilation;
readonly IType objectType;
int subtypeCheckNestingDepth;
public Conversions(ITypeResolveContext context)
public Conversions(ICompilation compilation)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.objectType = KnownTypeReference.Object.Resolve(context);
if (compilation == null)
throw new ArgumentNullException("compilation");
this.compilation = compilation;
this.objectType = compilation.FindType(KnownTypeCode.Object);
this.dynamicErasure = new DynamicErasure(this);
}
/// <summary>
/// Gets the Conversions instance for the specified <see cref="ITypeResolveContext"/>.
/// Gets the Conversions instance for the specified <see cref="ICompilation"/>.
/// This will make use of the context's cache manager (if available) to reuse the Conversions instance.
/// </summary>
public static Conversions Get(ITypeResolveContext context)
public static Conversions Get(ICompilation compilation)
{
CacheManager cache = context.CacheManager;
if (cache != null) {
Conversions conversions = cache.GetThreadLocal(typeof(Conversions)) as Conversions;
if (conversions == null) {
conversions = new Conversions(context);
cache.SetThreadLocal(typeof(Conversions), conversions);
}
return conversions;
} else {
return new Conversions(context);
CacheManager cache = compilation.CacheManager;
Conversions conversions = (Conversions)cache.GetThreadLocal(typeof(Conversions));
if (conversions == null) {
conversions = new Conversions(compilation);
cache.SetThreadLocal(typeof(Conversions), conversions);
}
return conversions;
}
#region TypePair (for caching)
@ -482,7 +482,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public override IType VisitOtherType(IType type)
{
if (type == SharedTypes.Dynamic)
if (type.Kind == TypeKind.Dynamic)
return objectType;
else
return base.VisitOtherType(type);
@ -589,8 +589,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
bool NullLiteralConversion(IType fromType, IType toType)
{
// C# 4.0 spec: §6.1.5
if (SharedTypes.Null.Equals(fromType)) {
return NullableType.IsNullable(toType) || toType.IsReferenceType(context) == true;
if (SpecialType.NullType.Equals(fromType)) {
return NullableType.IsNullable(toType) || toType.IsReferenceType == true;
} else {
return false;
}
@ -603,7 +603,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// C# 4.0 spec: §6.1.6
// reference conversions are possible only if both types are known to be reference types
if (!(fromType.IsReferenceType(context) == true && toType.IsReferenceType(context) == true))
if (!(fromType.IsReferenceType == true && toType.IsReferenceType == true))
return false;
ArrayType fromArray = fromType as ArrayType;
@ -625,8 +625,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
|| ImplicitReferenceConversion(fromArray.ElementType, toPT.GetTypeArgument(0));
}
// conversion from any array to System.Array and the interfaces it implements:
ITypeDefinition systemArray = context.GetTypeDefinition("System", "Array", 0, StringComparer.Ordinal);
return systemArray != null && (systemArray.Equals(toType) || ImplicitReferenceConversion(systemArray, toType));
IType systemArray = KnownTypeReference.Array.Resolve(compilation.TypeResolveContext);
return systemArray.Kind != TypeKind.Unknown && (systemArray.Equals(toType) || ImplicitReferenceConversion(systemArray, toType));
}
// now comes the hard part: traverse the inheritance chain and figure out generics+variance
@ -636,12 +636,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// Determines whether s is a subtype of t.
// Helper method used for ImplicitReferenceConversion, BoxingConversion and ImplicitTypeParameterConversion
int subtypeCheckNestingDepth;
bool IsSubtypeOf(IType s, IType t)
{
// conversion to dynamic + object are always possible
if (t.Equals(SharedTypes.Dynamic) || t.Equals(objectType))
if (t.Equals(SpecialType.Dynamic) || t.Equals(objectType))
return true;
try {
if (++subtypeCheckNestingDepth > 10) {
@ -654,7 +652,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return false;
}
// let GetAllBaseTypes do the work for us
foreach (IType baseType in s.GetAllBaseTypes(context)) {
foreach (IType baseType in s.GetAllBaseTypes()) {
if (IdentityOrVarianceConversion(baseType, t))
return true;
}
@ -706,11 +704,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// C# 4.0 spec: §6.2.4
// reference conversions are possible only if both types are known to be reference types
if (!(fromType.IsReferenceType(context) == true && toType.IsReferenceType(context) == true))
if (!(fromType.IsReferenceType == true && toType.IsReferenceType == true))
return false;
// There's lots of additional rules, but they're not really relevant,
// as they are only used to identify invalid casts, and we don't care about reporting those.
// as they are only used to identify invalid casts, and we currently don't care about reporting those.
return true;
}
#endregion
@ -720,7 +718,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
// C# 4.0 spec: §6.1.7
fromType = NullableType.GetUnderlyingType(fromType);
if (fromType.IsReferenceType(context) == false && toType.IsReferenceType(context) == true)
if (fromType.IsReferenceType == false && toType.IsReferenceType == true)
return IsSubtypeOf(fromType, toType);
else
return false;
@ -730,7 +728,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
// C# 4.0 spec: §6.2.5
toType = NullableType.GetUnderlyingType(toType);
if (fromType.IsReferenceType(context) == true && toType.IsReferenceType(context) == false)
if (fromType.IsReferenceType == true && toType.IsReferenceType == false)
return IsSubtypeOf(toType, fromType);
else
return false;
@ -776,7 +774,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
if (fromType.Kind != TypeKind.TypeParameter)
return false; // not a type parameter
if (fromType.IsReferenceType(context) == true)
if (fromType.IsReferenceType == true)
return false; // already handled by ImplicitReferenceConversion
return IsSubtypeOf(fromType, toType);
}
@ -784,7 +782,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
bool ExplicitTypeParameterConversion(IType fromType, IType toType)
{
if (toType.Kind == TypeKind.TypeParameter) {
return fromType.Kind == TypeKind.TypeParameter || fromType.IsReferenceType(context) == true;
return fromType.Kind == TypeKind.TypeParameter || fromType.IsReferenceType == true;
} else {
return fromType.Kind == TypeKind.TypeParameter && toType.Kind == TypeKind.Interface;
}
@ -797,7 +795,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// C# 4.0 spec: §18.4 Pointer conversions
if (fromType is PointerType && toType is PointerType && toType.ReflectionName == "System.Void*")
return true;
if (SharedTypes.Null.Equals(fromType) && toType is PointerType)
if (SpecialType.NullType.Equals(fromType) && toType is PointerType)
return true;
return false;
}
@ -881,13 +879,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
else
opFilter = m => m.IsStatic && m.IsOperator && m.Name == "op_Implicit" && m.Parameters.Count == 1;
var operators = NullableType.GetUnderlyingType(fromType).GetMethods(context, opFilter)
.Concat(NullableType.GetUnderlyingType(toType).GetMethods(context, opFilter)).Distinct();
var operators = NullableType.GetUnderlyingType(fromType).GetMethods(opFilter)
.Concat(NullableType.GetUnderlyingType(toType).GetMethods(opFilter)).Distinct();
// Determine whether one of them is applicable:
List<OperatorInfo> result = new List<OperatorInfo>();
foreach (IMethod op in operators) {
IType sourceType = op.Parameters[0].Type.Resolve(context);
IType targetType = op.ReturnType.Resolve(context);
IType sourceType = op.Parameters[0].Type;
IType targetType = op.ReturnType;
// Try if the operator is applicable:
bool isApplicable;
if (isExplicit) {
@ -900,11 +898,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
result.Add(new OperatorInfo(op, sourceType, targetType, false));
}
// Try if the operator is applicable in lifted form:
if (NullableType.IsNonNullableValueType(sourceType, context)
&& NullableType.IsNonNullableValueType(targetType, context))
if (NullableType.IsNonNullableValueType(sourceType)
&& NullableType.IsNonNullableValueType(targetType))
{
IType liftedSourceType = NullableType.Create(sourceType, context);
IType liftedTargetType = NullableType.Create(targetType, context);
IType liftedSourceType = NullableType.Create(compilation, sourceType);
IType liftedTargetType = NullableType.Create(compilation, targetType);
if (isExplicit) {
isApplicable = IsEncompassingOrEncompassedBy(fromType, liftedSourceType)
&& IsEncompassingOrEncompassedBy(liftedTargetType, toType);
@ -938,9 +936,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
IType[] dParamTypes = new IType[d.Parameters.Count];
for (int i = 0; i < dParamTypes.Length; i++) {
dParamTypes[i] = d.Parameters[i].Type.Resolve(context);
dParamTypes[i] = d.Parameters[i].Type;
}
IType dReturnType = d.ReturnType.Resolve(context);
IType dReturnType = d.ReturnType;
if (f.HasParameterList) {
// If F contains an anonymous-function-signature, then D and F have the same number of parameters.
@ -961,7 +959,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
IParameter pF = f.Parameters[i];
if (pD.IsRef != pF.IsRef || pD.IsOut != pF.IsOut)
return Conversion.None;
if (!dParamTypes[i].Equals(pF.Type.Resolve(context)))
if (!dParamTypes[i].Equals(pF.Type))
return Conversion.None;
}
}
@ -1002,7 +1000,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult[] args = new ResolveResult[m.Parameters.Count];
for (int i = 0; i < args.Length; i++) {
IParameter param = m.Parameters[i];
IType parameterType = param.Type.Resolve(context);
IType parameterType = param.Type;
if ((param.IsRef || param.IsOut) && parameterType.Kind == TypeKind.ByReference) {
parameterType = ((ByReferenceType)parameterType).ElementType;
args[i] = new ByReferenceResolveResult(parameterType, param.IsOut);
@ -1010,7 +1008,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
args[i] = new ResolveResult(parameterType);
}
}
var or = rr.PerformOverloadResolution(context, args, allowExpandingParams: false, conversions: this);
var or = rr.PerformOverloadResolution(compilation, args, allowExpandingParams: false, conversions: this);
if (or.FoundApplicableCandidate)
return Conversion.MethodGroupConversion((IMethod)or.BestCandidate);
else
@ -1042,15 +1040,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return 0;
IType[] parameterTypes = new IType[m1.Parameters.Count];
for (int i = 0; i < parameterTypes.Length; i++) {
parameterTypes[i] = m1.Parameters[i].Type.Resolve(context);
if (!parameterTypes[i].Equals(m2.Parameters[i].Type.Resolve(context)))
parameterTypes[i] = m1.Parameters[i].Type;
if (!parameterTypes[i].Equals(m2.Parameters[i].Type))
return 0;
}
if (lambda.HasParameterList && parameterTypes.Length != lambda.Parameters.Count)
return 0;
IType ret1 = m1.ReturnType.Resolve(context);
IType ret2 = m2.ReturnType.Resolve(context);
IType ret1 = m1.ReturnType;
IType ret2 = m2.ReturnType;
if (ret1.Kind == TypeKind.Void && ret2.Kind != TypeKind.Void)
return 1;
if (ret1.Kind != TypeKind.Void && ret2.Kind == TypeKind.Void)

Просмотреть файл

@ -20,7 +20,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Utils;
@ -40,11 +40,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public sealed class FindReferences
{
#region Properties
/// <summary>
/// Gets/Sets the cancellation token.
/// </summary>
public CancellationToken CancellationToken { get; set; }
/// <summary>
/// Gets/Sets whether to find type references even if an alias is being used.
/// </summary>
@ -224,7 +219,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary>
/// Gets the file names that possibly contain references to the element being searched for.
/// </summary>
public IList<string> GetInterestingFileNames(IFindReferenceSearchScope searchScope, IEnumerable<ITypeDefinition> allTypes, ITypeResolveContext context)
public IList<string> GetInterestingFileNames(IFindReferenceSearchScope searchScope, IEnumerable<ITypeDefinition> allTypes)
{
IEnumerable<ITypeDefinition> interestingTypes;
if (searchScope.TopLevelTypeDefinition != null) {
@ -234,18 +229,18 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
interestingTypes = new [] { searchScope.TopLevelTypeDefinition.GetDefinition() };
break;
case Accessibility.Protected:
interestingTypes = GetInterestingTypesProtected(allTypes, context, searchScope.TopLevelTypeDefinition);
interestingTypes = GetInterestingTypesProtected(allTypes, searchScope.TopLevelTypeDefinition);
break;
case Accessibility.Internal:
interestingTypes = GetInterestingTypesInternal(allTypes, context, searchScope.TopLevelTypeDefinition.ProjectContent);
interestingTypes = GetInterestingTypesInternal(allTypes, searchScope.TopLevelTypeDefinition.ParentAssembly);
break;
case Accessibility.ProtectedAndInternal:
interestingTypes = GetInterestingTypesProtected(allTypes, context, searchScope.TopLevelTypeDefinition)
.Intersect(GetInterestingTypesInternal(allTypes, context, searchScope.TopLevelTypeDefinition.ProjectContent));
interestingTypes = GetInterestingTypesProtected(allTypes, searchScope.TopLevelTypeDefinition)
.Intersect(GetInterestingTypesInternal(allTypes, searchScope.TopLevelTypeDefinition.ParentAssembly));
break;
case Accessibility.ProtectedOrInternal:
interestingTypes = GetInterestingTypesProtected(allTypes, context, searchScope.TopLevelTypeDefinition)
.Union(GetInterestingTypesInternal(allTypes, context, searchScope.TopLevelTypeDefinition.ProjectContent));
interestingTypes = GetInterestingTypesProtected(allTypes, searchScope.TopLevelTypeDefinition)
.Union(GetInterestingTypesInternal(allTypes, searchScope.TopLevelTypeDefinition.ParentAssembly));
break;
default:
interestingTypes = allTypes;
@ -255,20 +250,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
interestingTypes = allTypes;
}
return (from typeDef in interestingTypes
from part in typeDef.GetParts()
from part in typeDef.Parts
where part.ParsedFile != null
select part.ParsedFile.FileName
).Distinct(Platform.FileNameComparer).ToList();
}
IEnumerable<ITypeDefinition> GetInterestingTypesProtected(IEnumerable<ITypeDefinition> allTypes, ITypeResolveContext context, ITypeDefinition referencedTypeDefinition)
IEnumerable<ITypeDefinition> GetInterestingTypesProtected(IEnumerable<ITypeDefinition> allTypes, ITypeDefinition referencedTypeDefinition)
{
return allTypes.Where(t => t.IsDerivedFrom(referencedTypeDefinition, context));
return allTypes.Where(t => t.IsDerivedFrom(referencedTypeDefinition));
}
IEnumerable<ITypeDefinition> GetInterestingTypesInternal(IEnumerable<ITypeDefinition> allTypes, ITypeResolveContext context, IProjectContent referencedProjectContent)
IEnumerable<ITypeDefinition> GetInterestingTypesInternal(IEnumerable<ITypeDefinition> allTypes, IAssembly referencedAssembly)
{
return allTypes.Where(t => referencedProjectContent.InternalsVisibleTo(t.ProjectContent, context));
return allTypes.Where(t => referencedAssembly.InternalsVisibleTo(t.ParentAssembly));
}
#endregion
@ -282,11 +277,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <param name="context">The type resolve context to use for resolving the file.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
public void FindReferencesInFile(IFindReferenceSearchScope searchScope, CSharpParsedFile parsedFile, CompilationUnit compilationUnit,
ITypeResolveContext context, FoundReferenceCallback callback)
FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (searchScope == null)
throw new ArgumentNullException("searchScope");
FindReferencesInFile(new[] { searchScope }, parsedFile, compilationUnit, context, callback);
FindReferencesInFile(new[] { searchScope }, parsedFile, compilationUnit, callback, cancellationToken);
}
/// <summary>
@ -298,7 +293,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <param name="context">The type resolve context to use for resolving the file.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
public void FindReferencesInFile(IList<IFindReferenceSearchScope> searchScopes, CSharpParsedFile parsedFile, CompilationUnit compilationUnit,
ITypeResolveContext context, FoundReferenceCallback callback)
FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (searchScopes == null)
throw new ArgumentNullException("searchScopes");
@ -306,9 +301,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
throw new ArgumentNullException("parsedFile");
if (compilationUnit == null)
throw new ArgumentNullException("compilationUnit");
throw new NotImplementedException();
/*
if (context == null)
throw new ArgumentNullException("context");
this.CancellationToken.ThrowIfCancellationRequested();
if (searchScopes.Count == 0)
return;
using (var ctx = context.Synchronize()) {
@ -321,7 +318,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
CSharpResolver resolver = new CSharpResolver(ctx, this.CancellationToken);
ResolveVisitor v = new ResolveVisitor(resolver, parsedFile, navigator);
v.Scan(compilationUnit);
}
}*/
}
#endregion
@ -803,11 +800,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <param name="context">The type resolve context to use for resolving the file.</param>
/// <param name="callback">Callback used to report the references that were found.</param>
public void FindLocalReferences(IVariable variable, CSharpParsedFile parsedFile, CompilationUnit compilationUnit,
ITypeResolveContext context, FoundReferenceCallback callback)
FoundReferenceCallback callback, CancellationToken cancellationToken)
{
if (variable == null)
throw new ArgumentNullException("variable");
FindReferencesInFile(new FindLocalReferencesNavigator(variable), parsedFile, compilationUnit, context, callback);
FindReferencesInFile(new FindLocalReferencesNavigator(variable), parsedFile, compilationUnit, callback, cancellationToken);
}
class FindLocalReferencesNavigator : SearchScope

Просмотреть файл

@ -28,7 +28,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary>
public abstract class LambdaResolveResult : ResolveResult
{
protected LambdaResolveResult() : base(SharedTypes.UnknownType)
protected LambdaResolveResult() : base(SpecialType.UnknownType)
{
}

Просмотреть файл

@ -1,64 +0,0 @@
// 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 ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
/// <summary>
/// Converts a type by replacing all type definitions with the equivalent definitions in the new context.
/// </summary>
sealed class MapTypeIntoNewContext : TypeVisitor
{
readonly ITypeResolveContext context;
public MapTypeIntoNewContext(ITypeResolveContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
}
public override IType VisitTypeDefinition(ITypeDefinition type)
{
if (type.DeclaringTypeDefinition != null) {
ITypeDefinition decl = type.DeclaringTypeDefinition.AcceptVisitor(this) as ITypeDefinition;
if (decl != null) {
foreach (ITypeDefinition c in decl.NestedTypes) {
if (c.Name == type.Name && c.TypeParameterCount == type.TypeParameterCount)
return c;
}
}
return type;
} else {
return context.GetTypeDefinition(type.Namespace, type.Name, type.TypeParameterCount, StringComparer.Ordinal) ?? type;
}
}
public override IType VisitTypeParameter(ITypeParameter type)
{
// TODO: how to map type parameters?
// It might have constraints, and those constraints might be mutually recursive.
// Maybe reintroduce ITypeParameter.Owner?
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -36,31 +36,25 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary>
/// Gets whether the member is considered to be invocable.
/// </summary>
public static bool IsInvocable(IMember member, ITypeResolveContext context)
public static bool IsInvocable(IMember member)
{
if (member == null)
throw new ArgumentNullException("member");
// C# 4.0 spec, §7.4 member lookup
if (member is IEvent || member is IMethod)
return true;
IType returnType = member.ReturnType.Resolve(context);
if (returnType == SharedTypes.Dynamic)
return true;
return returnType.Kind == TypeKind.Delegate;
IType returnType = member.ReturnType;
return returnType.Kind == TypeKind.Dynamic || returnType.Kind == TypeKind.Delegate;
}
#endregion
ITypeResolveContext context;
ITypeDefinition currentTypeDefinition;
IProjectContent currentProject;
IAssembly currentAssembly;
public MemberLookup(ITypeResolveContext context, ITypeDefinition currentTypeDefinition, IProjectContent currentProject)
public MemberLookup(ITypeDefinition currentTypeDefinition, IAssembly currentAssembly)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.currentTypeDefinition = currentTypeDefinition;
this.currentProject = currentProject;
this.currentAssembly = currentAssembly;
}
#region IsAccessible
@ -70,7 +64,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public bool IsProtectedAccessAllowed(IType targetType)
{
ITypeDefinition typeDef = targetType.GetDefinition();
return typeDef != null && typeDef.IsDerivedFrom(currentTypeDefinition, context);
return typeDef != null && typeDef.IsDerivedFrom(currentTypeDefinition);
}
/// <summary>
@ -107,21 +101,21 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return (allowProtectedAccess || entity.IsStatic || entity.EntityType == EntityType.TypeDefinition)
&& IsProtectedAccessible(entity.DeclaringTypeDefinition);
case Accessibility.Internal:
return IsInternalAccessible(entity.ProjectContent);
return IsInternalAccessible(entity.ParentAssembly);
case Accessibility.ProtectedOrInternal:
return (allowProtectedAccess && IsProtectedAccessible(entity.DeclaringTypeDefinition))
|| IsInternalAccessible(entity.ProjectContent);
|| IsInternalAccessible(entity.ParentAssembly);
case Accessibility.ProtectedAndInternal:
return (allowProtectedAccess && IsProtectedAccessible(entity.DeclaringTypeDefinition))
&& IsInternalAccessible(entity.ProjectContent);
&& IsInternalAccessible(entity.ParentAssembly);
default:
throw new Exception("Invalid value for Accessibility");
}
}
bool IsInternalAccessible(IProjectContent declaringProject)
bool IsInternalAccessible(IAssembly assembly)
{
return declaringProject != null && currentProject != null && declaringProject.InternalsVisibleTo(currentProject, context);
return assembly != null && currentAssembly != null && assembly.InternalsVisibleTo(currentAssembly);
}
bool IsProtectedAccessible(ITypeDefinition declaringType)
@ -130,7 +124,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return true;
// PERF: this might hurt performance as this method is called several times (once for each member)
// make sure resolving base types is cheap (caches?) or cache within the MemberLookup instance
return currentTypeDefinition != null && currentTypeDefinition.IsDerivedFrom(declaringType, context);
return currentTypeDefinition != null && currentTypeDefinition.IsDerivedFrom(declaringType);
}
#endregion
@ -188,15 +182,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
List<LookupGroup> lookupGroups = new List<LookupGroup>();
if (declaringType.Kind != TypeKind.TypeParameter) {
foreach (IType type in declaringType.GetNonInterfaceBaseTypes(context)) {
foreach (IType type in declaringType.GetNonInterfaceBaseTypes()) {
List<IType> newNestedTypes = null;
IEnumerable<IType> typeBaseTypes = null;
IEnumerable<IType> nestedTypes;
if (parameterizeResultType) {
nestedTypes = type.GetNestedTypes(typeArguments, context, filter, GetMemberOptions.IgnoreInheritedMembers);
nestedTypes = type.GetNestedTypes(typeArguments, filter, GetMemberOptions.IgnoreInheritedMembers);
} else {
nestedTypes = type.GetNestedTypes(context, filter, GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions);
nestedTypes = type.GetNestedTypes(filter, GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions);
}
AddNestedTypes(type, nestedTypes, typeArgumentCount, lookupGroups, ref typeBaseTypes, ref newNestedTypes);
@ -255,7 +249,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// 2) It adds a new lookup group with the members from a declaring type.
// 3) It replaces virtual members with the overridden version, placing the override in the
// lookup group belonging to the base class.
foreach (IType type in targetResolveResult.Type.GetNonInterfaceBaseTypes(context)) {
foreach (IType type in targetResolveResult.Type.GetNonInterfaceBaseTypes()) {
List<IType> newNestedTypes = null;
List<IParameterizedMember> newMethods = null;
@ -267,7 +261,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// Consider nested types only if it's not an invocation.
// type.GetNestedTypes() is checking the type parameter count for an exact match,
// so we don't need to do that in our filter.
var nestedTypes = type.GetNestedTypes(typeArguments, context, filter, GetMemberOptions.IgnoreInheritedMembers);
var nestedTypes = type.GetNestedTypes(typeArguments, filter, GetMemberOptions.IgnoreInheritedMembers);
AddNestedTypes(type, nestedTypes, typeArguments.Count, lookupGroups, ref typeBaseTypes, ref newNestedTypes);
}
@ -275,13 +269,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (typeArguments.Count == 0) {
// Note: IsInvocable-checking cannot be done as part of the filter;
// because it must be done after type substitution.
members = type.GetMembers(context, filter, GetMemberOptions.IgnoreInheritedMembers);
members = type.GetMembers(filter, GetMemberOptions.IgnoreInheritedMembers);
if (isInvocation)
members = members.Where(m => IsInvocable(m, context));
members = members.Where(m => IsInvocable(m));
} else {
// No need to check for isInvocation/isInvocable here:
// we only fetch methods
members = type.GetMethods(typeArguments, context, filter, GetMemberOptions.IgnoreInheritedMembers);
members = type.GetMethods(typeArguments, filter, GetMemberOptions.IgnoreInheritedMembers);
}
AddMembers(type, members, lookupGroups, false, ref typeBaseTypes, ref newMethods, ref newNonMethod);
@ -314,13 +308,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
};
List<LookupGroup> lookupGroups = new List<LookupGroup>();
foreach (IType type in targetType.GetNonInterfaceBaseTypes(context)) {
foreach (IType type in targetType.GetNonInterfaceBaseTypes()) {
List<IParameterizedMember> newMethods = null;
IMember newNonMethod = null;
IEnumerable<IType> typeBaseTypes = null;
var members = type.GetProperties(context, filter, GetMemberOptions.IgnoreInheritedMembers);
var members = type.GetProperties(filter, GetMemberOptions.IgnoreInheritedMembers);
AddMembers(type, members, lookupGroups, true, ref typeBaseTypes, ref newMethods, ref newNonMethod);
if (newMethods != null || newNonMethod != null)
@ -366,7 +360,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (lookupGroup.AllHidden)
continue; // everything is already hidden
if (typeBaseTypes == null)
typeBaseTypes = type.GetNonInterfaceBaseTypes(context);
typeBaseTypes = type.GetNonInterfaceBaseTypes();
if (typeBaseTypes.Contains(lookupGroup.DeclaringType)) {
lookupGroup.MethodsAreHidden = true;
@ -416,14 +410,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// in the most-derived type
for (int i = lookupGroups.Count - 1; i >= 0 && !replacedVirtualMemberWithOverride; i--) {
if (typeBaseTypes == null)
typeBaseTypes = type.GetNonInterfaceBaseTypes(context);
typeBaseTypes = type.GetNonInterfaceBaseTypes();
var lookupGroup = lookupGroups[i];
if (typeBaseTypes.Contains(lookupGroup.DeclaringType)) {
if (method != null) {
// Find the matching method, and replace it with the override
for (int j = 0; j < lookupGroup.Methods.Count; j++) {
if (ParameterListComparer.Compare(context, method, lookupGroup.Methods[j])) {
if (SignatureComparer.Ordinal.Equals(method, lookupGroup.Methods[j])) {
lookupGroup.Methods[j] = method;
replacedVirtualMemberWithOverride = true;
break;
@ -448,7 +442,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (lookupGroup.AllHidden)
continue; // everything is already hidden
if (typeBaseTypes == null)
typeBaseTypes = type.GetNonInterfaceBaseTypes(context);
typeBaseTypes = type.GetNonInterfaceBaseTypes();
if (typeBaseTypes.Contains(lookupGroup.DeclaringType)) {
// Methods hide all non-methods; Non-methods hide everything
@ -502,7 +496,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// The mapping of virtual to overridden methods is already done,
// so we can simply remove the methods from the collection
interfaceLookupGroup.Methods.RemoveAll(
m => ParameterListComparer.Compare(context, classMethod, m));
m => SignatureComparer.Ordinal.Equals(classMethod, m));
}
}
}
@ -558,10 +552,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
if (lookupGroups.Count > 1) {
return new AmbiguousMemberResolveResult(targetResolveResult, resultGroup.NonMethod,
resultGroup.NonMethod.ReturnType.Resolve(context));
return new AmbiguousMemberResolveResult(targetResolveResult, resultGroup.NonMethod);
} else {
return new MemberResolveResult(targetResolveResult, resultGroup.NonMethod, context);
return new MemberResolveResult(targetResolveResult, resultGroup.NonMethod);
}
}
#endregion

Просмотреть файл

@ -22,7 +22,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
@ -58,7 +58,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
readonly ResolveResult targetResult;
readonly string methodName;
public MethodGroupResolveResult(ResolveResult targetResult, string methodName, IList<MethodListWithDeclaringType> methods, IList<IType> typeArguments) : base(SharedTypes.UnknownType)
public MethodGroupResolveResult(ResolveResult targetResult, string methodName, IList<MethodListWithDeclaringType> methods, IList<IType> typeArguments) : base(SpecialType.UnknownType)
{
if (targetResult == null)
throw new ArgumentNullException("targetResult");
@ -159,13 +159,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return string.Format("[{0} with {1} method(s)]", GetType().Name, this.Methods.Count());
}
public OverloadResolution PerformOverloadResolution(ITypeResolveContext context, ResolveResult[] arguments, string[] argumentNames = null, bool allowExtensionMethods = true, bool allowExpandingParams = true, Conversions conversions = null)
public OverloadResolution PerformOverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, bool allowExtensionMethods = true, bool allowExpandingParams = true, Conversions conversions = null)
{
Log.WriteLine("Performing overload resolution for " + this);
Log.WriteCollection(" Arguments: ", arguments);
var typeArgumentArray = this.TypeArguments.ToArray();
OverloadResolution or = new OverloadResolution(context, arguments, argumentNames, typeArgumentArray, conversions);
OverloadResolution or = new OverloadResolution(compilation, arguments, argumentNames, typeArgumentArray, conversions);
or.AllowExpandingParams = allowExpandingParams;
or.AddMethodLists(methodLists);
@ -185,7 +185,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
extArgumentNames = new string[argumentNames.Length + 1];
argumentNames.CopyTo(extArgumentNames, 1);
}
var extOr = new OverloadResolution(context, extArguments, extArgumentNames, typeArgumentArray, conversions);
var extOr = new OverloadResolution(compilation, extArguments, extArgumentNames, typeArgumentArray, conversions);
extOr.AllowExpandingParams = allowExpandingParams;
extOr.IsExtensionMethodInvocation = true;

Просмотреть файл

@ -110,7 +110,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
}
readonly ITypeResolveContext context;
readonly ICompilation compilation;
readonly ResolveResult[] arguments;
readonly string[] argumentNames;
readonly Conversions conversions;
@ -120,17 +120,17 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
IType[] explicitlyGivenTypeArguments;
#region Constructor
public OverloadResolution(ITypeResolveContext context, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, Conversions conversions = null)
public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, Conversions conversions = null)
{
if (context == null)
throw new ArgumentNullException("context");
if (compilation == null)
throw new ArgumentNullException("compilation");
if (arguments == null)
throw new ArgumentNullException("arguments");
if (argumentNames == null)
argumentNames = new string[arguments.Length];
else if (argumentNames.Length != arguments.Length)
throw new ArgumentException("argumentsNames.Length must be equal to arguments.Length");
this.context = context;
this.compilation = compilation;
this.arguments = arguments;
this.argumentNames = argumentNames;
@ -138,7 +138,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (typeArguments != null && typeArguments.Length > 0)
this.explicitlyGivenTypeArguments = typeArguments;
this.conversions = conversions ?? Conversions.Get(context);
this.conversions = conversions ?? Conversions.Get(compilation);
this.AllowExpandingParams = true;
}
#endregion
@ -214,7 +214,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
bool ResolveParameterTypes(Candidate candidate)
{
for (int i = 0; i < candidate.Parameters.Count; i++) {
IType type = candidate.Parameters[i].Type.Resolve(context);
IType type = candidate.Parameters[i].Type;
if (candidate.IsExpandedForm && i == candidate.Parameters.Count - 1) {
ArrayType arrayType = type as ArrayType;
if (arrayType != null && arrayType.Dimensions == 1)
@ -266,7 +266,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
if (foundApplicableCandidateInCurrentList && i > 0) {
foreach (IType baseType in methodList.DeclaringType.GetAllBaseTypes(context)) {
foreach (IType baseType in methodList.DeclaringType.GetAllBaseTypes()) {
for (int j = 0; j < i; j++) {
if (!isHiddenByDerivedType[j] && baseType.Equals(methodLists[j].DeclaringType))
isHiddenByDerivedType[j] = true;
@ -358,11 +358,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (i < explicitlyGivenTypeArguments.Length)
candidate.InferredTypes[i] = explicitlyGivenTypeArguments[i];
else
candidate.InferredTypes[i] = SharedTypes.UnknownType;
candidate.InferredTypes[i] = SpecialType.UnknownType;
}
}
} else {
TypeInference ti = new TypeInference(context, conversions);
TypeInference ti = new TypeInference(compilation, conversions);
bool success;
candidate.InferredTypes = ti.InferTypeArguments(method.TypeParameters, arguments, candidate.ParameterTypes, out success, classTypeArguments);
if (!success)
@ -380,13 +380,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
sealed class ConstraintValidatingSubstitution : TypeParameterSubstitution
{
readonly Conversions conversions;
readonly ITypeResolveContext context;
public bool ConstraintsValid = true;
public ConstraintValidatingSubstitution(IList<IType> classTypeArguments, IList<IType> methodTypeArguments, OverloadResolution overloadResolution)
: base(classTypeArguments, methodTypeArguments)
{
this.context = overloadResolution.context;
this.conversions = overloadResolution.conversions;
}
@ -409,26 +407,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ConstraintsValid = false;
break;
}
ITypeParameterConstraints constraints = tp.GetConstraints(context);
if (constraints.HasReferenceTypeConstraint) {
if (typeArg.IsReferenceType(context) != true)
if (tp.HasReferenceTypeConstraint) {
if (typeArg.IsReferenceType != true)
ConstraintsValid = false;
}
if (constraints.HasValueTypeConstraint) {
if (!NullableType.IsNonNullableValueType(typeArg, context))
if (tp.HasValueTypeConstraint) {
if (!NullableType.IsNonNullableValueType(typeArg))
ConstraintsValid = false;
}
if (constraints.HasDefaultConstructorConstraint) {
if (tp.HasDefaultConstructorConstraint) {
ITypeDefinition def = typeArg.GetDefinition();
if (def != null && def.IsAbstract)
ConstraintsValid = false;
ConstraintsValid &= typeArg.GetConstructors(
context,
m => m.Parameters.Count == 0 && m.Accessibility == Accessibility.Public,
GetMemberOptions.IgnoreInheritedMembers | GetMemberOptions.ReturnMemberDefinitions
).Any();
}
foreach (IType constraintType in constraints) {
foreach (IType constraintType in tp.DirectBaseTypes) {
IType c = constraintType.AcceptVisitor(newParameterizedType.GetSubstitution());
ConstraintsValid &= conversions.IsConstraintConvertible(typeArg, c);
}
@ -593,8 +589,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (r > 0) return 1;
else if (r < 0) return 2;
return MoreSpecificFormalParameters(c1.Parameters.Select(p => p.Type.Resolve(context)),
c2.Parameters.Select(p => p.Type.Resolve(context)));
return MoreSpecificFormalParameters(c1.Parameters.Select(p => p.Type), c2.Parameters.Select(p => p.Type));
}
static int MoreSpecificFormalParameters(IEnumerable<IType> t1, IEnumerable<IType> t2)
@ -745,7 +740,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (parameterIndex >= 0)
parameterType = bestCandidate.ParameterTypes[parameterIndex];
else
parameterType = SharedTypes.UnknownType;
parameterType = SpecialType.UnknownType;
args[i] = new ConversionResolveResult(parameterType, arguments[i], conversions[i]);
}
}
@ -773,7 +768,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return new CSharpInvocationResolveResult(
targetResolveResult,
member,
member.EntityType == EntityType.Constructor ? member.DeclaringType : member.ReturnType.Resolve(context),
GetArgumentsWithConversions(),
this.BestCandidateErrors,
this.IsExtensionMethodInvocation,

Просмотреть файл

@ -18,6 +18,7 @@
using System;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
@ -29,7 +30,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary>
public static class ResolveAtLocation
{
public static ResolveResult Resolve(ITypeResolveContext context, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location,
public static ResolveResult Resolve(ICompilation compilation, CSharpParsedFile parsedFile, CompilationUnit cu, TextLocation location,
CancellationToken cancellationToken = default(CancellationToken))
{
AstNode node = cu.GetNodeAt(location);
@ -39,7 +40,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (node is AstType) {
resolvableNode = node;
if (resolvableNode.Parent is ComposedType) {
while (resolvableNode.Parent is ComposedType)
while (resolvableNode.Parent is ComposedType)
resolvableNode = resolvableNode.Parent;
//node is preffered over the resolvable node. Which shouldn't be done in the case of nullables, arrays etc.
node = resolvableNode;
@ -69,6 +70,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
else
navigator = new NodeListResolveVisitorNavigator(new[] { resolvableNode });
throw new NotImplementedException();
/*
using (var ctx = context.Synchronize()) {
CSharpResolver resolver = new CSharpResolver(ctx, cancellationToken);
ResolveVisitor v = new ResolveVisitor(resolver, parsedFile, navigator);
@ -81,7 +84,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return v.GetResolveResult(parentInvocation);
else
return rr;
}
}*/
}
}
}

Просмотреть файл

@ -22,7 +22,7 @@ using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
@ -57,7 +57,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// The ResolveVisitor is also responsible for handling lambda expressions.
static readonly ResolveResult errorResult = ErrorResolveResult.UnknownError;
static readonly ResolveResult transparentIdentifierResolveResult = new ResolveResult(SharedTypes.UnboundTypeArgument);
static readonly ResolveResult transparentIdentifierResolveResult = new ResolveResult(SpecialType.UnboundTypeArgument);
readonly ResolveResult voidResult;
CSharpResolver resolver;
@ -71,6 +71,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
IResolveVisitorNavigator navigator;
bool resolverEnabled;
List<LambdaBase> undecidedLambdas;
internal CancellationToken cancellationToken;
#region Constructor
/// <summary>
@ -98,23 +99,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
this.resolver = resolver;
this.parsedFile = parsedFile;
this.navigator = navigator ?? new ConstantModeResolveVisitorNavigator(ResolveVisitorNavigationMode.Skip, null);
this.voidResult = new ResolveResult(KnownTypeReference.Void.Resolve(resolver.Context));
}
#endregion
#region Properties
/// <summary>
/// Gets the TypeResolveContext used by this ResolveVisitor.
/// </summary>
public ITypeResolveContext TypeResolveContext {
get { return resolver.Context; }
}
/// <summary>
/// Gets the CancellationToken used by this ResolveVisitor.
/// </summary>
public CancellationToken CancellationToken {
get { return resolver.cancellationToken; }
this.voidResult = new ResolveResult(resolver.Compilation.FindType(KnownTypeCode.Void));
}
#endregion
@ -214,7 +199,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
resolverEnabled = true;
ResolveResult result;
if (!resolveResultCache.TryGetValue(node, out result)) {
resolver.cancellationToken.ThrowIfCancellationRequested();
cancellationToken.ThrowIfCancellationRequested();
StoreCurrentState(node);
result = node.AcceptVisitor(this, null) ?? errorResult;
Log.WriteLine("Resolved '{0}' to {1}", node, result);
@ -502,8 +487,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// merge undecided lambdas before leaving the using scope so that
// the resolver can make better use of its cache
MergeUndecidedLambdas();
if (resolver.CurrentUsingScope != null)
return new NamespaceResolveResult(resolver.CurrentUsingScope.NamespaceName);
if (resolver.CurrentUsingScope != null && resolverEnabled)
return new NamespaceResolveResult(resolver.CurrentUsingScope.ResolveNamespace(resolver.Compilation));
else
return null;
} finally {
@ -513,20 +498,23 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
#endregion
#region Track CurrentTypeDefinition
ResolveResult VisitTypeOrDelegate(AstNode typeDeclaration)
ResolveResult VisitTypeOrDelegate(AstNode typeDeclaration, string name, int typeParameterCount)
{
ITypeDefinition previousTypeDefinition = resolver.CurrentTypeDefinition;
try {
ITypeDefinition newTypeDefinition = null;
if (resolver.CurrentTypeDefinition != null) {
int totalTypeParameterCount = resolver.CurrentTypeDefinition.TypeParameterCount;
foreach (ITypeDefinition nestedType in resolver.CurrentTypeDefinition.NestedTypes) {
if (nestedType.Region.IsInside(typeDeclaration.StartLocation)) {
if (nestedType.Name == name && nestedType.TypeParameterCount == totalTypeParameterCount) {
newTypeDefinition = nestedType;
break;
}
}
} else if (parsedFile != null) {
newTypeDefinition = parsedFile.GetTopLevelTypeDefinition(typeDeclaration.StartLocation);
} else if (resolver.CurrentUsingScope != null) {
INamespace ns = resolver.CurrentUsingScope.ResolveNamespace(resolver.Compilation);
if (ns != null)
newTypeDefinition = ns.GetTypeDefinition(name, typeParameterCount);
}
if (newTypeDefinition != null)
resolver.CurrentTypeDefinition = newTypeDefinition;
@ -553,12 +541,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
{
return VisitTypeOrDelegate(typeDeclaration);
return VisitTypeOrDelegate(typeDeclaration, typeDeclaration.Name, typeDeclaration.TypeParameters.Count);
}
ResolveResult IAstVisitor<object, ResolveResult>.VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data)
{
return VisitTypeOrDelegate(delegateDeclaration);
return VisitTypeOrDelegate(delegateDeclaration, delegateDeclaration.Name, delegateDeclaration.TypeParameters.Count);
}
#endregion
@ -583,14 +571,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
int initializerCount = fieldOrEventDeclaration.GetChildrenByRole(FieldDeclaration.Roles.Variable).Count;
for (AstNode node = fieldOrEventDeclaration.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == FieldDeclaration.Roles.Variable) {
if (resolver.CurrentTypeDefinition != null) {
IEnumerable<IMember> members;
if (fieldOrEventDeclaration is EventDeclaration)
members = resolver.CurrentTypeDefinition.Events;
else
members = resolver.CurrentTypeDefinition.Fields;
resolver.CurrentMember = members.FirstOrDefault(f => f.Region.IsInside(node.StartLocation));
}
resolver.CurrentMember = GetMemberFromLocation(node.StartLocation);
Scan(node);
@ -602,6 +583,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return voidResult;
}
IMember GetMemberFromLocation(TextLocation location)
{
throw new NotImplementedException();
}
ResolveResult IAstVisitor<object, ResolveResult>.VisitVariableInitializer(VariableInitializer variableInitializer, object data)
{
ArrayInitializerExpression aie = variableInitializer.Initializer as ArrayInitializerExpression;
@ -609,14 +595,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult result = errorResult;
if (variableInitializer.Parent is FieldDeclaration || variableInitializer.Parent is EventDeclaration) {
if (resolver.CurrentMember != null) {
result = new MemberResolveResult(null, resolver.CurrentMember, resolver.CurrentMember.ReturnType.Resolve(resolver.Context));
result = new MemberResolveResult(null, resolver.CurrentMember);
}
} else {
string identifier = variableInitializer.Name;
foreach (IVariable v in resolver.LocalVariables) {
if (v.Name == identifier) {
object constantValue = v.IsConst ? v.ConstantValue.Resolve(resolver.Context).ConstantValue : null;
result = new LocalResolveResult(v, v.Type.Resolve(resolver.Context), constantValue);
result = new LocalResolveResult(v);
break;
}
}
@ -648,9 +633,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (resolverEnabled) {
ResolveResult result = errorResult;
if (resolver.CurrentMember != null) {
result = new MemberResolveResult(null, resolver.CurrentMember, resolver.CurrentMember.ReturnType.Resolve(resolver.Context));
result = new MemberResolveResult(null, resolver.CurrentMember);
}
ResolveAndProcessConversion(fixedVariableInitializer.CountExpression, KnownTypeReference.Int32.Resolve(resolver.Context));
ResolveAndProcessConversion(fixedVariableInitializer.CountExpression, resolver.Compilation.FindType(KnownTypeCode.Int32));
return result;
} else {
ScanChildren(fixedVariableInitializer);
@ -661,14 +646,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult VisitMethodMember(AttributedNode member)
{
try {
if (resolver.CurrentTypeDefinition != null) {
resolver.CurrentMember = resolver.CurrentTypeDefinition.Methods.FirstOrDefault(m => m.Region.IsInside(member.StartLocation));
}
resolver.CurrentMember = GetMemberFromLocation(member.StartLocation);
ScanChildren(member);
if (resolverEnabled && resolver.CurrentMember != null)
return new MemberResolveResult(null, resolver.CurrentMember, resolver.Context);
return new MemberResolveResult(null, resolver.CurrentMember);
else
return errorResult;
} finally {
@ -700,14 +683,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult VisitPropertyMember(MemberDeclaration propertyOrIndexerDeclaration)
{
try {
if (resolver.CurrentTypeDefinition != null) {
resolver.CurrentMember = resolver.CurrentTypeDefinition.Properties.FirstOrDefault(p => p.Region.IsInside(propertyOrIndexerDeclaration.StartLocation));
}
resolver.CurrentMember = GetMemberFromLocation(propertyOrIndexerDeclaration.StartLocation);
for (AstNode node = propertyOrIndexerDeclaration.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == PropertyDeclaration.SetterRole && resolver.CurrentMember != null) {
resolver.PushBlock();
resolver.AddVariable(resolver.CurrentMember.ReturnType, DomRegion.Empty, "value");
resolver.AddVariable(new DefaultParameter(resolver.CurrentMember.ReturnType, "value"));
Scan(node);
resolver.PopBlock();
} else {
@ -715,7 +696,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
}
if (resolverEnabled && resolver.CurrentMember != null)
return new MemberResolveResult(null, resolver.CurrentMember, resolver.Context);
return new MemberResolveResult(null, resolver.CurrentMember);
else
return errorResult;
} finally {
@ -736,13 +717,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration, object data)
{
try {
if (resolver.CurrentTypeDefinition != null) {
resolver.CurrentMember = resolver.CurrentTypeDefinition.Events.FirstOrDefault(e => e.Region.IsInside(eventDeclaration.StartLocation));
}
resolver.CurrentMember = GetMemberFromLocation(eventDeclaration.StartLocation);
if (resolver.CurrentMember != null) {
resolver.PushBlock();
resolver.AddVariable(resolver.CurrentMember.ReturnType, DomRegion.Empty, "value");
resolver.AddVariable(new DefaultParameter(resolver.CurrentMember.ReturnType, "value"));
ScanChildren(eventDeclaration);
resolver.PopBlock();
} else {
@ -750,7 +729,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
if (resolverEnabled && resolver.CurrentMember != null)
return new MemberResolveResult(null, resolver.CurrentMember, resolver.Context);
return new MemberResolveResult(null, resolver.CurrentMember);
else
return errorResult;
} finally {
@ -766,14 +745,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// Look in lambda parameters:
foreach (IParameter p in resolver.LocalVariables.OfType<IParameter>()) {
if (p.Name == name)
return new LocalResolveResult(p, p.Type.Resolve(resolver.Context));
return new LocalResolveResult(p);
}
IParameterizedMember pm = resolver.CurrentMember as IParameterizedMember;
if (pm != null) {
foreach (IParameter p in pm.Parameters) {
if (p.Name == name) {
return new LocalResolveResult(p, p.Type.Resolve(resolver.Context));
return new LocalResolveResult(p);
}
}
}
@ -812,14 +791,12 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, object data)
{
try {
if (resolver.CurrentTypeDefinition != null) {
resolver.CurrentMember = resolver.CurrentTypeDefinition.Fields.FirstOrDefault(f => f.Region.IsInside(enumMemberDeclaration.StartLocation));
}
resolver.CurrentMember = GetMemberFromLocation(enumMemberDeclaration.StartLocation);
ScanChildren(enumMemberDeclaration);
if (resolverEnabled && resolver.CurrentMember != null)
return new MemberResolveResult(null, resolver.CurrentMember, resolver.Context);
return new MemberResolveResult(null, resolver.CurrentMember);
else
return errorResult;
} finally {
@ -910,6 +887,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitAnonymousTypeCreateExpression(AnonymousTypeCreateExpression anonymousTypeCreateExpression, object data)
{
// 7.6.10.6 Anonymous object creation expressions
throw new NotImplementedException();
/*
if (resolver.ProjectContent == null) {
ScanChildren(anonymousTypeCreateExpression);
return errorResult;
@ -931,7 +910,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
ScanChildren(anonymousTypeCreateExpression);
resolver.PopInitializerType();
return new ResolveResult(anonymousType);
return new ResolveResult(anonymousType);*/
}
ResolveResult IAstVisitor<object, ResolveResult>.VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data)
@ -986,7 +965,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
} else {
IType elementType = ResolveType(arrayCreateExpression.Type);
foreach (var spec in additionalArraySpecifiers.Reverse()) {
elementType = new ArrayType(elementType, spec.Dimensions);
elementType = new ArrayType(resolver.Compilation, elementType, spec.Dimensions);
}
acrr = resolver.ResolveArrayCreation(elementType, dimensions, sizeArguments, initializerElementResults);
}
@ -1169,7 +1148,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
ScanChildren(isExpression);
if (resolverEnabled)
return new ResolveResult(KnownTypeReference.Boolean.Resolve(resolver.Context));
return new ResolveResult(resolver.Compilation.FindType(KnownTypeCode.Boolean));
else
return null;
}
@ -1266,7 +1245,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
var addRR = memberLookup.Lookup(targetResult, "Add", EmptyList<IType>.Instance, true);
var mgrr = addRR as MethodGroupResolveResult;
if (mgrr != null) {
OverloadResolution or = mgrr.PerformOverloadResolution(resolver.Context, addArguments, null, false, false, resolver.conversions);
OverloadResolution or = mgrr.PerformOverloadResolution(resolver.Compilation, addArguments, null, false, false, resolver.conversions);
var invocationRR = or.CreateResolveResult(targetResult);
StoreResult(aie, invocationRR);
ProcessConversionsInInvocation(null, aie.Elements, invocationRR);
@ -1334,7 +1313,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitStackAllocExpression(StackAllocExpression stackAllocExpression, object data)
{
if (resolverEnabled) {
ResolveAndProcessConversion(stackAllocExpression.CountExpression, KnownTypeReference.Int32.Resolve(resolver.Context));
ResolveAndProcessConversion(stackAllocExpression.CountExpression, resolver.Compilation.FindType(KnownTypeCode.Int32));
return new ResolveResult(new PointerType(ResolveType(stackAllocExpression.Type)));
} else {
ScanChildren(stackAllocExpression);
@ -1354,7 +1333,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
ScanChildren(typeOfExpression);
if (resolverEnabled)
return new ResolveResult(KnownTypeReference.Type.Resolve(resolver.Context));
return new ResolveResult(KnownTypeReference.Type.Resolve(resolver.Compilation.TypeResolveContext));
else
return null;
}
@ -1395,29 +1374,29 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
ScanChildren(undocumentedExpression);
if (resolverEnabled) {
ITypeReference resultType;
IType resultType;
switch (undocumentedExpression.UndocumentedExpressionType) {
case UndocumentedExpressionType.ArgListAccess:
case UndocumentedExpressionType.ArgList:
resultType = typeof(RuntimeArgumentHandle).ToTypeReference();
resultType = resolver.Compilation.FindType(typeof(RuntimeArgumentHandle));
break;
case UndocumentedExpressionType.RefValue:
var tre = undocumentedExpression.Arguments.ElementAtOrDefault(1) as TypeReferenceExpression;
if (tre != null)
resultType = ResolveType(tre.Type);
else
resultType = SharedTypes.UnknownType;
resultType = SpecialType.UnknownType;
break;
case UndocumentedExpressionType.RefType:
resultType = KnownTypeReference.Type;
resultType = KnownTypeReference.Type.Resolve(resolver.Compilation.TypeResolveContext);
break;
case UndocumentedExpressionType.MakeRef:
resultType = typeof(TypedReference).ToTypeReference();
resultType = resolver.Compilation.FindType(typeof(TypedReference));
break;
default:
throw new InvalidOperationException("Invalid value for UndocumentedExpressionType");
}
return new ResolveResult(resultType.Resolve(resolver.Context));
return new ResolveResult(resultType);
} else {
return null;
}
@ -1658,15 +1637,18 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
AstNode body, bool isAnonymousMethod, bool hasParameterList, bool isAsync)
{
List<IParameter> parameters = new List<IParameter>();
resolver.PushLambdaBlock();
resolver.PushBlock();
bool oldIsWithinLambdaExpression = resolver.IsWithinLambdaExpression;
resolver.IsWithinLambdaExpression = true;
foreach (var pd in parameterDeclarations) {
ITypeReference type = MakeTypeReference(pd.Type);
IType type = ResolveType(pd.Type);
if (pd.ParameterModifier == ParameterModifier.Ref || pd.ParameterModifier == ParameterModifier.Out)
type = ByReferenceTypeReference.Create(type);
type = new ByReferenceType(type);
var p = resolver.AddLambdaParameter(type, MakeRegion(pd), pd.Name,
IParameter p = new DefaultParameter(type, pd.Name, MakeRegion(pd),
isRef: pd.ParameterModifier == ParameterModifier.Ref,
isOut: pd.ParameterModifier == ParameterModifier.Out);
resolver.AddVariable(p);
parameters.Add(p);
Scan(pd);
}
@ -1676,6 +1658,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// Don't scan the lambda body here - we'll do that later when analyzing the ExplicitlyTypedLambda.
resolver.PopBlock();
resolver.IsWithinLambdaExpression = oldIsWithinLambdaExpression;
return lambda;
}
@ -1838,7 +1821,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
internal override void EnforceMerge(ResolveVisitor parentVisitor)
{
ApplyReturnType(parentVisitor, SharedTypes.UnknownType);
ApplyReturnType(parentVisitor, SpecialType.UnknownType);
}
}
#endregion
@ -1897,9 +1880,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
this.lambda = lambda;
foreach (var pd in lambda.Parameters) {
parameters.Add(new DefaultParameter(SharedTypes.UnknownType, pd.Name) {
Region = parentVisitor.MakeRegion(pd)
});
parameters.Add(new DefaultParameter(SpecialType.UnknownType, pd.Name, parentVisitor.MakeRegion(pd)));
}
RegisterUndecidedLambda();
}
@ -1976,7 +1957,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// make a new hypothesis with unknown parameter types
IType[] parameterTypes = new IType[parameters.Count];
for (int i = 0; i < parameterTypes.Length; i++) {
parameterTypes[i] = SharedTypes.UnknownType;
parameterTypes[i] = SpecialType.UnknownType;
}
return GetHypothesis(parameterTypes);
} else {
@ -1998,7 +1979,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
internal override void EnforceMerge(ResolveVisitor parentVisitor)
{
GetAnyHypothesis().MergeInto(parentVisitor, SharedTypes.UnknownType);
GetAnyHypothesis().MergeInto(parentVisitor, SpecialType.UnknownType);
}
public override bool IsImplicitlyTyped {
@ -2055,24 +2036,29 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Log.WriteLine("Analyzing " + ToString() + "...");
Log.Indent();
visitor.resolver.PushLambdaBlock();
bool oldInsideLambda = visitor.resolver.IsWithinLambdaExpression;
visitor.resolver.PushBlock();
visitor.resolver.IsWithinLambdaExpression = true;
lambdaParameters = new IParameter[parameterTypes.Length];
if (parameterDeclarations != null) {
int i = 0;
foreach (var pd in parameterDeclarations) {
lambdaParameters[i] = visitor.resolver.AddLambdaParameter(parameterTypes[i], visitor.MakeRegion(pd), pd.Name);
lambdaParameters[i] = new DefaultParameter(parameterTypes[i], pd.Name, visitor.MakeRegion(pd));
visitor.resolver.AddVariable(lambdaParameters[i]);
i++;
visitor.Scan(pd);
}
} else {
for (int i = 0; i < parameterTypes.Length; i++) {
var p = lambda.Parameters[i];
lambdaParameters[i] = visitor.resolver.AddLambdaParameter(parameterTypes[i], p.Region, p.Name);
lambdaParameters[i] = new DefaultParameter(parameterTypes[i], p.Name, p.Region);
visitor.resolver.AddVariable(lambdaParameters[i]);
}
}
visitor.AnalyzeLambda(lambda.BodyExpression, lambda.IsAsync, out success, out isValidAsVoidMethod, out inferredReturnType, out returnExpressions, out returnValues);
visitor.resolver.PopBlock();
visitor.resolver.IsWithinLambdaExpression = false;
Log.Unindent();
Log.WriteLine("Finished analyzing " + ToString());
}
@ -2209,15 +2195,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
IType GetTaskType(IType resultType)
{
if (resultType.Kind == TypeKind.Unknown)
return SharedTypes.UnknownType;
return SpecialType.UnknownType;
if (resultType.Kind == TypeKind.Void)
return resolver.Context.GetTypeDefinition("System.Threading.Tasks", "Task", 0, StringComparer.Ordinal) ?? SharedTypes.UnknownType;
return KnownTypeReference.Task.Resolve(resolver.Compilation.TypeResolveContext);
ITypeDefinition def = resolver.Context.GetTypeDefinition("System.Threading.Tasks", "Task", 1, StringComparer.Ordinal);
ITypeDefinition def = KnownTypeReference.TaskOfT.Resolve(resolver.Compilation.TypeResolveContext).GetDefinition();
if (def != null)
return new ParameterizedType(def, new[] { resultType });
else
return SharedTypes.UnknownType;
return SpecialType.UnknownType;
}
void AnalyzeLambda(AstNode body, bool isAsync, out bool success, out bool isValidAsVoidMethod, out IType inferredReturnType, out IList<Expression> returnExpressions, out IList<ResolveResult> returnValues)
@ -2237,14 +2223,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (alv.HasVoidReturnStatements) {
returnExpressions = EmptyList<Expression>.Instance;
returnValues = EmptyList<ResolveResult>.Instance;
inferredReturnType = KnownTypeReference.Void.Resolve(resolver.Context);
inferredReturnType = resolver.Compilation.FindType(KnownTypeCode.Void);
} else {
returnExpressions = alv.ReturnExpressions;
returnValues = new ResolveResult[returnExpressions.Count];
for (int i = 0; i < returnValues.Count; i++) {
returnValues[i] = resolveResultCache[returnExpressions[i]];
}
TypeInference ti = new TypeInference(resolver.Context, resolver.conversions);
TypeInference ti = new TypeInference(resolver.Compilation, resolver.conversions);
bool tiSuccess;
inferredReturnType = ti.GetBestCommonType(returnValues, out tiSuccess);
// Failure to infer a return type does not make the lambda invalid,
@ -2316,7 +2302,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (!IsTask(type))
return type;
if (type.TypeParameterCount == 0)
return KnownTypeReference.Void.Resolve(resolver.Context);
return resolver.Compilation.FindType(KnownTypeCode.Void);
else
return ((ParameterizedType)type).GetTypeArgument(0);
}
@ -2380,9 +2366,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (resolverEnabled) {
for (AstNode child = usingStatement.FirstChild; child != null; child = child.NextSibling) {
if (child.Role == UsingStatement.ResourceAcquisitionRole && child is Expression) {
ITypeDefinition disposable = resolver.Context.GetTypeDefinition(
"System", "IDisposable", 0, StringComparer.Ordinal);
ResolveAndProcessConversion((Expression)child, disposable ?? SharedTypes.UnknownType);
ResolveAndProcessConversion((Expression)child, resolver.Compilation.FindType(KnownTypeCode.IDisposable));
} else {
Scan(child);
}
@ -2397,11 +2381,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitFixedStatement(FixedStatement fixedStatement, object data)
{
resolver.PushBlock();
ITypeReference type = MakeTypeReference(fixedStatement.Type);
AstType type = fixedStatement.Type;
for (AstNode node = fixedStatement.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == FixedStatement.Roles.Variable) {
VariableInitializer vi = (VariableInitializer)node;
resolver.AddVariable(type, MakeRegion(vi) , vi.Name);
resolver.AddVariable(MakeVariable(type, vi.NameToken));
}
Scan(node);
}
@ -2412,24 +2396,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitForeachStatement(ForeachStatement foreachStatement, object data)
{
resolver.PushBlock();
ITypeReference type;
IVariable v;
if (IsVar(foreachStatement.VariableType)) {
if (navigator.Scan(foreachStatement.VariableType) == ResolveVisitorNavigationMode.Resolve) {
IType collectionType = Resolve(foreachStatement.InExpression).Type;
IType elementType = GetElementType(collectionType, resolver.Context, false);
IType elementType = GetElementType(collectionType, resolver.Compilation, false);
StoreResult(foreachStatement.VariableType, new TypeResolveResult(elementType));
type = elementType;
v = MakeVariable(elementType, foreachStatement.VariableNameToken);
} else {
Scan(foreachStatement.InExpression);
type = MakeVarTypeReference(foreachStatement.InExpression, true);
v = MakeImplicitlyTypedVariable(foreachStatement.VariableNameToken, foreachStatement.InExpression, true);
}
} else {
Scan(foreachStatement.InExpression);
type = ResolveType(foreachStatement.VariableType);
v = MakeVariable(foreachStatement.VariableType, foreachStatement.VariableNameToken);
}
StoreCurrentState(foreachStatement.VariableNameToken);
IVariable v = resolver.AddVariable(type, MakeRegion(foreachStatement.VariableNameToken), foreachStatement.VariableName);
StoreResult(foreachStatement.VariableNameToken, new LocalResolveResult(v, v.Type.Resolve(resolver.Context)));
resolver.AddVariable(v);
StoreResult(foreachStatement.VariableNameToken, new LocalResolveResult(v));
Scan(foreachStatement.EmbeddedStatement);
resolver.PopBlock();
return voidResult;
@ -2447,11 +2431,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
resolver.PushBlock();
if (!string.IsNullOrEmpty(catchClause.VariableName)) {
ITypeReference variableType = MakeTypeReference(catchClause.Type);
DomRegion region = MakeRegion(catchClause.VariableNameToken);
StoreCurrentState(catchClause.VariableNameToken);
IVariable v = resolver.AddVariable(variableType, region, catchClause.VariableName);
StoreResult(catchClause.VariableNameToken, new LocalResolveResult(v, v.Type.Resolve(resolver.Context)));
IVariable v = MakeVariable(catchClause.Type, catchClause.VariableNameToken);
resolver.AddVariable(v);
StoreResult(catchClause.VariableNameToken, new LocalResolveResult(v));
}
ScanChildren(catchClause);
resolver.PopBlock();
@ -2468,38 +2452,38 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
bool needResolve = resolverEnabled
|| navigator.Scan(variableDeclarationStatement.Type) == ResolveVisitorNavigationMode.Resolve
|| navigator.Scan(vi) == ResolveVisitorNavigationMode.Resolve;
ITypeReference type;
IVariable v;
if (needResolve) {
StoreCurrentState(variableDeclarationStatement.Type);
type = Resolve(vi.Initializer).Type;
IType type = Resolve(vi.Initializer).Type;
if (!resolveResultCache.ContainsKey(variableDeclarationStatement.Type)) {
StoreResult(variableDeclarationStatement.Type, new TypeResolveResult(type.Resolve(resolver.Context)));
StoreResult(variableDeclarationStatement.Type, new TypeResolveResult(type));
}
v = MakeVariable(type, vi.NameToken);
} else {
Scan(vi.Initializer);
type = MakeVarTypeReference(vi.Initializer, false);
v = MakeImplicitlyTypedVariable(vi.NameToken, vi.Initializer, false);
}
IVariable v = resolver.AddVariable(type, MakeRegion(vi), vi.Name);
StoreCurrentState(vi);
resolver.AddVariable(v);
if (needResolve) {
ResolveResult result;
if (!resolveResultCache.TryGetValue(vi, out result)) {
result = new LocalResolveResult(v, type.Resolve(resolver.Context));
StoreResult(vi, result);
StoreResult(vi, new LocalResolveResult(v));
}
}
} else {
ITypeReference type = MakeTypeReference(variableDeclarationStatement.Type);
AstType type = variableDeclarationStatement.Type;
for (AstNode node = variableDeclarationStatement.FirstChild; node != null; node = node.NextSibling) {
if (node.Role == VariableDeclarationStatement.Roles.Variable) {
VariableInitializer vi = (VariableInitializer)node;
IConstantValue cv = null;
if (isConst) {
cv = TypeSystemConvertVisitor.ConvertConstantValue(type, vi.Initializer, resolver.CurrentTypeDefinition, resolver.CurrentMember as IMethod, resolver.CurrentUsingScope);
resolver.AddVariable(MakeConstant(type, vi.NameToken, vi.Initializer));
} else {
resolver.AddVariable(MakeVariable(type, vi.NameToken));
}
resolver.AddVariable(type, MakeRegion(vi), vi.Name, cv);
}
Scan(node);
}
@ -2540,7 +2524,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (resolverEnabled) {
for (AstNode child = conditionStatement.FirstChild; child != null; child = child.NextSibling) {
if (child.Role == AstNode.Roles.Condition) {
ResolveAndProcessConversion((Expression)child, KnownTypeReference.Boolean.Resolve(resolver.Context));
ResolveAndProcessConversion((Expression)child, resolver.Compilation.FindType(KnownTypeCode.Boolean));
} else {
Scan(child);
}
@ -2555,7 +2539,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitReturnStatement(ReturnStatement returnStatement, object data)
{
if (resolverEnabled && !resolver.IsWithinLambdaExpression && resolver.CurrentMember != null) {
IType type = resolver.CurrentMember.ReturnType.Resolve(resolver.Context);
IType type = resolver.CurrentMember.ReturnType;
if (IsTask(type)) {
var methodDecl = returnStatement.Ancestors.OfType<AttributedNode>().FirstOrDefault();
if (methodDecl != null && (methodDecl.Modifiers & Modifiers.Async) == Modifiers.Async)
@ -2571,8 +2555,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitYieldReturnStatement(YieldReturnStatement yieldStatement, object data)
{
if (resolverEnabled && resolver.CurrentMember != null) {
IType returnType = resolver.CurrentMember.ReturnType.Resolve(resolver.Context);
IType elementType = GetElementType(returnType, resolver.Context, true);
IType returnType = resolver.CurrentMember.ReturnType;
IType elementType = GetElementType(returnType, resolver.Compilation, true);
ResolveAndProcessConversion(yieldStatement.Expression, elementType);
} else {
Scan(yieldStatement.Expression);
@ -2660,14 +2644,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return st != null && st.Identifier == "var" && st.TypeArguments.Count == 0;
}
ITypeReference MakeTypeReference(AstType type)
IVariable MakeVariable(IType type, Identifier variableName)
{
return TypeSystemConvertVisitor.ConvertType(type, resolver.CurrentTypeDefinition, resolver.CurrentMember as IMethod, resolver.CurrentUsingScope, currentTypeLookupMode);
throw new NotImplementedException();
}
ITypeReference MakeVarTypeReference(Expression initializer, bool isForEach)
IVariable MakeVariable(AstType type, Identifier variableName)
{
return new VarTypeReference(this, resolver.Clone(), initializer, isForEach);
throw new NotImplementedException();
}
IVariable MakeConstant(AstType type, Identifier variableName, Expression initializer)
{
throw new NotImplementedException();
}
IVariable MakeImplicitlyTypedVariable(Identifier variableName, Expression initializer, bool isForEach)
{
throw new NotImplementedException();
}
sealed class VarTypeReference : ITypeReference
@ -2690,7 +2684,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public IType Resolve(ITypeResolveContext context)
{
if (visitor == null)
return result ?? SharedTypes.UnknownType;
return result ?? SpecialType.UnknownType;
visitor.ResetContext(
storedContext,
@ -2698,7 +2692,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
result = visitor.Resolve(initializerExpression).Type;
if (isForEach) {
result = GetElementType(result, storedContext.Context, false);
result = GetElementType(result, storedContext.Compilation, false);
}
});
visitor = null;
@ -2716,28 +2710,27 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
}
static IType GetElementType(IType result, ITypeResolveContext context, bool allowIEnumerator)
static IType GetElementType(IType result, ICompilation compilation, bool allowIEnumerator)
{
bool foundSimpleIEnumerable = false;
foreach (IType baseType in result.GetAllBaseTypes(context)) {
bool foundNonGenericIEnumerable = false;
foreach (IType baseType in result.GetAllBaseTypes()) {
ITypeDefinition baseTypeDef = baseType.GetDefinition();
if (baseTypeDef != null && (
baseTypeDef.Name == "IEnumerable" || (allowIEnumerator && baseType.Name == "IEnumerator")))
{
if (baseTypeDef.Namespace == "System.Collections.Generic" && baseTypeDef.TypeParameterCount == 1) {
if (baseTypeDef != null) {
KnownTypeCode typeCode = baseTypeDef.KnownTypeCode;
if (typeCode == KnownTypeCode.IEnumerableOfT || (allowIEnumerator && typeCode == KnownTypeCode.IEnumeratorOfT)) {
ParameterizedType pt = baseType as ParameterizedType;
if (pt != null) {
return pt.GetTypeArgument(0);
}
} else if (baseTypeDef.Namespace == "System.Collections" && baseTypeDef.TypeParameterCount == 0) {
foundSimpleIEnumerable = true;
}
if (typeCode == KnownTypeCode.IEnumerable || (allowIEnumerator && typeCode == KnownTypeCode.IEnumerator))
foundNonGenericIEnumerable = true;
}
}
// System.Collections.IEnumerable found in type hierarchy -> Object is element type.
if (foundSimpleIEnumerable)
return KnownTypeReference.Object.Resolve(context);
return SharedTypes.UnknownType;
if (foundNonGenericIEnumerable)
return compilation.FindType(KnownTypeCode.Object);
return SpecialType.UnknownType;
}
#endregion
@ -2805,21 +2798,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
if (!resolverEnabled)
return null;
IType type = MakeTypeReference(primitiveType).Resolve(resolver.Context);
if (type.Kind != TypeKind.Unknown)
return new TypeResolveResult(type);
else
return errorResult;
KnownTypeCode typeCode = TypeSystemConvertVisitor.GetTypeCodeForPrimitiveType(primitiveType.Keyword);
IType type = resolver.Compilation.FindType(typeCode);
return new TypeResolveResult(type);
}
ResolveResult HandleAttributeType(AstType astType)
{
ScanChildren(astType);
IType type = TypeSystemConvertVisitor.ConvertAttributeType(astType, resolver.CurrentTypeDefinition, resolver.CurrentMember as IMethod, resolver.CurrentUsingScope).Resolve(resolver.Context);
if (type.Kind != TypeKind.Unknown)
return new TypeResolveResult(type);
else
return errorResult;
throw new NotImplementedException();
}
ResolveResult IAstVisitor<object, ResolveResult>.VisitSimpleType(SimpleType simpleType, object data)
@ -2867,13 +2853,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
IType t = ResolveType(composedType.BaseType);
if (composedType.HasNullableSpecifier) {
t = NullableType.Create(t, resolver.Context);
t = NullableType.Create(resolver.Compilation, t);
}
for (int i = 0; i < composedType.PointerRank; i++) {
t = new PointerType(t);
}
foreach (var a in composedType.ArraySpecifiers.Reverse()) {
t = new ArrayType(t, a.Dimensions);
t = new ArrayType(resolver.Compilation, t, a.Dimensions);
}
return new TypeResolveResult(t);
}
@ -2900,7 +2886,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
// This assumes queries are only used on IEnumerable.
// We might want to look at the signature of a LINQ method (e.g. Select) instead.
return GetElementType(type, resolver.Context, false);
return GetElementType(type, resolver.Compilation, false);
}
sealed class QueryExpressionLambda : LambdaResolveResult
@ -2914,7 +2900,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
this.parameters = new IParameter[parameterCount];
for (int i = 0; i < parameterCount; i++) {
parameters[i] = new DefaultParameter(SharedTypes.UnknownType, "x" + i);
parameters[i] = new DefaultParameter(SpecialType.UnknownType, "x" + i);
}
this.bodyExpression = bodyExpression;
}
@ -2986,23 +2972,22 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
ResolveResult result = null;
ResolveResult expr = Resolve(queryFromClause.Expression);
IType variableType;
IVariable v;
if (queryFromClause.Type.IsNull) {
variableType = GetTypeForQueryVariable(expr.Type);
v = MakeVariable(GetTypeForQueryVariable(expr.Type), queryFromClause.IdentifierToken);
result = expr;
} else {
variableType = ResolveType(queryFromClause.Type);
v = MakeVariable(ResolveType(queryFromClause.Type), queryFromClause.IdentifierToken);
if (resolverEnabled) {
// resolve the .Cast<>() call
ResolveResult methodGroup = resolver.ResolveMemberAccess(expr, "Cast", new[] { variableType }, true);
ResolveResult methodGroup = resolver.ResolveMemberAccess(expr, "Cast", new[] { v.Type }, true);
result = resolver.ResolveInvocation(methodGroup, new ResolveResult[0]);
}
}
StoreCurrentState(queryFromClause.IdentifierToken);
DomRegion region = MakeRegion(queryFromClause.IdentifierToken);
IVariable v = resolver.AddVariable(variableType, region, queryFromClause.Identifier);
StoreResult(queryFromClause.IdentifierToken, new LocalResolveResult(v, variableType));
resolver.AddVariable(v);
StoreResult(queryFromClause.IdentifierToken, new LocalResolveResult(v));
if (resolverEnabled && currentQueryResult != null) {
// this is a second 'from': resolve the .SelectMany() call
@ -3029,20 +3014,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
ResolveResult rr = Resolve(queryContinuationClause.PrecedingQuery);
IType variableType = GetTypeForQueryVariable(rr.Type);
DomRegion region = MakeRegion(queryContinuationClause.IdentifierToken);
StoreCurrentState(queryContinuationClause.IdentifierToken);
IVariable v = resolver.AddVariable(variableType, region, queryContinuationClause.Identifier);
StoreResult(queryContinuationClause.IdentifierToken, new LocalResolveResult(v, variableType));
IVariable v = MakeVariable(variableType, queryContinuationClause.IdentifierToken);
resolver.AddVariable(v);
StoreResult(queryContinuationClause.IdentifierToken, new LocalResolveResult(v));
return rr;
}
ResolveResult IAstVisitor<object, ResolveResult>.VisitQueryLetClause(QueryLetClause queryLetClause, object data)
{
ResolveResult expr = Resolve(queryLetClause.Expression);
DomRegion region = MakeRegion(queryLetClause.IdentifierToken);
StoreCurrentState(queryLetClause.IdentifierToken);
IVariable v = resolver.AddVariable(expr.Type, region, queryLetClause.Identifier);
StoreResult(queryLetClause.IdentifierToken, new LocalResolveResult(v, expr.Type));
IVariable v = MakeVariable(expr.Type, queryLetClause.IdentifierToken);
resolver.AddVariable(v);
StoreResult(queryLetClause.IdentifierToken, new LocalResolveResult(v));
if (resolverEnabled && currentQueryResult != null) {
// resolve the .Select() call
ResolveResult methodGroup = resolver.ResolveMemberAccess(currentQueryResult, "Select", EmptyList<IType>.Instance, true);
@ -3078,19 +3063,19 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// scan the 'Equals' expression in a context that contains only the variable 'v'
CSharpResolver resolverOutsideQuery = resolver.Clone();
resolverOutsideQuery.PopBlock(); // pop all variables from the current query expression
DomRegion joinIdentifierRegion = MakeRegion(queryJoinClause.JoinIdentifierToken);
IVariable v = resolverOutsideQuery.AddVariable(variableType, joinIdentifierRegion, queryJoinClause.JoinIdentifier);
IVariable v = MakeVariable(variableType, queryJoinClause.JoinIdentifierToken);
resolverOutsideQuery.AddVariable(v);
ResolveResult equalsResult = errorResult;
ResetContext(resolverOutsideQuery, delegate {
equalsResult = Resolve(queryJoinClause.EqualsExpression);
});
StoreCurrentState(queryJoinClause.JoinIdentifierToken);
StoreResult(queryJoinClause.JoinIdentifierToken, new LocalResolveResult(v, variableType));
StoreResult(queryJoinClause.JoinIdentifierToken, new LocalResolveResult(v));
if (queryJoinClause.IsGroupJoin) {
return ResolveGroupJoin(queryJoinClause, inResult, onResult, equalsResult);
} else {
resolver.AddVariable(variableType, joinIdentifierRegion, queryJoinClause.JoinIdentifier);
resolver.AddVariable(v);
if (resolverEnabled && currentQueryResult != null) {
QuerySelectClause selectClause = GetNextQueryClause(queryJoinClause) as QuerySelectClause;
ResolveResult selectResult;
@ -3132,10 +3117,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (selectClause != null) {
// from ... join ... into g select - the GroupJoin call also performs the Select operation
IParameter[] selectLambdaParameters = {
new DefaultParameter(SharedTypes.UnknownType, "<>transparentIdentifier"),
new DefaultParameter(SharedTypes.UnknownType, queryJoinClause.IntoIdentifier) {
Region = intoIdentifierRegion
}
new DefaultParameter(SpecialType.UnknownType, "<>transparentIdentifier"),
new DefaultParameter(SpecialType.UnknownType, queryJoinClause.IntoIdentifier, region: intoIdentifierRegion)
};
groupJoinLambda = new ImplicitlyTypedLambda(selectClause, selectLambdaParameters, this);
} else {
@ -3191,15 +3174,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (inferredParameterTypes != null && inferredParameterTypes.Length == 2)
groupParameterType = inferredParameterTypes[1];
else
groupParameterType = SharedTypes.UnknownType;
groupParameterType = SpecialType.UnknownType;
StoreCurrentState(queryJoinClause.IntoIdentifierToken);
groupVariable = resolver.AddVariable(groupParameterType, intoIdentifierRegion, queryJoinClause.IntoIdentifier);
groupVariable = MakeVariable(groupParameterType, queryJoinClause.IntoIdentifierToken);
resolver.AddVariable(groupVariable);
}
if (groupVariable != null) {
LocalResolveResult lrr = new LocalResolveResult(groupVariable, groupVariable.Type.Resolve(resolver.Context));
StoreResult(queryJoinClause.IntoIdentifierToken, lrr);
StoreResult(queryJoinClause.IntoIdentifierToken, new LocalResolveResult(groupVariable));
}
return rr;
@ -3208,7 +3190,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
ResolveResult IAstVisitor<object, ResolveResult>.VisitQueryWhereClause(QueryWhereClause queryWhereClause, object data)
{
ResolveResult condition = Resolve(queryWhereClause.Condition);
IType boolType = KnownTypeReference.Boolean.Resolve(resolver.Context);
IType boolType = resolver.Compilation.FindType(KnownTypeCode.Boolean);
Conversion conversionToBool = resolver.conversions.ImplicitConversion(condition, boolType);
ProcessConversion(queryWhereClause.Condition, condition, conversionToBool, boolType);
if (resolverEnabled && currentQueryResult != null) {

Просмотреть файл

@ -49,7 +49,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary>
public sealed class TypeInference
{
readonly ITypeResolveContext context;
readonly ICompilation compilation;
readonly Conversions conversions;
TypeInferenceAlgorithm algorithm = TypeInferenceAlgorithm.CSharp4;
@ -58,12 +58,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
int nestingLevel;
#region Constructor
public TypeInference(ITypeResolveContext context, Conversions conversions = null)
public TypeInference(ICompilation compilation)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.conversions = conversions ?? Conversions.Get(context);
if (compilation == null)
throw new ArgumentNullException("compilation");
this.compilation = compilation;
this.conversions = Conversions.Get(compilation);
}
internal TypeInference(ICompilation compilation, Conversions conversions)
{
Debug.Assert(compilation != null);
Debug.Assert(conversions != null);
this.compilation = compilation;
this.conversions = conversions;
}
#endregion
@ -78,7 +86,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
TypeInference CreateNestedInstance()
{
TypeInference c = new TypeInference(context, conversions);
TypeInference c = new TypeInference(compilation, conversions);
c.algorithm = algorithm;
c.nestingLevel = nestingLevel + 1;
return c;
@ -141,8 +149,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Log.Unindent();
Log.WriteLine(" Type inference finished " + (success ? "successfully" : "with errors") + ": " +
"M<" + string.Join(", ", this.typeParameters.Select(tp => tp.FixedTo ?? SharedTypes.UnknownType)) + ">");
return this.typeParameters.Select(tp => tp.FixedTo ?? SharedTypes.UnknownType).ToArray();
"M<" + string.Join(", ", this.typeParameters.Select(tp => tp.FixedTo ?? SpecialType.UnknownType)) + ">");
return this.typeParameters.Select(tp => tp.FixedTo ?? SpecialType.UnknownType).ToArray();
} finally {
Reset();
}
@ -188,7 +196,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
success = true;
for (int i = 0; i < result.Length; i++) {
success &= Fix(this.typeParameters[i]);
result[i] = this.typeParameters[i].FixedTo ?? SharedTypes.UnknownType;
result[i] = this.typeParameters[i].FixedTo ?? SpecialType.UnknownType;
}
Reset();
return result;
@ -264,7 +272,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
IType U = Ei.Type;
if (U != SharedTypes.UnknownType) {
if (U != SpecialType.UnknownType) {
if (Ti is ByReferenceType) {
MakeExactInference(Ei.Type, Ti);
} else {
@ -348,7 +356,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (m != null) {
IType[] inputTypes = new IType[m.Parameters.Count];
for (int i = 0; i < inputTypes.Length; i++) {
inputTypes[i] = m.Parameters[i].Type.Resolve(context);
inputTypes[i] = m.Parameters[i].Type;
}
return inputTypes;
}
@ -363,7 +371,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (lrr != null && lrr.IsImplicitlyTyped || e is MethodGroupResolveResult) {
IMethod m = GetDelegateOrExpressionTreeSignature(t);
if (m != null) {
return new[] { m.ReturnType.Resolve(context) };
return new[] { m.ReturnType };
}
}
return emptyTypeArray;
@ -465,14 +473,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
TypeParameterSubstitution substitution = GetSubstitutionForFixedTPs();
IType[] inferredParameterTypes = new IType[m.Parameters.Count];
for (int i = 0; i < inferredParameterTypes.Length; i++) {
IType parameterType = m.Parameters[i].Type.Resolve(context);
IType parameterType = m.Parameters[i].Type;
inferredParameterTypes[i] = parameterType.AcceptVisitor(substitution);
}
inferredReturnType = lrr.GetInferredReturnType(inferredParameterTypes);
} else {
inferredReturnType = lrr.GetInferredReturnType(null);
}
MakeLowerBoundInference(inferredReturnType, m.ReturnType.Resolve(context));
MakeLowerBoundInference(inferredReturnType, m.ReturnType);
return;
}
}
@ -488,8 +496,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
TypeParameterSubstitution substitution = GetSubstitutionForFixedTPs();
for (int i = 0; i < args.Length; i++) {
IParameter param = m.Parameters[i];
IType parameterType = param.Type.Resolve(context);
parameterType = parameterType.AcceptVisitor(substitution);
IType parameterType = param.Type.AcceptVisitor(substitution);
if ((param.IsRef || param.IsOut) && parameterType.Kind == TypeKind.ByReference) {
parameterType = ((ByReferenceType)parameterType).ElementType;
args[i] = new ByReferenceResolveResult(parameterType, param.IsOut);
@ -497,18 +504,19 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
args[i] = new ResolveResult(parameterType);
}
}
var or = mgrr.PerformOverloadResolution(context, args,
var or = mgrr.PerformOverloadResolution(compilation,
args,
allowExtensionMethods: false,
allowExpandingParams: false);
if (or.FoundApplicableCandidate && or.BestCandidateAmbiguousWith == null) {
IType returnType = or.BestCandidate.ReturnType.Resolve(context);
MakeLowerBoundInference(returnType, m.ReturnType.Resolve(context));
IType returnType = or.BestCandidate.ReturnType;
MakeLowerBoundInference(returnType, m.ReturnType);
}
}
return;
}
// Otherwise, if E is an expression with type U, then a lower-bound inference is made from U to T.
if (e.Type != SharedTypes.UnknownType) {
if (e.Type != SpecialType.UnknownType) {
MakeLowerBoundInference(e.Type, t);
}
}
@ -517,7 +525,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
IType[] fixedTypes = new IType[typeParameters.Length];
for (int i = 0; i < fixedTypes.Length; i++) {
fixedTypes[i] = typeParameters[i].FixedTo ?? SharedTypes.UnknownType;
fixedTypes[i] = typeParameters[i].FixedTo ?? SpecialType.UnknownType;
}
return new TypeParameterSubstitution(classTypeArguments, fixedTypes);
}
@ -534,7 +542,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (m == null)
return;
for (int i = 0; i < e.Parameters.Count && i < m.Parameters.Count; i++) {
MakeExactInference(e.Parameters[i].Type.Resolve(context), m.Parameters[i].Type.Resolve(context));
MakeExactInference(e.Parameters[i].Type, m.Parameters[i].Type);
}
}
#endregion
@ -628,7 +636,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// Handle parameterized types:
if (pV != null) {
ParameterizedType uniqueBaseType = null;
foreach (IType baseU in U.GetAllBaseTypes(context)) {
foreach (IType baseU in U.GetAllBaseTypes()) {
ParameterizedType pU = baseU as ParameterizedType;
if (pU != null && object.Equals(pU.GetDefinition(), pV.GetDefinition()) && pU.TypeParameterCount == pV.TypeParameterCount) {
if (uniqueBaseType == null)
@ -642,7 +650,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
for (int i = 0; i < uniqueBaseType.TypeParameterCount; i++) {
IType Ui = uniqueBaseType.GetTypeArgument(i);
IType Vi = pV.GetTypeArgument(i);
if (Ui.IsReferenceType(context) == true) {
if (Ui.IsReferenceType == true) {
// look for variance
ITypeParameter Xi = pV.GetDefinition().TypeParameters[i];
switch (Xi.Variance) {
@ -712,7 +720,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// Handle parameterized types:
if (pU != null) {
ParameterizedType uniqueBaseType = null;
foreach (IType baseV in V.GetAllBaseTypes(context)) {
foreach (IType baseV in V.GetAllBaseTypes()) {
ParameterizedType pV = baseV as ParameterizedType;
if (pV != null && object.Equals(pU.GetDefinition(), pV.GetDefinition()) && pU.TypeParameterCount == pV.TypeParameterCount) {
if (uniqueBaseType == null)
@ -726,7 +734,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
for (int i = 0; i < uniqueBaseType.TypeParameterCount; i++) {
IType Ui = pU.GetTypeArgument(i);
IType Vi = uniqueBaseType.GetTypeArgument(i);
if (Ui.IsReferenceType(context) == true) {
if (Ui.IsReferenceType == true) {
// look for variance
ITypeParameter Xi = pU.GetDefinition().TypeParameters[i];
switch (Xi.Variance) {
@ -785,12 +793,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
Log.WriteCollection("GetBestCommonType() for ", expressions);
try {
this.typeParameters = new TP[1] { new TP(DummyTypeParameter.Instance) };
DummyTypeParameter tp = new DummyTypeParameter(compilation);
this.typeParameters = new TP[1] { new TP(tp) };
foreach (ResolveResult r in expressions) {
MakeOutputTypeInference(r, DummyTypeParameter.Instance);
MakeOutputTypeInference(r, tp);
}
success = Fix(typeParameters[0]);
return typeParameters[0].FixedTo ?? SharedTypes.UnknownType;
return typeParameters[0].FixedTo ?? SpecialType.UnknownType;
} finally {
Reset();
}
@ -798,25 +807,32 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
sealed class DummyTypeParameter : AbstractType, ITypeParameter
{
public static readonly DummyTypeParameter Instance = new DummyTypeParameter();
readonly ICompilation compilation;
public DummyTypeParameter(ICompilation compilation)
{
this.compilation = compilation;
}
ICompilation IResolved.Compilation {
get { return compilation; }
}
public override string Name {
get { return "X"; }
}
public override bool? IsReferenceType(ITypeResolveContext context)
{
return null;
public override bool? IsReferenceType {
get { return null; }
}
public override int GetHashCode()
{
return 0;
public override TypeKind Kind {
get { return TypeKind.TypeParameter; }
}
public override bool Equals(IType other)
public override ITypeReference ToTypeReference()
{
return this == other;
throw new NotSupportedException();
}
int ITypeParameter.Index {
@ -835,35 +851,32 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
get { return VarianceModifier.Invariant; }
}
bool IFreezable.IsFrozen {
get { return true; }
}
void IFreezable.Freeze()
{
}
DomRegion ITypeParameter.Region {
get { return DomRegion.Empty; }
}
public override TypeKind Kind {
get { return TypeKind.TypeParameter; }
IEntity ITypeParameter.Owner {
get { return null; }
}
ITypeParameterConstraints ITypeParameter.GetConstraints(ITypeResolveContext context)
{
return DefaultTypeParameterConstraints.Empty;
IType ITypeParameter.EffectiveBaseClass {
get { return SpecialType.UnknownType; }
}
IType ITypeParameter.GetEffectiveBaseClass(ITypeResolveContext context)
{
return KnownTypeReference.Object.Resolve(context);
IList<IType> ITypeParameter.EffectiveInterfaceSet {
get { return EmptyList<IType>.Instance; }
}
IEnumerable<IType> ITypeParameter.GetEffectiveInterfaceSet(ITypeResolveContext context)
{
return EmptyList<IType>.Instance;
bool ITypeParameter.HasDefaultConstructorConstraint {
get { return false; }
}
bool ITypeParameter.HasReferenceTypeConstraint {
get { return false; }
}
bool ITypeParameter.HasValueTypeConstraint {
get { return false; }
}
}
#endregion
@ -892,7 +905,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
static IType GetFirstTypePreferNonInterfaces(IList<IType> result)
{
return result.FirstOrDefault(c => c.Kind != TypeKind.Interface)
?? result.FirstOrDefault() ?? SharedTypes.UnknownType;
?? result.FirstOrDefault() ?? SpecialType.UnknownType;
}
IList<IType> FindTypesInBounds(IList<IType> lowerBounds, IList<IType> upperBounds)
@ -934,21 +947,21 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
List<ITypeDefinition> candidateTypeDefinitions;
if (lowerBounds.Count > 0) {
// Find candidates by using the lower bounds:
var hashSet = new HashSet<ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions(context));
var hashSet = new HashSet<ITypeDefinition>(lowerBounds[0].GetAllBaseTypeDefinitions());
for (int i = 1; i < lowerBounds.Count; i++) {
hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions(context));
hashSet.IntersectWith(lowerBounds[i].GetAllBaseTypeDefinitions());
}
candidateTypeDefinitions = hashSet.ToList();
} else {
// Find candidates by looking at all classes in the project:
candidateTypeDefinitions = context.GetAllTypes().ToList();
candidateTypeDefinitions = compilation.GetAllTypeDefinitions().ToList();
}
// Now filter out candidates that violate the upper bounds:
foreach (IType ub in upperBounds) {
ITypeDefinition ubDef = ub.GetDefinition();
if (ubDef != null) {
candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef, context));
candidateTypeDefinitions.RemoveAll(c => !c.IsDerivedFrom(ubDef));
}
}
@ -978,9 +991,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// if there were lower bounds, we aim for the most specific candidate:
// if this candidate isn't made redundant by an existing, more specific candidate:
if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef, context))) {
if (!candidateTypes.Any(c => c.GetDefinition().IsDerivedFrom(candidateDef))) {
// remove all existing candidates made redundant by this candidate:
candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition(), context));
candidateTypes.RemoveAll(c => candidateDef.IsDerivedFrom(c.GetDefinition()));
// add new candidate
candidateTypes.Add(candidate);
}
@ -988,9 +1001,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// if there only were upper bounds, we aim for the least specific candidate:
// if this candidate isn't made redundant by an existing, less specific candidate:
if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition(), context))) {
if (!candidateTypes.Any(c => candidateDef.IsDerivedFrom(c.GetDefinition()))) {
// remove all existing candidates made redundant by this candidate:
candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef, context));
candidateTypes.RemoveAll(c => c.GetDefinition().IsDerivedFrom(candidateDef));
// add new candidate
candidateTypes.Add(candidate);
}

Просмотреть файл

@ -17,10 +17,11 @@
// DEALINGS IN THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp.Resolver
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Looks up an alias (identifier in front of :: operator).
@ -30,38 +31,24 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// by <see cref="MemberTypeOrNamespaceReference"/>.
/// </remarks>
[Serializable]
public class AliasNamespaceReference : ITypeOrNamespaceReference
public class AliasNamespaceReference : TypeOrNamespaceReference
{
readonly UsingScope parentUsingScope;
readonly string identifier;
public AliasNamespaceReference(string identifier, UsingScope parentUsingScope)
public AliasNamespaceReference(string identifier)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
this.identifier = identifier;
this.parentUsingScope = parentUsingScope;
}
public string Identifier {
get { return identifier; }
}
public ResolveResult DoResolve(ITypeResolveContext context)
public override ResolveResult Resolve(CSharpResolver resolver)
{
CSharpResolver r = new CSharpResolver(context);
r.CurrentUsingScope = parentUsingScope;
return r.ResolveAlias(identifier);
}
public NamespaceResolveResult ResolveNamespace(ITypeResolveContext context)
{
return DoResolve(context) as NamespaceResolveResult;
}
public IType Resolve(ITypeResolveContext context)
{
return SharedTypes.UnknownType;
return resolver.ResolveAlias(identifier);
}
public override string ToString()

Просмотреть файл

@ -0,0 +1,93 @@
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Type reference used within an attribute.
/// Looks up both 'withoutSuffix' and 'withSuffix' and returns the type that exists.
/// </summary>
[Serializable]
public sealed class AttributeTypeReference : ITypeReference, ISupportsInterning
{
ITypeReference withoutSuffix, withSuffix;
public AttributeTypeReference(ITypeReference withoutSuffix, ITypeReference withSuffix)
{
if (withoutSuffix == null)
throw new ArgumentNullException("withoutSuffix");
if (withSuffix == null)
throw new ArgumentNullException("withSuffix");
this.withoutSuffix = withoutSuffix;
this.withSuffix = withSuffix;
}
public IType Resolve(ITypeResolveContext context)
{
IType t1 = withoutSuffix.Resolve(context);
IType t2 = withSuffix.Resolve(context);
if (t2.Kind == TypeKind.Unknown) return t1;
if (t1.Kind == TypeKind.Unknown) return t2;
var attrTypeDef = KnownTypeReference.Attribute.Resolve(context).GetDefinition();
if (attrTypeDef != null) {
bool t1IsAttribute = (t1.GetDefinition() != null && t1.GetDefinition().IsDerivedFrom(attrTypeDef));
bool t2IsAttribute = (t2.GetDefinition() != null && t2.GetDefinition().IsDerivedFrom(attrTypeDef));
if (t2IsAttribute && !t1IsAttribute)
return t2;
// If both types exist and are attributes, C# considers that to be an ambiguity, but we are less strict.
}
return t1;
}
public override string ToString()
{
return withoutSuffix.ToString() + "[Attribute]";
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
withoutSuffix = provider.Intern(withoutSuffix);
withSuffix = provider.Intern(withSuffix);
}
int ISupportsInterning.GetHashCodeForInterning()
{
unchecked {
return withoutSuffix.GetHashCode() + 715613 * withSuffix.GetHashCode();
}
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
AttributeTypeReference atr = other as AttributeTypeReference;
return atr != null && this.withoutSuffix == atr.withoutSuffix && this.withSuffix == atr.withSuffix;
}
}
}

Просмотреть файл

@ -17,46 +17,57 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.TypeSystem
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Represents an explicit interface implementation.
/// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(IExplicitInterfaceImplementationContract))]
#endif
public interface IExplicitInterfaceImplementation : IFreezable
public class CSharpAssembly : IAssembly
{
/// <summary>
/// Gets the type of the interface.
/// </summary>
ITypeReference InterfaceType { get; }
/// <summary>
/// Gets the member name.
/// </summary>
string MemberName { get; }
}
#if WITH_CONTRACTS
[ContractClassFor(typeof(IExplicitInterfaceImplementation))]
abstract class IExplicitInterfaceImplementationContract : IFreezableContract, IExplicitInterfaceImplementation
{
ITypeReference IExplicitInterfaceImplementation.InterfaceType {
bool IAssembly.IsMainAssembly {
get {
Contract.Ensures(Contract.Result<ITypeReference>() != null);
return null;
throw new NotImplementedException();
}
}
string IExplicitInterfaceImplementation.MemberName {
IUnresolvedAssembly IAssembly.UnresolvedAssembly {
get {
Contract.Ensures(Contract.Result<string>() != null);
return null;
throw new NotImplementedException();
}
}
string IAssembly.AssemblyName {
get {
throw new NotImplementedException();
}
}
System.Collections.Generic.IList<IAttribute> IAssembly.AssemblyAttributes {
get {
throw new NotImplementedException();
}
}
System.Collections.Generic.IList<IAttribute> IAssembly.ModuleAttributes {
get {
throw new NotImplementedException();
}
}
INamespace IAssembly.RootNamespace {
get {
throw new NotImplementedException();
}
}
ICompilation IResolved.Compilation {
get {
throw new NotImplementedException();
}
}
bool IAssembly.InternalsVisibleTo(IAssembly assembly)
{
throw new NotImplementedException();
}
}
#endif
}

Просмотреть файл

@ -21,15 +21,15 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
[Serializable]
public sealed class CSharpAttribute : Immutable, IAttribute
public sealed class CSharpAttribute : IUnresolvedAttribute
{
ITypeReference attributeType;
DomRegion region;
@ -59,6 +59,71 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
get { return attributeType; }
}
public IAttribute CreateResolvedAttribute(ITypeResolveContext context)
{
return new CSharpResolvedAttribute(context, this);
}
sealed class CSharpResolvedAttribute : IAttribute
{
readonly ITypeResolveContext context;
readonly CSharpAttribute unresolved;
readonly IType attributeType;
IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
public CSharpResolvedAttribute(ITypeResolveContext context, CSharpAttribute unresolved)
{
this.context = context;
this.unresolved = unresolved;
// Pretty much any access to the attribute checks the type first, so
// we don't need to use lazy-loading for that.
this.attributeType = unresolved.AttributeType.Resolve(context);
}
DomRegion IAttribute.Region {
get { return unresolved.Region; }
}
IType IAttribute.AttributeType {
get { return attributeType; }
}
IMethod IAttribute.Constructor {
get {
throw new NotImplementedException();
}
}
IList<ResolveResult> IAttribute.PositionalArguments {
get {
throw new NotImplementedException();
}
}
IList<KeyValuePair<IMember, ResolveResult>> IAttribute.NamedArguments {
get {
var namedArgs = this.namedArguments;
if (namedArgs != null) {
LazyInit.ReadBarrier();
return namedArgs;
} else {
namedArgs = new List<KeyValuePair<IMember, ResolveResult>>();
foreach (var pair in unresolved.namedArguments) {
IMember member = attributeType.GetMembers(m => (m.EntityType == EntityType.Field || m.EntityType == EntityType.Property) && m.Name == pair.Key).FirstOrDefault();
if (member != null) {
ResolveResult val = pair.Value.Resolve(context);
namedArgs.Add(new KeyValuePair<IMember, ResolveResult>(member, val));
}
}
return LazyInit.GetOrSet(ref this.namedArguments, namedArgs);
}
}
}
}
}
/*
public IMethod ResolveConstructor(ITypeResolveContext context)
{
CSharpResolver r = new CSharpResolver(context);
@ -132,7 +197,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (constantValue != null)
return constantValue.Resolve(context);
else
return new ErrorResolveResult(SharedTypes.UnknownType);
return new ErrorResolveResult(SpecialType.UnknownType);
}
public IList<KeyValuePair<string, ResolveResult>> GetNamedArguments(ITypeResolveContext context)
@ -145,62 +210,5 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
}
}
/// <summary>
/// Type reference used within an attribute.
/// Looks up both 'withoutSuffix' and 'withSuffix' and returns the type that exists.
/// </summary>
[Serializable]
public sealed class AttributeTypeReference : ITypeReference, ISupportsInterning
{
ITypeReference withoutSuffix, withSuffix;
public AttributeTypeReference(ITypeReference withoutSuffix, ITypeReference withSuffix)
{
if (withoutSuffix == null)
throw new ArgumentNullException("withoutSuffix");
if (withSuffix == null)
throw new ArgumentNullException("withSuffix");
this.withoutSuffix = withoutSuffix;
this.withSuffix = withSuffix;
}
public IType Resolve(ITypeResolveContext context)
{
// If both types exist, C# considers that to be an ambiguity, but we are less strict.
IType type = withoutSuffix.Resolve(context);
var attrType = context.GetTypeDefinition (typeof(System.Attribute));
if (attrType == null)
return SharedTypes.UnknownType;
if (type.GetDefinition() == null || !type.GetDefinition().IsDerivedFrom(attrType, context))
type = withSuffix.Resolve(context);
return type;
}
public override string ToString()
{
return withoutSuffix.ToString() + "[Attribute]";
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
withoutSuffix = provider.Intern(withoutSuffix);
withSuffix = provider.Intern(withSuffix);
}
int ISupportsInterning.GetHashCodeForInterning()
{
unchecked {
return withoutSuffix.GetHashCode() + 715613 * withSuffix.GetHashCode();
}
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
AttributeTypeReference atr = other as AttributeTypeReference;
return atr != null && this.withoutSuffix == atr.withoutSuffix && this.withSuffix == atr.withSuffix;
}
}
*/
}

Просмотреть файл

@ -18,11 +18,10 @@
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Represents a file that was parsed and converted for the type system.
@ -32,9 +31,9 @@ namespace ICSharpCode.NRefactory.CSharp
{
readonly string fileName;
readonly UsingScope rootUsingScope;
IList<ITypeDefinition> topLevelTypeDefinitions = new List<ITypeDefinition>();
IList<IAttribute> assemblyAttributes = new List<IAttribute>();
IList<IAttribute> moduleAttributes = new List<IAttribute>();
IList<IUnresolvedTypeDefinition> topLevelTypeDefinitions = new List<IUnresolvedTypeDefinition>();
IList<IUnresolvedAttribute> assemblyAttributes = new List<IUnresolvedAttribute>();
IList<IUnresolvedAttribute> moduleAttributes = new List<IUnresolvedAttribute>();
IList<UsingScope> usingScopes = new List<UsingScope>();
IList<Error> errors = new List<Error> ();
@ -42,10 +41,10 @@ namespace ICSharpCode.NRefactory.CSharp
{
base.FreezeInternal();
rootUsingScope.Freeze();
topLevelTypeDefinitions = FreezeList(topLevelTypeDefinitions);
assemblyAttributes = FreezeList(assemblyAttributes);
moduleAttributes = FreezeList(moduleAttributes);
usingScopes = FreezeList(usingScopes);
topLevelTypeDefinitions = FreezableHelper.FreezeListAndElements(topLevelTypeDefinitions);
assemblyAttributes = FreezableHelper.FreezeListAndElements(assemblyAttributes);
moduleAttributes = FreezableHelper.FreezeListAndElements(moduleAttributes);
usingScopes = FreezableHelper.FreezeListAndElements(usingScopes);
}
public CSharpParsedFile(string fileName, UsingScope rootUsingScope)
@ -67,7 +66,7 @@ namespace ICSharpCode.NRefactory.CSharp
public DateTime LastWriteTime {
get { return lastWriteTime; }
set {
CheckBeforeMutation();
FreezableHelper.ThrowIfFrozen(this);
lastWriteTime = value;
}
}
@ -85,19 +84,15 @@ namespace ICSharpCode.NRefactory.CSharp
get { return usingScopes; }
}
public IProjectContent ProjectContent {
get { return rootUsingScope.ProjectContent; }
}
public IList<ITypeDefinition> TopLevelTypeDefinitions {
public IList<IUnresolvedTypeDefinition> TopLevelTypeDefinitions {
get { return topLevelTypeDefinitions; }
}
public IList<IAttribute> AssemblyAttributes {
public IList<IUnresolvedAttribute> AssemblyAttributes {
get { return assemblyAttributes; }
}
public IList<IAttribute> ModuleAttributes {
public IList<IUnresolvedAttribute> ModuleAttributes {
get { return moduleAttributes; }
}
@ -110,15 +105,15 @@ namespace ICSharpCode.NRefactory.CSharp
return rootUsingScope;
}
public ITypeDefinition GetTopLevelTypeDefinition(TextLocation location)
public IUnresolvedTypeDefinition GetTopLevelTypeDefinition(TextLocation location)
{
return FindEntity(topLevelTypeDefinitions, location);
}
public ITypeDefinition GetInnermostTypeDefinition(TextLocation location)
public IUnresolvedTypeDefinition GetInnermostTypeDefinition(TextLocation location)
{
ITypeDefinition parent = null;
ITypeDefinition type = GetTopLevelTypeDefinition(location);
IUnresolvedTypeDefinition parent = null;
IUnresolvedTypeDefinition type = GetTopLevelTypeDefinition(location);
while (type != null) {
parent = type;
type = FindEntity(parent.NestedTypes, location);
@ -126,18 +121,15 @@ namespace ICSharpCode.NRefactory.CSharp
return parent;
}
public IMember GetMember(TextLocation location)
public IUnresolvedMember GetMember(TextLocation location)
{
ITypeDefinition type = GetInnermostTypeDefinition(location);
IUnresolvedTypeDefinition type = GetInnermostTypeDefinition(location);
if (type == null)
return null;
return FindEntity(type.Methods, location)
?? FindEntity(type.Fields, location)
?? FindEntity(type.Properties, location)
?? (IMember)FindEntity(type.Events, location);
return FindEntity(type.Members, location);
}
static T FindEntity<T>(IList<T> list, TextLocation location) where T : class, IEntity
static T FindEntity<T>(IList<T> list, TextLocation location) where T : class, IUnresolvedEntity
{
// This could be improved using a binary search
foreach (T entity in list) {

Просмотреть файл

@ -19,127 +19,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Analysis;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
namespace ICSharpCode.NRefactory.CSharp.TypeSystem.ConstantValues
{
// Contains representations for constant C# expressions.
// We use these instead of storing the full AST to reduce the memory usage.
[Serializable]
public sealed class CSharpConstantValue : Immutable, IConstantValue, ISupportsInterning
public abstract class ConstantExpression : IConstantValue
{
ConstantExpression expression;
UsingScope parentUsingScope;
ITypeDefinition parentTypeDefinition;
public CSharpConstantValue(ConstantExpression expression, UsingScope parentUsingScope, ITypeDefinition parentTypeDefinition)
{
if (expression == null)
throw new ArgumentNullException("expression");
this.expression = expression;
this.parentUsingScope = parentUsingScope;
this.parentTypeDefinition = parentTypeDefinition;
}
CSharpResolver CreateResolver(ITypeResolveContext context)
{
// Because constants are evaluated by the compiler, we need to evaluate them in the resolve context
// of the project where they are defined, not in that where the constant value is used.
// TODO: how do we get the correct resolve context?
return new CSharpResolver(context) {
CheckForOverflow = false, // TODO: get project-wide overflow setting
CurrentTypeDefinition = parentTypeDefinition,
CurrentUsingScope = parentUsingScope
};
}
public abstract ResolveResult Resolve(CSharpResolver resolver);
public ResolveResult Resolve(ITypeResolveContext context)
{
CacheManager cache = context.CacheManager;
if (cache != null) {
ResolveResult cachedResult = cache.GetShared(this) as ResolveResult;
if (cachedResult != null)
return cachedResult;
if (context.CurrentAssembly is CSharpAssembly && context.CurrentAssembly != context.Compilation.MainAssembly) {
// The constant needs to be resolved in a different compilation.
throw new NotImplementedException();
} else {
// Resolve in current context.
return Resolve(new CSharpResolver(context));
}
CSharpResolver resolver = CreateResolver(context);
ResolveResult rr = expression.Resolve(resolver);
// Retrieve the equivalent type in the new resolve context.
// E.g. if the constant is defined in a .NET 2.0 project, type might be Int32 from mscorlib 2.0.
// However, the calling project might be a .NET 4.0 project, so we need to return Int32 from mscorlib 4.0.
rr = MapToNewContext(rr, new MapTypeIntoNewContext(context));
if (cache != null)
cache.SetShared(this, rr);
return rr;
}
static ResolveResult MapToNewContext(ResolveResult rr, MapTypeIntoNewContext mapping)
static ResolveResult MapToNewContext(ResolveResult rr, ICompilation mainCompilation)
{
if (rr is TypeOfResolveResult) {
return new TypeOfResolveResult(
rr.Type.AcceptVisitor(mapping),
((TypeOfResolveResult)rr).ReferencedType.AcceptVisitor(mapping));
rr.Type.ToTypeReference().Resolve(mainCompilation.TypeResolveContext),
((TypeOfResolveResult)rr).ReferencedType.ToTypeReference().Resolve(mainCompilation.TypeResolveContext));
} else if (rr is ArrayCreateResolveResult) {
ArrayCreateResolveResult acrr = (ArrayCreateResolveResult)rr;
return new ArrayCreateResolveResult(
acrr.Type.AcceptVisitor(mapping),
MapToNewContext(acrr.SizeArguments, mapping),
MapToNewContext(acrr.InitializerElements, mapping));
acrr.Type.ToTypeReference().Resolve(mainCompilation.TypeResolveContext),
MapToNewContext(acrr.SizeArguments, mainCompilation),
MapToNewContext(acrr.InitializerElements, mainCompilation));
} else if (rr.IsCompileTimeConstant) {
return new ConstantResolveResult(
rr.Type.AcceptVisitor(mapping),
rr.Type.ToTypeReference().Resolve(mainCompilation.TypeResolveContext),
rr.ConstantValue
);
} else {
return new ErrorResolveResult(rr.Type.AcceptVisitor(mapping));
return new ErrorResolveResult(rr.Type.ToTypeReference().Resolve(mainCompilation.TypeResolveContext));
}
}
static ResolveResult[] MapToNewContext(ResolveResult[] input, MapTypeIntoNewContext mapping)
static ResolveResult[] MapToNewContext(ResolveResult[] input, ICompilation mainCompilation)
{
if (input == null)
return null;
ResolveResult[] output = new ResolveResult[input.Length];
for (int i = 0; i < input.Length; i++) {
output[i] = MapToNewContext(input[i], mapping);
output[i] = MapToNewContext(input[i], mainCompilation);
}
return output;
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
expression = provider.Intern(expression);
}
int ISupportsInterning.GetHashCodeForInterning()
{
return expression.GetHashCode()
^ (parentUsingScope != null ? parentUsingScope.GetHashCode() : 0)
^ (parentTypeDefinition != null ? parentTypeDefinition.GetHashCode() : 0);
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
CSharpConstantValue cv = other as CSharpConstantValue;
return cv != null
&& expression == cv.expression
&& parentUsingScope == cv.parentUsingScope
&& parentTypeDefinition == cv.parentTypeDefinition;
}
}
/// <summary>
/// Used for constants that could not be converted to IConstantValue.
/// </summary>
[Serializable]
public sealed class ErrorConstantValue : Immutable, IConstantValue
public sealed class ErrorConstantValue : IConstantValue
{
ITypeReference type;
readonly ITypeReference type;
public ErrorConstantValue(ITypeReference type)
{
@ -158,7 +106,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
/// Increments an integer <see cref="IConstantValue"/> by a fixed amount without changing the type.
/// </summary>
[Serializable]
public sealed class IncrementConstantValue : Immutable, IConstantValue, ISupportsInterning
public sealed class IncrementConstantValue : IConstantValue, ISupportsInterning
{
IConstantValue baseValue;
int incrementAmount;
@ -199,7 +147,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
int ISupportsInterning.GetHashCodeForInterning()
{
return baseValue.GetHashCode() ^ incrementAmount;
unchecked {
return baseValue.GetHashCode() * 33 ^ incrementAmount;
}
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
@ -209,12 +159,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
}
}
[Serializable]
public abstract class ConstantExpression
{
public abstract ResolveResult Resolve(CSharpResolver resolver);
}
/// <summary>
/// C#'s equivalent to the SimpleConstantValue.
/// </summary>
@ -242,10 +186,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
public override ResolveResult Resolve(CSharpResolver resolver)
{
object val = value;
if (val is ITypeReference)
val = ((ITypeReference)val).Resolve(resolver.Context);
return new ConstantResolveResult(type.Resolve(resolver.Context), val);
return new ConstantResolveResult(type.Resolve(resolver.CurrentTypeResolveContext), value);
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
@ -284,7 +225,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
public override ResolveResult Resolve(CSharpResolver resolver)
{
return resolver.ResolveCast(targetType.Resolve(resolver.Context), expression.Resolve(resolver));
return resolver.ResolveCast(targetType.Resolve(resolver.CurrentTypeResolveContext), expression.Resolve(resolver));
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
@ -324,18 +265,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
public override ResolveResult Resolve(CSharpResolver resolver)
{
return resolver.ResolveSimpleName(identifier, ResolveTypes(resolver, typeArguments));
}
internal static IList<IType> ResolveTypes(CSharpResolver resolver, IList<ITypeReference> typeArguments)
{
if (typeArguments == null)
return EmptyList<IType>.Instance;
IType[] types = new IType[typeArguments.Count];
for (int i = 0; i < types.Length; i++) {
types[i] = typeArguments[i].Resolve(resolver.Context);
}
return types;
return resolver.ResolveSimpleName(identifier, typeArguments.Resolve(resolver.CurrentTypeResolveContext));
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
@ -396,10 +326,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
{
ResolveResult rr;
if (targetType != null)
rr = new TypeResolveResult(targetType.Resolve(resolver.Context));
rr = new TypeResolveResult(targetType.Resolve(resolver.CurrentTypeResolveContext));
else
rr = targetExpression.Resolve(resolver);
return resolver.ResolveMemberAccess(rr, memberName, ConstantIdentifierReference.ResolveTypes(resolver, typeArguments));
return resolver.ResolveMemberAccess(rr, memberName, typeArguments.Resolve(resolver.CurrentTypeResolveContext));
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
@ -492,7 +422,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
public override ResolveResult Resolve(CSharpResolver resolver)
{
return resolver.ResolveDefaultValue(type.Resolve(resolver.Context));
return resolver.ResolveDefaultValue(type.Resolve(resolver.CurrentTypeResolveContext));
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
@ -677,7 +607,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues
elements[i] = arrayElements[i].Resolve(resolver);
}
if (elementType != null) {
return resolver.ResolveArrayCreation(elementType.Resolve(resolver.Context), 1, null, elements);
return resolver.ResolveArrayCreation(elementType.Resolve(resolver.CurrentTypeResolveContext), 1, null, elements);
} else {
return resolver.ResolveArrayCreation(null, 1, null, elements);
}

Просмотреть файл

@ -19,26 +19,24 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Reference to a qualified type or namespace name.
/// </summary>
[Serializable]
public sealed class MemberTypeOrNamespaceReference : ITypeOrNamespaceReference, ISupportsInterning
public sealed class MemberTypeOrNamespaceReference : TypeOrNamespaceReference, ISupportsInterning
{
ITypeOrNamespaceReference target;
readonly ITypeDefinition parentTypeDefinition;
readonly UsingScope parentUsingScope;
TypeOrNamespaceReference target;
string identifier;
IList<ITypeReference> typeArguments;
public MemberTypeOrNamespaceReference(ITypeOrNamespaceReference target, string identifier, IList<ITypeReference> typeArguments, ITypeDefinition parentTypeDefinition, UsingScope parentUsingScope)
public MemberTypeOrNamespaceReference(TypeOrNamespaceReference target, string identifier, IList<ITypeReference> typeArguments)
{
if (target == null)
throw new ArgumentNullException("target");
@ -47,15 +45,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
this.target = target;
this.identifier = identifier;
this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
this.parentTypeDefinition = parentTypeDefinition;
this.parentUsingScope = parentUsingScope;
}
public string Identifier {
get { return identifier; }
}
public ITypeOrNamespaceReference Target {
public TypeOrNamespaceReference Target {
get { return target; }
}
@ -69,53 +65,23 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary>
public MemberTypeOrNamespaceReference AddSuffix(string suffix)
{
return new MemberTypeOrNamespaceReference(target, identifier + suffix, typeArguments, parentTypeDefinition, parentUsingScope);
return new MemberTypeOrNamespaceReference(target, identifier + suffix, typeArguments);
}
public ResolveResult DoResolve(ITypeResolveContext context)
public override ResolveResult Resolve(CSharpResolver resolver)
{
CacheManager cacheManager = context.CacheManager;
if (cacheManager != null) {
ResolveResult cachedResult = cacheManager.GetShared(this) as ResolveResult;;
if (cachedResult != null)
return cachedResult;
}
ResolveResult targetRR = target.DoResolve(context);
ResolveResult targetRR = target.Resolve(resolver);
if (targetRR.IsError)
return targetRR;
CSharpResolver r = new CSharpResolver(context);
r.CurrentTypeDefinition = parentTypeDefinition;
r.CurrentUsingScope = parentUsingScope;
IType[] typeArgs = new IType[typeArguments.Count];
for (int i = 0; i < typeArgs.Length; i++) {
typeArgs[i] = typeArguments[i].Resolve(context);
}
ResolveResult rr;
IList<IType> typeArgs = typeArguments.Resolve(resolver.CurrentTypeResolveContext);
using (var busyLock = BusyManager.Enter(this)) {
if (busyLock.Success) {
rr = r.ResolveMemberType(targetRR, identifier, typeArgs);
return resolver.ResolveMemberType(targetRR, identifier, typeArgs);
} else {
// This can happen for "class Test : $Test.Base$ { public class Base {} }":
return ErrorResolveResult.UnknownError; // don't cache this error
}
}
if (cacheManager != null)
cacheManager.SetShared(this, rr);
return rr;
}
public NamespaceResolveResult ResolveNamespace(ITypeResolveContext context)
{
// TODO: use resolve context for original project, if possible
return DoResolve(context) as NamespaceResolveResult;
}
public IType Resolve(ITypeResolveContext context)
{
// TODO: use resolve context for original project, if possible; then map the result type into the new context
TypeResolveResult rr = DoResolve(context) as TypeResolveResult;
return rr != null ? rr.Type : SharedTypes.UnknownType;
}
public override string ToString()
@ -138,10 +104,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
int hashCode = 0;
unchecked {
hashCode += 1000000007 * target.GetHashCode();
if (parentTypeDefinition != null)
hashCode += 1000000009 * parentTypeDefinition.GetHashCode();
if (parentUsingScope != null)
hashCode += 1000000021 * parentUsingScope.GetHashCode();
hashCode += 1000000033 * identifier.GetHashCode();
hashCode += 1000000087 * typeArguments.GetHashCode();
}
@ -151,9 +113,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
MemberTypeOrNamespaceReference o = other as MemberTypeOrNamespaceReference;
return o != null && this.target == o.target && this.parentTypeDefinition == o.parentTypeDefinition
&& this.parentUsingScope == o.parentUsingScope && this.identifier == o.identifier
&& this.typeArguments == o.typeArguments;
return o != null && this.target == o.target
&& this.identifier == o.identifier && this.typeArguments == o.typeArguments;
}
}
}

Просмотреть файл

@ -0,0 +1,121 @@
// 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.Linq;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
[Serializable]
public sealed class MethodTypeParameterWithInheritedConstraints : DefaultUnresolvedTypeParameter
{
public MethodTypeParameterWithInheritedConstraints(int index, string name)
: base(EntityType.Method, index, name)
{
}
static ITypeParameter ResolveBaseTypeParameter(IMethod parentMethod, int index)
{
IMethod baseMethod = null;
if (parentMethod.IsOverride) {
foreach (IMethod m in InheritanceHelper.GetBaseMembers(parentMethod, false).OfType<IMethod>()) {
if (!m.IsOverride) {
baseMethod = m;
break;
}
}
} else if (parentMethod.IsExplicitInterfaceImplementation && parentMethod.InterfaceImplementations.Count == 1) {
baseMethod = parentMethod.InterfaceImplementations[0] as IMethod;
}
if (baseMethod != null && index < baseMethod.TypeParameters.Count)
return baseMethod.TypeParameters[index];
else
return null;
}
public override ITypeParameter CreateResolvedTypeParameter(ITypeResolveContext context)
{
if (context.CurrentMember is IMethod) {
return new ResolvedMethodTypeParameterWithInheritedConstraints(this, context);
} else {
return base.CreateResolvedTypeParameter(context);
}
}
sealed class ResolvedMethodTypeParameterWithInheritedConstraints : AbstractResolvedTypeParameter
{
volatile ITypeParameter baseTypeParameter;
public ResolvedMethodTypeParameterWithInheritedConstraints(MethodTypeParameterWithInheritedConstraints unresolved, ITypeResolveContext context)
: base(context.CurrentMember, unresolved.Index, unresolved.Name, unresolved.Variance,
unresolved.Attributes.CreateResolvedAttributes(context), unresolved.Region)
{
}
ITypeParameter GetBaseTypeParameter()
{
ITypeParameter baseTP = this.baseTypeParameter;
if (baseTP == null) {
// ResolveBaseTypeParameter() is idempotent, so this is thread-safe.
this.baseTypeParameter = baseTP = ResolveBaseTypeParameter((IMethod)this.Owner, this.Index);
}
return baseTP;
}
public override bool HasValueTypeConstraint {
get {
ITypeParameter baseTP = GetBaseTypeParameter();
return baseTP != null ? baseTP.HasValueTypeConstraint : false;
}
}
public override bool HasReferenceTypeConstraint {
get {
ITypeParameter baseTP = GetBaseTypeParameter();
return baseTP != null ? baseTP.HasReferenceTypeConstraint : false;
}
}
public override bool HasDefaultConstructorConstraint {
get {
ITypeParameter baseTP = GetBaseTypeParameter();
return baseTP != null ? baseTP.HasDefaultConstructorConstraint : false;
}
}
public override IEnumerable<IType> DirectBaseTypes {
get {
ITypeParameter baseTP = GetBaseTypeParameter();
if (baseTP != null) {
// Substitute occurrences of the base method's type parameters in the constraints
// with the type parameters from the
IMethod owner = (IMethod)this.Owner;
var substitution = new TypeParameterSubstitution(null, new ProjectedList<ITypeParameter, IType>(owner.TypeParameters, t => t));
return baseTP.DirectBaseTypes.Select(t => t.AcceptVisitor(substitution));
} else {
return EmptyList<IType>.Instance;
}
}
}
}
}
}

Просмотреть файл

@ -20,32 +20,29 @@ using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Represents a simple C# name. (a single non-qualified identifier with an optional list of type arguments)
/// </summary>
[Serializable]
public sealed class SimpleTypeOrNamespaceReference : ITypeOrNamespaceReference, ISupportsInterning
public sealed class SimpleTypeOrNamespaceReference : TypeOrNamespaceReference, ISupportsInterning
{
readonly ITypeDefinition parentTypeDefinition;
readonly UsingScope parentUsingScope;
string identifier;
IList<ITypeReference> typeArguments;
readonly SimpleNameLookupMode lookupMode;
public SimpleTypeOrNamespaceReference(string identifier, IList<ITypeReference> typeArguments, ITypeDefinition parentTypeDefinition, UsingScope parentUsingScope, SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
public SimpleTypeOrNamespaceReference(string identifier, IList<ITypeReference> typeArguments, SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
this.identifier = identifier;
this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
this.parentTypeDefinition = parentTypeDefinition;
this.parentUsingScope = parentUsingScope;
this.lookupMode = lookupMode;
}
@ -63,42 +60,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary>
public SimpleTypeOrNamespaceReference AddSuffix(string suffix)
{
return new SimpleTypeOrNamespaceReference(identifier + suffix, typeArguments, parentTypeDefinition, parentUsingScope, lookupMode);
return new SimpleTypeOrNamespaceReference(identifier + suffix, typeArguments, lookupMode);
}
public ResolveResult DoResolve(ITypeResolveContext context)
public override ResolveResult Resolve(CSharpResolver resolver)
{
CacheManager cacheManager = context.CacheManager;
if (cacheManager != null) {
ResolveResult cachedResult = cacheManager.GetShared(this) as ResolveResult;
if (cachedResult != null)
return cachedResult;
}
CSharpResolver r = new CSharpResolver(context);
r.CurrentTypeDefinition = parentTypeDefinition;
r.CurrentUsingScope = parentUsingScope;
IType[] typeArgs = new IType[typeArguments.Count];
for (int i = 0; i < typeArgs.Length; i++) {
typeArgs[i] = typeArguments[i].Resolve(context);
}
ResolveResult rr = r.LookupSimpleNameOrTypeName(identifier, typeArgs, lookupMode);
if (cacheManager != null)
cacheManager.SetShared(this, rr);
return rr;
}
public NamespaceResolveResult ResolveNamespace(ITypeResolveContext context)
{
// TODO: use resolve context for original project, if possible
return DoResolve(context) as NamespaceResolveResult;
}
public IType Resolve(ITypeResolveContext context)
{
// TODO: use resolve context for original project, if possible; then map the result type into the new context
TypeResolveResult rr = DoResolve(context) as TypeResolveResult;
return rr != null ? rr.Type : SharedTypes.UnknownType;
var typeArgs = typeArguments.Resolve(resolver.CurrentTypeResolveContext);
return resolver.LookupSimpleNameOrTypeName(identifier, typeArgs, lookupMode);
}
public override string ToString()
@ -119,11 +87,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
int hashCode = 0;
unchecked {
if (parentTypeDefinition != null)
hashCode += 1000000007 * parentTypeDefinition.GetHashCode();
if (parentUsingScope != null)
hashCode += 1000000009 * parentUsingScope.GetHashCode();
hashCode += 1000000021 * identifier.GetHashCode();
hashCode += 1000000033 * typeArguments.GetHashCode();
hashCode += 1000000087 * (int)lookupMode;
@ -134,8 +97,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
SimpleTypeOrNamespaceReference o = other as SimpleTypeOrNamespaceReference;
return o != null && this.parentTypeDefinition == o.parentTypeDefinition
&& this.parentUsingScope == o.parentUsingScope && this.identifier == o.identifier
return o != null && this.identifier == o.identifier
&& this.typeArguments == o.typeArguments && this.lookupMode == o.lookupMode;
}
}

Просмотреть файл

@ -0,0 +1,61 @@
// 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 ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Represents a reference which could point to a type or namespace.
/// </summary>
[Serializable]
public abstract class TypeOrNamespaceReference : ITypeReference
{
/// <summary>
/// Resolves the reference and returns the ResolveResult.
/// </summary>
public abstract ResolveResult Resolve(CSharpResolver resolver);
/// <summary>
/// Returns the namespace that is referenced; or null if no such namespace is found.
/// </summary>
public INamespace ResolveNamespace(CSharpResolver resolver)
{
NamespaceResolveResult nrr = Resolve(resolver) as NamespaceResolveResult;
return nrr != null ? nrr.Namespace : null;
}
/// <summary>
/// Returns the type that is referenced; or <see cref="SpecialTypes.UnknownType"/> if the type isn't found.
/// </summary>
public IType ResolveType(CSharpResolver resolver)
{
TypeResolveResult trr = Resolve(resolver) as TypeResolveResult;
return trr != null ? trr.Type : SpecialType.UnknownType;
}
IType ITypeReference.Resolve(ITypeResolveContext context)
{
// TODO: use the correct compilation
return ResolveType(new CSharpResolver(context));
}
}
}

Просмотреть файл

@ -22,22 +22,23 @@ using System.Diagnostics;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Analysis;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.Resolver.ConstantValues;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.CSharp.TypeSystem.ConstantValues;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Produces type and member definitions from the DOM.
/// </summary>
public class TypeSystemConvertVisitor : DepthFirstAstVisitor<object, IEntity>
public class TypeSystemConvertVisitor : DepthFirstAstVisitor<object, IUnresolvedEntity>
{
readonly CSharpParsedFile parsedFile;
UsingScope usingScope;
DefaultTypeDefinition currentTypeDefinition;
DefaultMethod currentMethod;
DefaultUnresolvedTypeDefinition currentTypeDefinition;
DefaultUnresolvedMethod currentMethod;
IInterningProvider interningProvider = new SimpleInterningProvider();
@ -53,15 +54,12 @@ namespace ICSharpCode.NRefactory.CSharp
/// <summary>
/// Creates a new TypeSystemConvertVisitor.
/// </summary>
/// <param name="pc">The parent project content (used as owner for the types being created).</param>
/// <param name="fileName">The file name (used for DomRegions).</param>
public TypeSystemConvertVisitor(IProjectContent pc, string fileName)
public TypeSystemConvertVisitor(string fileName)
{
if (pc == null)
throw new ArgumentNullException("pc");
if (fileName == null)
throw new ArgumentNullException("fileName");
this.parsedFile = new CSharpParsedFile(fileName, new UsingScope(pc));
this.parsedFile = new CSharpParsedFile(fileName, new UsingScope());
this.usingScope = parsedFile.RootUsingScope;
}
@ -71,7 +69,7 @@ namespace ICSharpCode.NRefactory.CSharp
/// <param name="parsedFile">The parsed file to which members should be added.</param>
/// <param name="currentUsingScope">The current using scope.</param>
/// <param name="currentTypeDefinition">The current type definition.</param>
public TypeSystemConvertVisitor(CSharpParsedFile parsedFile, UsingScope currentUsingScope = null, DefaultTypeDefinition currentTypeDefinition = null)
public TypeSystemConvertVisitor(CSharpParsedFile parsedFile, UsingScope currentUsingScope = null, DefaultUnresolvedTypeDefinition currentTypeDefinition = null)
{
if (parsedFile == null)
throw new ArgumentNullException("parsedFile");
@ -113,7 +111,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
#region Compilation Unit
public override IEntity VisitCompilationUnit (CompilationUnit unit, object data)
public override IUnresolvedEntity VisitCompilationUnit (CompilationUnit unit, object data)
{
parsedFile.Errors = unit.Errors;
return base.VisitCompilationUnit (unit, data);
@ -121,15 +119,15 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Using Declarations
public override IEntity VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, object data)
public override IUnresolvedEntity VisitExternAliasDeclaration(ExternAliasDeclaration externAliasDeclaration, object data)
{
usingScope.ExternAliases.Add(externAliasDeclaration.Name);
return null;
}
public override IEntity VisitUsingDeclaration(UsingDeclaration usingDeclaration, object data)
public override IUnresolvedEntity VisitUsingDeclaration(UsingDeclaration usingDeclaration, object data)
{
ITypeOrNamespaceReference u = ConvertType(usingDeclaration.Import, SimpleNameLookupMode.TypeInUsingDeclaration) as ITypeOrNamespaceReference;
TypeOrNamespaceReference u = ConvertType(usingDeclaration.Import, SimpleNameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference;
if (u != null) {
if (interningProvider != null)
u = interningProvider.Intern(u);
@ -138,20 +136,20 @@ namespace ICSharpCode.NRefactory.CSharp
return null;
}
public override IEntity VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration, object data)
public override IUnresolvedEntity VisitUsingAliasDeclaration(UsingAliasDeclaration usingDeclaration, object data)
{
ITypeOrNamespaceReference u = ConvertType(usingDeclaration.Import, SimpleNameLookupMode.TypeInUsingDeclaration) as ITypeOrNamespaceReference;
TypeOrNamespaceReference u = ConvertType(usingDeclaration.Import, SimpleNameLookupMode.TypeInUsingDeclaration) as TypeOrNamespaceReference;
if (u != null) {
if (interningProvider != null)
u = interningProvider.Intern(u);
usingScope.UsingAliases.Add(new KeyValuePair<string, ITypeOrNamespaceReference>(usingDeclaration.Alias, u));
usingScope.UsingAliases.Add(new KeyValuePair<string, TypeOrNamespaceReference>(usingDeclaration.Alias, u));
}
return null;
}
#endregion
#region Namespace Declaration
public override IEntity VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data)
public override IUnresolvedEntity VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data)
{
DomRegion region = MakeRegion(namespaceDeclaration);
UsingScope previousUsingScope = usingScope;
@ -167,27 +165,27 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Type Definitions
DefaultTypeDefinition CreateTypeDefinition(string name)
DefaultUnresolvedTypeDefinition CreateTypeDefinition(string name)
{
DefaultTypeDefinition newType;
DefaultUnresolvedTypeDefinition newType;
if (currentTypeDefinition != null) {
newType = new DefaultTypeDefinition(currentTypeDefinition, name);
newType = new DefaultUnresolvedTypeDefinition(currentTypeDefinition, name);
foreach (var typeParameter in currentTypeDefinition.TypeParameters)
newType.TypeParameters.Add(typeParameter);
currentTypeDefinition.NestedTypes.Add(newType);
} else {
newType = new DefaultTypeDefinition(parsedFile, usingScope.NamespaceName, name);
newType = new DefaultUnresolvedTypeDefinition(usingScope.NamespaceName, name);
parsedFile.TopLevelTypeDefinitions.Add(newType);
}
newType.ParsedFile = parsedFile;
return newType;
}
public override IEntity VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
public override IUnresolvedEntity VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data)
{
var td = currentTypeDefinition = CreateTypeDefinition(typeDeclaration.Name);
td.Region = MakeRegion(typeDeclaration);
td.BodyRegion = MakeBraceRegion(typeDeclaration);
td.AddDefaultConstructorIfRequired = true;
ApplyModifiers(td, typeDeclaration.Modifiers);
switch (typeDeclaration.ClassType) {
@ -216,21 +214,19 @@ namespace ICSharpCode.NRefactory.CSharp
member.AcceptVisitor(this, data);
}
td.HasExtensionMethods = td.Methods.Any(m => m.IsExtensionMethod);
currentTypeDefinition = (DefaultTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
currentTypeDefinition = (DefaultUnresolvedTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
if (interningProvider != null) {
td.ApplyInterningProvider(interningProvider);
}
return td;
}
public override IEntity VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data)
public override IUnresolvedEntity VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data)
{
var td = currentTypeDefinition = CreateTypeDefinition(delegateDeclaration.Name);
td.Kind = TypeKind.Delegate;
td.Region = MakeRegion(delegateDeclaration);
td.BaseTypes.Add(multicastDelegateReference);
td.BaseTypes.Add(KnownTypeReference.MulticastDelegate);
ApplyModifiers(td, delegateDeclaration.Modifiers);
td.IsSealed = true; // delegates are implicitly sealed
@ -238,35 +234,40 @@ namespace ICSharpCode.NRefactory.CSharp
ConvertTypeParameters(td.TypeParameters, delegateDeclaration.TypeParameters, delegateDeclaration.Constraints, EntityType.TypeDefinition);
ITypeReference returnType = ConvertType(delegateDeclaration.ReturnType);
List<IParameter> parameters = new List<IParameter>();
List<IUnresolvedParameter> parameters = new List<IUnresolvedParameter>();
ConvertParameters(parameters, delegateDeclaration.Parameters);
AddDefaultMethodsToDelegate(td, returnType, parameters);
foreach (AttributeSection section in delegateDeclaration.Attributes) {
if (section.AttributeTarget == "return") {
ConvertAttributes(td.Methods.Single(m => m.Name == "Invoke").ReturnTypeAttributes, section);
ConvertAttributes(td.Methods.Single(m => m.Name == "EndInvoke").ReturnTypeAttributes, section);
List<IUnresolvedAttribute> returnTypeAttributes = new List<IUnresolvedAttribute>();
ConvertAttributes(returnTypeAttributes, section);
IUnresolvedMethod invokeMethod = (IUnresolvedMethod)td.Members.Single(m => m.Name == "Invoke");
IUnresolvedMethod endInvokeMethod = (IUnresolvedMethod)td.Members.Single(m => m.Name == "EndInvoke");
foreach (IUnresolvedAttribute attr in returnTypeAttributes) {
invokeMethod.ReturnTypeAttributes.Add(attr);
endInvokeMethod.ReturnTypeAttributes.Add(attr);
}
} else {
ConvertAttributes(td.Attributes, section);
}
}
currentTypeDefinition = (DefaultTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
currentTypeDefinition = (DefaultUnresolvedTypeDefinition)currentTypeDefinition.DeclaringTypeDefinition;
if (interningProvider != null) {
td.ApplyInterningProvider(interningProvider);
}
return td;
}
static readonly ITypeReference multicastDelegateReference = typeof(MulticastDelegate).ToTypeReference();
static readonly IParameter delegateObjectParameter = MakeParameter(KnownTypeReference.Object, "object");
static readonly IParameter delegateIntPtrMethodParameter = MakeParameter(typeof(IntPtr).ToTypeReference(), "method");
static readonly IParameter delegateAsyncCallbackParameter = MakeParameter(typeof(AsyncCallback).ToTypeReference(), "callback");
static readonly IParameter delegateResultParameter = MakeParameter(typeof(IAsyncResult).ToTypeReference(), "result");
static readonly IUnresolvedParameter delegateObjectParameter = MakeParameter(KnownTypeReference.Object, "object");
static readonly IUnresolvedParameter delegateIntPtrMethodParameter = MakeParameter(KnownTypeReference.IntPtr, "method");
static readonly IUnresolvedParameter delegateAsyncCallbackParameter = MakeParameter(typeof(AsyncCallback).ToTypeReference(), "callback");
static readonly IUnresolvedParameter delegateResultParameter = MakeParameter(typeof(IAsyncResult).ToTypeReference(), "result");
static IParameter MakeParameter(ITypeReference type, string name)
static IUnresolvedParameter MakeParameter(ITypeReference type, string name)
{
DefaultParameter p = new DefaultParameter(type, name);
DefaultUnresolvedParameter p = new DefaultUnresolvedParameter(type, name);
p.Freeze();
return p;
}
@ -274,7 +275,7 @@ namespace ICSharpCode.NRefactory.CSharp
/// <summary>
/// Adds the 'Invoke', 'BeginInvoke', 'EndInvoke' methods, and a constructor, to the <paramref name="delegateType"/>.
/// </summary>
public static void AddDefaultMethodsToDelegate(DefaultTypeDefinition delegateType, ITypeReference returnType, IEnumerable<IParameter> parameters)
public static void AddDefaultMethodsToDelegate(DefaultUnresolvedTypeDefinition delegateType, ITypeReference returnType, IEnumerable<IUnresolvedParameter> parameters)
{
if (delegateType == null)
throw new ArgumentNullException("delegateType");
@ -283,18 +284,19 @@ namespace ICSharpCode.NRefactory.CSharp
if (parameters == null)
throw new ArgumentNullException("parameters");
DomRegion region = new DomRegion(delegateType.Region.FileName, delegateType.Region.BeginLine, delegateType.Region.BeginColumn);
DomRegion region = delegateType.Region;
region = new DomRegion(region.FileName, region.BeginLine, region.BeginColumn); // remove end position
DefaultMethod invoke = new DefaultMethod(delegateType, "Invoke");
DefaultUnresolvedMethod invoke = new DefaultUnresolvedMethod(delegateType, "Invoke");
invoke.Accessibility = Accessibility.Public;
invoke.IsSynthetic = true;
foreach (var p in parameters)
invoke.Parameters.Add(p);
invoke.ReturnType = returnType;
invoke.Region = region;
delegateType.Methods.Add(invoke);
delegateType.Members.Add(invoke);
DefaultMethod beginInvoke = new DefaultMethod(delegateType, "BeginInvoke");
DefaultUnresolvedMethod beginInvoke = new DefaultUnresolvedMethod(delegateType, "BeginInvoke");
beginInvoke.Accessibility = Accessibility.Public;
beginInvoke.IsSynthetic = true;
foreach (var p in parameters)
@ -303,17 +305,17 @@ namespace ICSharpCode.NRefactory.CSharp
beginInvoke.Parameters.Add(delegateObjectParameter);
beginInvoke.ReturnType = delegateResultParameter.Type;
beginInvoke.Region = region;
delegateType.Methods.Add(beginInvoke);
delegateType.Members.Add(beginInvoke);
DefaultMethod endInvoke = new DefaultMethod(delegateType, "EndInvoke");
DefaultUnresolvedMethod endInvoke = new DefaultUnresolvedMethod(delegateType, "EndInvoke");
endInvoke.Accessibility = Accessibility.Public;
endInvoke.IsSynthetic = true;
endInvoke.Parameters.Add(delegateResultParameter);
endInvoke.ReturnType = invoke.ReturnType;
endInvoke.Region = region;
delegateType.Methods.Add(endInvoke);
delegateType.Members.Add(endInvoke);
DefaultMethod ctor = new DefaultMethod(delegateType, ".ctor");
DefaultUnresolvedMethod ctor = new DefaultUnresolvedMethod(delegateType, ".ctor");
ctor.EntityType = EntityType.Constructor;
ctor.Accessibility = Accessibility.Public;
ctor.IsSynthetic = true;
@ -321,18 +323,18 @@ namespace ICSharpCode.NRefactory.CSharp
ctor.Parameters.Add(delegateIntPtrMethodParameter);
ctor.ReturnType = delegateType;
ctor.Region = region;
delegateType.Methods.Add(ctor);
delegateType.Members.Add(ctor);
}
#endregion
#region Fields
public override IEntity VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data)
public override IUnresolvedEntity VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data)
{
bool isSingleField = fieldDeclaration.Variables.Count == 1;
Modifiers modifiers = fieldDeclaration.Modifiers;
DefaultField field = null;
DefaultUnresolvedField field = null;
foreach (VariableInitializer vi in fieldDeclaration.Variables) {
field = new DefaultField(currentTypeDefinition, vi.Name);
field = new DefaultUnresolvedField(currentTypeDefinition, vi.Name);
field.Region = isSingleField ? MakeRegion(fieldDeclaration) : MakeRegion(vi);
field.BodyRegion = MakeRegion(vi);
@ -348,7 +350,7 @@ namespace ICSharpCode.NRefactory.CSharp
field.ConstantValue = ConvertConstantValue(field.ReturnType, vi.Initializer);
}
currentTypeDefinition.Fields.Add(field);
currentTypeDefinition.Members.Add(field);
if (interningProvider != null) {
field.ApplyInterningProvider(interningProvider);
}
@ -356,15 +358,15 @@ namespace ICSharpCode.NRefactory.CSharp
return isSingleField ? field : null;
}
public override IEntity VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, object data)
public override IUnresolvedEntity VisitFixedFieldDeclaration(FixedFieldDeclaration fixedFieldDeclaration, object data)
{
// TODO: add support for fixed fields
return base.VisitFixedFieldDeclaration(fixedFieldDeclaration, data);
}
public override IEntity VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, object data)
public override IUnresolvedEntity VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, object data)
{
DefaultField field = new DefaultField(currentTypeDefinition, enumMemberDeclaration.Name);
DefaultUnresolvedField field = new DefaultUnresolvedField(currentTypeDefinition, enumMemberDeclaration.Name);
field.Region = field.BodyRegion = MakeRegion(enumMemberDeclaration);
ConvertAttributes(field.Attributes, enumMemberDeclaration.Attributes);
@ -374,7 +376,7 @@ namespace ICSharpCode.NRefactory.CSharp
if (!enumMemberDeclaration.Initializer.IsNull) {
field.ConstantValue = ConvertConstantValue(currentTypeDefinition, enumMemberDeclaration.Initializer);
} else {
IField prevField = currentTypeDefinition.Fields.LastOrDefault();
DefaultUnresolvedField prevField = currentTypeDefinition.Members.LastOrDefault() as DefaultUnresolvedField;
if (prevField == null || prevField.ConstantValue == null) {
field.ConstantValue = ConvertConstantValue(currentTypeDefinition, new PrimitiveExpression(0));
} else {
@ -382,7 +384,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
currentTypeDefinition.Fields.Add(field);
currentTypeDefinition.Members.Add(field);
if (interningProvider != null) {
field.ApplyInterningProvider(interningProvider);
}
@ -391,9 +393,9 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Methods
public override IEntity VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
public override IUnresolvedEntity VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data)
{
DefaultMethod m = new DefaultMethod(currentTypeDefinition, methodDeclaration.Name);
DefaultUnresolvedMethod m = new DefaultUnresolvedMethod(currentTypeDefinition, methodDeclaration.Name);
currentMethod = m; // required for resolving type parameters
m.Region = MakeRegion(methodDeclaration);
m.BodyRegion = MakeRegion(methodDeclaration.Body);
@ -401,7 +403,7 @@ namespace ICSharpCode.NRefactory.CSharp
if (InheritsConstraints(methodDeclaration) && methodDeclaration.Constraints.Count == 0) {
int index = 0;
foreach (TypeParameterDeclaration tpDecl in methodDeclaration.TypeParameters) {
var tp = new TypeParameterWithInheritedConstraints(m, index++, tpDecl.Name);
var tp = new MethodTypeParameterWithInheritedConstraints(index++, tpDecl.Name);
tp.Region = MakeRegion(tpDecl);
ConvertAttributes(tp.Attributes, tpDecl.Attributes);
tp.Variance = tpDecl.Variance;
@ -423,7 +425,7 @@ namespace ICSharpCode.NRefactory.CSharp
m.InterfaceImplementations.Add(ConvertInterfaceImplementation(methodDeclaration.PrivateImplementationType, m.Name));
}
currentTypeDefinition.Methods.Add(m);
currentTypeDefinition.Members.Add(m);
currentMethod = null;
if (interningProvider != null) {
m.ApplyInterningProvider(interningProvider);
@ -439,13 +441,14 @@ namespace ICSharpCode.NRefactory.CSharp
return !methodDeclaration.PrivateImplementationType.IsNull;
}
void ConvertTypeParameters(IList<ITypeParameter> output, AstNodeCollection<TypeParameterDeclaration> typeParameters, AstNodeCollection<Constraint> constraints, EntityType ownerType)
void ConvertTypeParameters(IList<IUnresolvedTypeParameter> output, AstNodeCollection<TypeParameterDeclaration> typeParameters,
AstNodeCollection<Constraint> constraints, EntityType ownerType)
{
// output might be non-empty when type parameters were copied from an outer class
int index = output.Count;
List<DefaultTypeParameter> list = new List<DefaultTypeParameter>();
List<DefaultUnresolvedTypeParameter> list = new List<DefaultUnresolvedTypeParameter>();
foreach (TypeParameterDeclaration tpDecl in typeParameters) {
DefaultTypeParameter tp = new DefaultTypeParameter(ownerType, index++, tpDecl.Name);
DefaultUnresolvedTypeParameter tp = new DefaultUnresolvedTypeParameter(ownerType, index++, tpDecl.Name);
tp.Region = MakeRegion(tpDecl);
ConvertAttributes(tp.Attributes, tpDecl.Attributes);
tp.Variance = tpDecl.Variance;
@ -477,16 +480,17 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
DefaultExplicitInterfaceImplementation ConvertInterfaceImplementation(AstType interfaceType, string memberName)
IMemberReference ConvertInterfaceImplementation(AstType interfaceType, string memberName)
{
return new DefaultExplicitInterfaceImplementation(ConvertType(interfaceType), memberName);
throw new NotImplementedException();
//return new DefaultExplicitInterfaceImplementation(ConvertType(interfaceType), memberName);
}
#endregion
#region Operators
public override IEntity VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, object data)
public override IUnresolvedEntity VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, object data)
{
DefaultMethod m = new DefaultMethod(currentTypeDefinition, operatorDeclaration.Name);
DefaultUnresolvedMethod m = new DefaultUnresolvedMethod(currentTypeDefinition, operatorDeclaration.Name);
m.EntityType = EntityType.Operator;
m.Region = MakeRegion(operatorDeclaration);
m.BodyRegion = MakeRegion(operatorDeclaration.Body);
@ -499,7 +503,7 @@ namespace ICSharpCode.NRefactory.CSharp
ConvertParameters(m.Parameters, operatorDeclaration.Parameters);
currentTypeDefinition.Methods.Add(m);
currentTypeDefinition.Members.Add(m);
if (interningProvider != null) {
m.ApplyInterningProvider(interningProvider);
}
@ -508,11 +512,11 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Constructors
public override IEntity VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data)
public override IUnresolvedEntity VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data)
{
Modifiers modifiers = constructorDeclaration.Modifiers;
bool isStatic = (modifiers & Modifiers.Static) != 0;
DefaultMethod ctor = new DefaultMethod(currentTypeDefinition, isStatic ? ".cctor" : ".ctor");
DefaultUnresolvedMethod ctor = new DefaultUnresolvedMethod(currentTypeDefinition, isStatic ? ".cctor" : ".ctor");
ctor.EntityType = EntityType.Constructor;
ctor.Region = MakeRegion(constructorDeclaration);
if (!constructorDeclaration.Initializer.IsNull) {
@ -530,7 +534,7 @@ namespace ICSharpCode.NRefactory.CSharp
else
ApplyModifiers(ctor, modifiers);
currentTypeDefinition.Methods.Add(ctor);
currentTypeDefinition.Members.Add(ctor);
if (interningProvider != null) {
ctor.ApplyInterningProvider(interningProvider);
}
@ -539,9 +543,9 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Destructors
public override IEntity VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, object data)
public override IUnresolvedEntity VisitDestructorDeclaration(DestructorDeclaration destructorDeclaration, object data)
{
DefaultMethod dtor = new DefaultMethod(currentTypeDefinition, "Finalize");
DefaultUnresolvedMethod dtor = new DefaultUnresolvedMethod(currentTypeDefinition, "Finalize");
dtor.EntityType = EntityType.Destructor;
dtor.Region = MakeRegion(destructorDeclaration);
dtor.BodyRegion = MakeRegion(destructorDeclaration.Body);
@ -551,7 +555,7 @@ namespace ICSharpCode.NRefactory.CSharp
ConvertAttributes(dtor.Attributes, destructorDeclaration.Attributes);
currentTypeDefinition.Methods.Add(dtor);
currentTypeDefinition.Members.Add(dtor);
if (interningProvider != null) {
dtor.ApplyInterningProvider(interningProvider);
}
@ -560,9 +564,9 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Properties / Indexers
public override IEntity VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data)
public override IUnresolvedEntity VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data)
{
DefaultProperty p = new DefaultProperty(currentTypeDefinition, propertyDeclaration.Name);
DefaultUnresolvedProperty p = new DefaultUnresolvedProperty(currentTypeDefinition, propertyDeclaration.Name);
p.Region = MakeRegion(propertyDeclaration);
p.BodyRegion = MakeBraceRegion(propertyDeclaration);
ApplyModifiers(p, propertyDeclaration.Modifiers);
@ -574,16 +578,16 @@ namespace ICSharpCode.NRefactory.CSharp
}
p.Getter = ConvertAccessor(propertyDeclaration.Getter, p.Accessibility);
p.Setter = ConvertAccessor(propertyDeclaration.Setter, p.Accessibility);
currentTypeDefinition.Properties.Add(p);
currentTypeDefinition.Members.Add(p);
if (interningProvider != null) {
p.ApplyInterningProvider(interningProvider);
}
return p;
}
public override IEntity VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, object data)
public override IUnresolvedEntity VisitIndexerDeclaration(IndexerDeclaration indexerDeclaration, object data)
{
DefaultProperty p = new DefaultProperty(currentTypeDefinition, "Item");
DefaultUnresolvedProperty p = new DefaultUnresolvedProperty(currentTypeDefinition, "Item");
p.EntityType = EntityType.Indexer;
p.Region = MakeRegion(indexerDeclaration);
p.BodyRegion = MakeBraceRegion(indexerDeclaration);
@ -597,18 +601,18 @@ namespace ICSharpCode.NRefactory.CSharp
p.Getter = ConvertAccessor(indexerDeclaration.Getter, p.Accessibility);
p.Setter = ConvertAccessor(indexerDeclaration.Setter, p.Accessibility);
ConvertParameters(p.Parameters, indexerDeclaration.Parameters);
currentTypeDefinition.Properties.Add(p);
currentTypeDefinition.Members.Add(p);
if (interningProvider != null) {
p.ApplyInterningProvider(interningProvider);
}
return p;
}
IAccessor ConvertAccessor(Accessor accessor, Accessibility defaultAccessibility)
IUnresolvedAccessor ConvertAccessor(Accessor accessor, Accessibility defaultAccessibility)
{
if (accessor.IsNull)
return null;
DefaultAccessor a = new DefaultAccessor();
DefaultUnresolvedAccessor a = new DefaultUnresolvedAccessor();
a.Accessibility = GetAccessibility(accessor.Modifiers) ?? defaultAccessibility;
a.Region = MakeRegion(accessor);
foreach (AttributeSection section in accessor.Attributes) {
@ -623,13 +627,13 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Events
public override IEntity VisitEventDeclaration(EventDeclaration eventDeclaration, object data)
public override IUnresolvedEntity VisitEventDeclaration(EventDeclaration eventDeclaration, object data)
{
bool isSingleEvent = eventDeclaration.Variables.Count == 1;
Modifiers modifiers = eventDeclaration.Modifiers;
DefaultEvent ev = null;
DefaultUnresolvedEvent ev = null;
foreach (VariableInitializer vi in eventDeclaration.Variables) {
ev = new DefaultEvent(currentTypeDefinition, vi.Name);
ev = new DefaultUnresolvedEvent(currentTypeDefinition, vi.Name);
ev.Region = isSingleEvent ? MakeRegion(eventDeclaration) : MakeRegion(vi);
ev.BodyRegion = MakeRegion(vi);
@ -639,10 +643,10 @@ namespace ICSharpCode.NRefactory.CSharp
ev.ReturnType = ConvertType(eventDeclaration.ReturnType);
if (eventDeclaration.Attributes.Any(a => a.AttributeTarget == "method")) {
ev.AddAccessor = ev.RemoveAccessor = new DefaultAccessor { Accessibility = ev.Accessibility };
ev.AddAccessor = ev.RemoveAccessor = new DefaultUnresolvedAccessor { Accessibility = ev.Accessibility };
} else {
// if there's no attributes on the accessors, we can re-use the shared accessor instance
ev.AddAccessor = ev.RemoveAccessor = DefaultAccessor.GetFromAccessibility(ev.Accessibility);
ev.AddAccessor = ev.RemoveAccessor = DefaultUnresolvedAccessor.GetFromAccessibility(ev.Accessibility);
}
foreach (AttributeSection section in eventDeclaration.Attributes) {
if (section.AttributeTarget == "method") {
@ -653,7 +657,7 @@ namespace ICSharpCode.NRefactory.CSharp
}
}
currentTypeDefinition.Events.Add(ev);
currentTypeDefinition.Members.Add(ev);
if (interningProvider != null) {
ev.ApplyInterningProvider(interningProvider);
}
@ -661,9 +665,9 @@ namespace ICSharpCode.NRefactory.CSharp
return isSingleEvent ? ev : null;
}
public override IEntity VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration, object data)
public override IUnresolvedEntity VisitCustomEventDeclaration(CustomEventDeclaration eventDeclaration, object data)
{
DefaultEvent e = new DefaultEvent(currentTypeDefinition, eventDeclaration.Name);
DefaultUnresolvedEvent e = new DefaultUnresolvedEvent(currentTypeDefinition, eventDeclaration.Name);
e.Region = MakeRegion(eventDeclaration);
e.BodyRegion = MakeBraceRegion(eventDeclaration);
ApplyModifiers(e, eventDeclaration.Modifiers);
@ -678,7 +682,7 @@ namespace ICSharpCode.NRefactory.CSharp
e.AddAccessor = ConvertAccessor(eventDeclaration.AddAccessor, e.Accessibility);
e.RemoveAccessor = ConvertAccessor(eventDeclaration.RemoveAccessor, e.Accessibility);
currentTypeDefinition.Events.Add(e);
currentTypeDefinition.Members.Add(e);
if (interningProvider != null) {
e.ApplyInterningProvider(interningProvider);
}
@ -687,7 +691,7 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Modifiers
static void ApplyModifiers(DefaultTypeDefinition td, Modifiers modifiers)
static void ApplyModifiers(DefaultUnresolvedTypeDefinition td, Modifiers modifiers)
{
td.Accessibility = GetAccessibility(modifiers) ?? (td.DeclaringTypeDefinition != null ? Accessibility.Private : Accessibility.Internal);
td.IsAbstract = (modifiers & (Modifiers.Abstract | Modifiers.Static)) != 0;
@ -695,7 +699,7 @@ namespace ICSharpCode.NRefactory.CSharp
td.IsShadowing = (modifiers & Modifiers.New) != 0;
}
static void ApplyModifiers(TypeSystem.Implementation.AbstractMember m, Modifiers modifiers)
static void ApplyModifiers(AbstractUnresolvedMember m, Modifiers modifiers)
{
// members from interfaces are always Public+Abstract.
if (m.DeclaringTypeDefinition.Kind == TypeKind.Interface) {
@ -732,7 +736,7 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Attributes
public override IEntity VisitAttributeSection(AttributeSection attributeSection, object data)
public override IUnresolvedEntity VisitAttributeSection(AttributeSection attributeSection, object data)
{
// non-assembly attributes are handled by their parent entity
if (attributeSection.AttributeTarget == "assembly") {
@ -743,23 +747,23 @@ namespace ICSharpCode.NRefactory.CSharp
return null;
}
void ConvertAttributes(IList<IAttribute> outputList, IEnumerable<AttributeSection> attributes)
void ConvertAttributes(IList<IUnresolvedAttribute> outputList, IEnumerable<AttributeSection> attributes)
{
foreach (AttributeSection section in attributes) {
ConvertAttributes(outputList, section);
}
}
void ConvertAttributes(IList<IAttribute> outputList, AttributeSection attributeSection)
void ConvertAttributes(IList<IUnresolvedAttribute> outputList, AttributeSection attributeSection)
{
foreach (CSharp.Attribute attr in attributeSection.Attributes) {
outputList.Add(ConvertAttribute(attr));
}
}
internal static ITypeReference ConvertAttributeType(AstType type, ITypeDefinition parentTypeDefinition, IMethod parentMethodDefinition, UsingScope parentUsingScope)
internal static ITypeReference ConvertAttributeType(AstType type)
{
ITypeReference tr = ConvertType(type, parentTypeDefinition, parentMethodDefinition, parentUsingScope, SimpleNameLookupMode.Type);
ITypeReference tr = ConvertType(type, SimpleNameLookupMode.Type);
if (!type.GetChildByRole(AstNode.Roles.Identifier).IsVerbatim) {
// Try to add "Attribute" suffix, but only if the identifier
// (=last identifier in fully qualified name) isn't a verbatim identifier.
@ -773,10 +777,10 @@ namespace ICSharpCode.NRefactory.CSharp
return tr;
}
IAttribute ConvertAttribute(CSharp.Attribute attr)
CSharpAttribute ConvertAttribute(CSharp.Attribute attr)
{
DomRegion region = MakeRegion(attr);
ITypeReference type = ConvertAttributeType(attr.Type, currentTypeDefinition, currentMethod, usingScope);
ITypeReference type = ConvertAttributeType(attr.Type);
List<IConstantValue> positionalArguments = null;
List<KeyValuePair<string, IConstantValue>> namedCtorArguments = null;
List<KeyValuePair<string, IConstantValue>> namedArguments = null;
@ -805,110 +809,111 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Types
ITypeReference ConvertType(AstType type, SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
{
return ConvertType(type, currentTypeDefinition, currentMethod, usingScope, lookupMode);
}
internal static ITypeReference ConvertType(AstType type, ITypeDefinition parentTypeDefinition, IMethod parentMethodDefinition, UsingScope parentUsingScope, SimpleNameLookupMode lookupMode)
public static ITypeReference ConvertType(AstType type, SimpleNameLookupMode lookupMode = SimpleNameLookupMode.Type)
{
SimpleType s = type as SimpleType;
if (s != null) {
List<ITypeReference> typeArguments = new List<ITypeReference>();
foreach (var ta in s.TypeArguments) {
typeArguments.Add(ConvertType(ta, parentTypeDefinition, parentMethodDefinition, parentUsingScope, lookupMode));
}
if (typeArguments.Count == 0 && parentMethodDefinition != null) {
// SimpleTypeOrNamespaceReference doesn't have a 'current method' context
// so we have to handle method type parameters here.
foreach (ITypeParameter tp in parentMethodDefinition.TypeParameters) {
if (tp.Name == s.Identifier)
return tp;
}
typeArguments.Add(ConvertType(ta, lookupMode));
}
if (typeArguments.Count == 0 && string.IsNullOrEmpty(s.Identifier)) {
// empty SimpleType is used for typeof(List<>).
return SharedTypes.UnboundTypeArgument;
return SpecialType.UnboundTypeArgument;
}
return new SimpleTypeOrNamespaceReference(s.Identifier, typeArguments, parentTypeDefinition, parentUsingScope, lookupMode);
return new SimpleTypeOrNamespaceReference(s.Identifier, typeArguments, lookupMode);
}
PrimitiveType p = type as PrimitiveType;
if (p != null) {
switch (p.Keyword) {
case "string":
return KnownTypeReference.String;
case "int":
return KnownTypeReference.Int32;
case "uint":
return KnownTypeReference.UInt32;
case "object":
return KnownTypeReference.Object;
case "bool":
return KnownTypeReference.Boolean;
case "sbyte":
return KnownTypeReference.SByte;
case "byte":
return KnownTypeReference.Byte;
case "short":
return KnownTypeReference.Int16;
case "ushort":
return KnownTypeReference.UInt16;
case "long":
return KnownTypeReference.Int64;
case "ulong":
return KnownTypeReference.UInt64;
case "float":
return KnownTypeReference.Single;
case "double":
return KnownTypeReference.Double;
case "decimal":
return KnownTypeReference.Decimal;
case "char":
return KnownTypeReference.Char;
case "void":
return KnownTypeReference.Void;
default:
return SharedTypes.UnknownType;
}
return ConvertPrimitiveType(p.Keyword);
}
MemberType m = type as MemberType;
if (m != null) {
ITypeOrNamespaceReference t;
TypeOrNamespaceReference t;
if (m.IsDoubleColon) {
SimpleType st = m.Target as SimpleType;
if (st != null) {
t = new AliasNamespaceReference(st.Identifier, parentUsingScope);
t = new AliasNamespaceReference(st.Identifier);
} else {
t = null;
}
} else {
t = ConvertType(m.Target, parentTypeDefinition, parentMethodDefinition, parentUsingScope, lookupMode) as ITypeOrNamespaceReference;
t = ConvertType(m.Target, lookupMode) as TypeOrNamespaceReference;
}
if (t == null)
return SharedTypes.UnknownType;
return SpecialType.UnknownType;
List<ITypeReference> typeArguments = new List<ITypeReference>();
foreach (var ta in m.TypeArguments) {
typeArguments.Add(ConvertType(ta, parentTypeDefinition, parentMethodDefinition, parentUsingScope, lookupMode));
typeArguments.Add(ConvertType(ta, lookupMode));
}
return new MemberTypeOrNamespaceReference(t, m.MemberName, typeArguments, parentTypeDefinition, parentUsingScope);
return new MemberTypeOrNamespaceReference(t, m.MemberName, typeArguments);
}
ComposedType c = type as ComposedType;
if (c != null) {
ITypeReference t = ConvertType(c.BaseType, parentTypeDefinition, parentMethodDefinition, parentUsingScope, lookupMode);
ITypeReference t = ConvertType(c.BaseType, lookupMode);
if (c.HasNullableSpecifier) {
t = NullableType.Create(t);
}
for (int i = 0; i < c.PointerRank; i++) {
t = PointerTypeReference.Create(t);
t = new PointerTypeReference(t);
}
foreach (var a in c.ArraySpecifiers.Reverse()) {
t = ArrayTypeReference.Create(t, a.Dimensions);
t = new ArrayTypeReference(t, a.Dimensions);
}
return t;
}
Debug.WriteLine("Unknown node used as type: " + type);
return SharedTypes.UnknownType;
return SpecialType.UnknownType;
}
public static ITypeReference ConvertPrimitiveType(string keyword)
{
KnownTypeCode typeCode = GetTypeCodeForPrimitiveType(keyword);
if (typeCode == KnownTypeCode.None)
return SpecialType.UnknownType;
else
return KnownTypeReference.Get(typeCode);
}
public static KnownTypeCode GetTypeCodeForPrimitiveType(string keyword)
{
switch (keyword) {
case "string":
return KnownTypeCode.String;
case "int":
return KnownTypeCode.Int32;
case "uint":
return KnownTypeCode.UInt32;
case "object":
return KnownTypeCode.Object;
case "bool":
return KnownTypeCode.Boolean;
case "sbyte":
return KnownTypeCode.SByte;
case "byte":
return KnownTypeCode.Byte;
case "short":
return KnownTypeCode.Int16;
case "ushort":
return KnownTypeCode.UInt16;
case "long":
return KnownTypeCode.Int64;
case "ulong":
return KnownTypeCode.UInt64;
case "float":
return KnownTypeCode.Single;
case "double":
return KnownTypeCode.Double;
case "decimal":
return KnownTypeCode.Decimal;
case "char":
return KnownTypeCode.Char;
case "void":
return KnownTypeCode.Void;
default:
return KnownTypeCode.None;
}
}
#endregion
@ -918,10 +923,11 @@ namespace ICSharpCode.NRefactory.CSharp
return ConvertConstantValue(targetType, expression, currentTypeDefinition, currentMethod, usingScope);
}
internal static IConstantValue ConvertConstantValue(ITypeReference targetType, AstNode expression,
ITypeDefinition parentTypeDefinition, IMethod parentMethodDefinition, UsingScope parentUsingScope)
internal static IConstantValue ConvertConstantValue(
ITypeReference targetType, AstNode expression,
IUnresolvedTypeDefinition parentTypeDefinition, IUnresolvedMethod parentMethodDefinition, UsingScope parentUsingScope)
{
ConstantValueBuilder b = new ConstantValueBuilder(parentTypeDefinition, parentMethodDefinition, parentUsingScope, false);
ConstantValueBuilder b = new ConstantValueBuilder(false);
ConstantExpression c = expression.AcceptVisitor(b, null);
if (c == null)
return new ErrorConstantValue(targetType);
@ -931,44 +937,24 @@ namespace ICSharpCode.NRefactory.CSharp
return new SimpleConstantValue(targetType, pc.Value);
}
// cast to the desired type
return new CSharpConstantValue(new ConstantCast(targetType, c), parentUsingScope, parentTypeDefinition);
return new ConstantCast(targetType, c);
}
IConstantValue ConvertAttributeArgument(Expression expression)
{
ConstantValueBuilder b = new ConstantValueBuilder(currentTypeDefinition, currentMethod, usingScope, true);
ConstantExpression c = expression.AcceptVisitor(b, null);
if (c == null)
return null;
PrimitiveConstantExpression pc = c as PrimitiveConstantExpression;
if (pc != null) {
// Save memory by directly using a SimpleConstantValue.
return new SimpleConstantValue(pc.Type, pc.Value);
} else {
return new CSharpConstantValue(c, usingScope, currentTypeDefinition);
}
ConstantValueBuilder b = new ConstantValueBuilder(true);
return expression.AcceptVisitor(b, null);
}
sealed class ConstantValueBuilder : DepthFirstAstVisitor<object, ConstantExpression>
{
readonly ITypeDefinition currentTypeDefinition;
readonly IMethod currentMethod;
readonly UsingScope usingScope;
readonly bool isAttributeArgument;
public ConstantValueBuilder(ITypeDefinition currentTypeDefinition, IMethod currentMethod, UsingScope usingScope, bool isAttributeArgument)
public ConstantValueBuilder(bool isAttributeArgument)
{
this.currentTypeDefinition = currentTypeDefinition;
this.currentMethod = currentMethod;
this.usingScope = usingScope;
this.isAttributeArgument = isAttributeArgument;
}
ITypeReference ConvertType(AstType type)
{
return TypeSystemConvertVisitor.ConvertType(type, currentTypeDefinition, currentMethod, usingScope, SimpleNameLookupMode.Type);
}
protected override ConstantExpression VisitChildren(AstNode node, object data)
{
return null;
@ -1102,7 +1088,7 @@ namespace ICSharpCode.NRefactory.CSharp
} else {
type = ConvertType(arrayCreateExpression.Type);
foreach (var spec in arrayCreateExpression.AdditionalArraySpecifiers.Reverse()) {
type = ArrayTypeReference.Create(type, spec.Dimensions);
type = new ArrayTypeReference(type, spec.Dimensions);
}
}
ConstantExpression[] elements = new ConstantExpression[initializer.Elements.Count];
@ -1122,20 +1108,20 @@ namespace ICSharpCode.NRefactory.CSharp
#endregion
#region Parameters
void ConvertParameters(IList<IParameter> outputList, IEnumerable<ParameterDeclaration> parameters)
void ConvertParameters(IList<IUnresolvedParameter> outputList, IEnumerable<ParameterDeclaration> parameters)
{
foreach (ParameterDeclaration pd in parameters) {
DefaultParameter p = new DefaultParameter(ConvertType(pd.Type), pd.Name);
DefaultUnresolvedParameter p = new DefaultUnresolvedParameter(ConvertType(pd.Type), pd.Name);
p.Region = MakeRegion(pd);
ConvertAttributes(p.Attributes, pd.Attributes);
switch (pd.ParameterModifier) {
case ParameterModifier.Ref:
p.IsRef = true;
p.Type = ByReferenceTypeReference.Create(p.Type);
p.Type = new ByReferenceTypeReference(p.Type);
break;
case ParameterModifier.Out:
p.IsOut = true;
p.Type = ByReferenceTypeReference.Create(p.Type);
p.Type = new ByReferenceTypeReference(p.Type);
break;
case ParameterModifier.Params:
p.IsParams = true;

Просмотреть файл

@ -19,10 +19,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.CSharp.Resolver
namespace ICSharpCode.NRefactory.CSharp.TypeSystem
{
/// <summary>
/// Represents a scope that contains "using" statements.
@ -31,33 +32,21 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[Serializable]
public class UsingScope : AbstractFreezable
{
readonly IProjectContent projectContent;
readonly UsingScope parent;
DomRegion region;
string namespaceName = "";
IList<ITypeOrNamespaceReference> usings;
IList<KeyValuePair<string, ITypeOrNamespaceReference>> usingAliases;
IList<TypeOrNamespaceReference> usings;
IList<KeyValuePair<string, TypeOrNamespaceReference>> usingAliases;
IList<string> externAliases;
//IList<UsingScope> childScopes;
protected override void FreezeInternal()
{
if (usings == null || usings.Count == 0)
usings = EmptyList<ITypeOrNamespaceReference>.Instance;
else
usings = Array.AsReadOnly(usings.ToArray());
if (usingAliases == null || usingAliases.Count == 0)
usingAliases = EmptyList<KeyValuePair<string, ITypeOrNamespaceReference>>.Instance;
else
usingAliases = Array.AsReadOnly(usingAliases.ToArray());
externAliases = FreezeList(externAliases);
//childScopes = FreezeList(childScopes);
usings = FreezableHelper.FreezeList(usings);
usingAliases = FreezableHelper.FreezeList(usingAliases);
externAliases = FreezableHelper.FreezeList(externAliases);
// In current model (no child scopes), it makes sense to freeze the parent as well
// to ensure the whole lookup chain is immutable.
// But we probably shouldn't do this if we add back childScopes.
if (parent != null)
parent.Freeze();
@ -67,11 +56,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary>
/// Creates a new root using scope.
/// </summary>
public UsingScope(IProjectContent projectContent)
public UsingScope()
{
if (projectContent == null)
throw new ArgumentNullException("projectContent");
this.projectContent = projectContent;
}
/// <summary>
@ -86,7 +72,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
if (namespaceName == null)
throw new ArgumentNullException("namespaceName");
this.parent = parent;
this.projectContent = parent.projectContent;
this.namespaceName = namespaceName;
}
@ -94,14 +79,10 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
get { return parent; }
}
public IProjectContent ProjectContent {
get { return projectContent; }
}
public DomRegion Region {
get { return region; }
set {
CheckBeforeMutation();
FreezableHelper.ThrowIfFrozen(this);
region = value;
}
}
@ -111,23 +92,23 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
set {
if (value == null)
throw new ArgumentNullException("NamespaceName");
CheckBeforeMutation();
FreezableHelper.ThrowIfFrozen(this);
namespaceName = value;
}
}
public IList<ITypeOrNamespaceReference> Usings {
public IList<TypeOrNamespaceReference> Usings {
get {
if (usings == null)
usings = new List<ITypeOrNamespaceReference>();
usings = new List<TypeOrNamespaceReference>();
return usings;
}
}
public IList<KeyValuePair<string, ITypeOrNamespaceReference>> UsingAliases {
public IList<KeyValuePair<string, TypeOrNamespaceReference>> UsingAliases {
get {
if (usingAliases == null)
usingAliases = new List<KeyValuePair<string, ITypeOrNamespaceReference>>();
usingAliases = new List<KeyValuePair<string, TypeOrNamespaceReference>>();
return usingAliases;
}
}
@ -162,5 +143,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
return externAliases != null && externAliases.Contains(identifier);
}
/// <summary>
/// Resolves the namespace represented by this using scope.
/// </summary>
public INamespace ResolveNamespace(ICompilation compilation)
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -172,7 +172,7 @@ namespace ICSharpCode.NRefactory.Demo
}
}
Lazy<IList<IProjectContent>> builtInLibs = new Lazy<IList<IProjectContent>>(
Lazy<IList<IUnresolvedAssembly>> builtInLibs = new Lazy<IList<IUnresolvedAssembly>>(
delegate {
Assembly[] assemblies = {
typeof(object).Assembly, // mscorlib
@ -183,7 +183,7 @@ namespace ICSharpCode.NRefactory.Demo
// typeof(Form).Assembly, // System.Windows.Forms.dll
typeof(ICSharpCode.NRefactory.TypeSystem.IProjectContent).Assembly,
};
IProjectContent[] projectContents = new IProjectContent[assemblies.Length];
IUnresolvedAssembly[] projectContents = new IUnresolvedAssembly[assemblies.Length];
Stopwatch total = Stopwatch.StartNew();
Parallel.For(
0, assemblies.Length,
@ -199,27 +199,23 @@ namespace ICSharpCode.NRefactory.Demo
void ResolveButtonClick(object sender, EventArgs e)
{
SimpleProjectContent project = new SimpleProjectContent();
var parsedFile = new TypeSystemConvertVisitor(project, "dummy.cs").Convert(compilationUnit);
project.UpdateProjectContent(null, parsedFile);
IProjectContent project = new CSharpProjectContent();
var parsedFile = compilationUnit.ToTypeSystem("dummy.cs");
project = project.UpdateProjectContent(null, parsedFile);
project = project.AddAssemblyReferences(builtInLibs.Value);
List<ITypeResolveContext> projects = new List<ITypeResolveContext>();
projects.Add(project);
projects.AddRange(builtInLibs.Value);
ICompilation compilation = project.CreateCompilation();
CSharpResolver resolver = new CSharpResolver(compilation);
using (var context = new CompositeTypeResolveContext(projects).Synchronize()) {
CSharpResolver resolver = new CSharpResolver(context);
IResolveVisitorNavigator navigator = null;
if (csharpTreeView.SelectedNode != null) {
navigator = new NodeListResolveVisitorNavigator(new[] { (AstNode)csharpTreeView.SelectedNode.Tag });
}
ResolveVisitor visitor = new ResolveVisitor(resolver, parsedFile, navigator);
visitor.Scan(compilationUnit);
csharpTreeView.BeginUpdate();
ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
csharpTreeView.EndUpdate();
IResolveVisitorNavigator navigator = null;
if (csharpTreeView.SelectedNode != null) {
navigator = new NodeListResolveVisitorNavigator(new[] { (AstNode)csharpTreeView.SelectedNode.Tag });
}
ResolveVisitor visitor = new ResolveVisitor(resolver, parsedFile, navigator);
visitor.Scan(compilationUnit);
csharpTreeView.BeginUpdate();
ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
csharpTreeView.EndUpdate();
}
void ShowResolveResultsInTree(TreeNodeCollection c, ResolveVisitor v)
@ -256,49 +252,45 @@ namespace ICSharpCode.NRefactory.Demo
if (csharpTreeView.SelectedNode == null)
return;
SimpleProjectContent project = new SimpleProjectContent();
var parsedFile = new TypeSystemConvertVisitor(project, "dummy.cs").Convert(compilationUnit);
project.UpdateProjectContent(null, parsedFile);
IProjectContent project = new CSharpProjectContent();
var parsedFile = compilationUnit.ToTypeSystem("dummy.cs");
project = project.UpdateProjectContent(null, parsedFile);
project = project.AddAssemblyReferences(builtInLibs.Value);
List<ITypeResolveContext> projects = new List<ITypeResolveContext>();
projects.Add(project);
projects.AddRange(builtInLibs.Value);
ICompilation compilation = project.CreateCompilation();
CSharpResolver resolver = new CSharpResolver(compilation);
using (var context = new CompositeTypeResolveContext(projects).Synchronize()) {
CSharpResolver resolver = new CSharpResolver(context);
AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag;
IResolveVisitorNavigator navigator = new NodeListResolveVisitorNavigator(new[] { node });
ResolveVisitor visitor = new ResolveVisitor(resolver, parsedFile, navigator);
visitor.Scan(compilationUnit);
IEntity entity;
MemberResolveResult mrr = visitor.GetResolveResult(node) as MemberResolveResult;
TypeResolveResult trr = visitor.GetResolveResult(node) as TypeResolveResult;
if (mrr != null) {
entity = mrr.Member;
} else if (trr != null) {
entity = trr.Type.GetDefinition();
} else {
return;
}
FindReferences fr = new FindReferences();
int referenceCount = 0;
FoundReferenceCallback callback = delegate(AstNode matchNode, ResolveResult result) {
referenceCount++;
};
var searchScopes = fr.GetSearchScopes(entity);
navigator = new CompositeResolveVisitorNavigator(searchScopes.Select(s => s.GetNavigator(callback)).ToArray());
visitor = new ResolveVisitor(resolver, parsedFile, navigator);
visitor.Scan(compilationUnit);
csharpTreeView.BeginUpdate();
ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
csharpTreeView.EndUpdate();
MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName);
AstNode node = (AstNode)csharpTreeView.SelectedNode.Tag;
IResolveVisitorNavigator navigator = new NodeListResolveVisitorNavigator(new[] { node });
ResolveVisitor visitor = new ResolveVisitor(resolver, parsedFile, navigator);
visitor.Scan(compilationUnit);
IEntity entity;
MemberResolveResult mrr = visitor.GetResolveResult(node) as MemberResolveResult;
TypeResolveResult trr = visitor.GetResolveResult(node) as TypeResolveResult;
if (mrr != null) {
entity = mrr.Member;
} else if (trr != null) {
entity = trr.Type.GetDefinition();
} else {
return;
}
FindReferences fr = new FindReferences();
int referenceCount = 0;
FoundReferenceCallback callback = delegate(AstNode matchNode, ResolveResult result) {
referenceCount++;
};
var searchScopes = fr.GetSearchScopes(entity);
navigator = new CompositeResolveVisitorNavigator(searchScopes.Select(s => s.GetNavigator(callback)).ToArray());
visitor = new ResolveVisitor(resolver, parsedFile, navigator);
visitor.Scan(compilationUnit);
csharpTreeView.BeginUpdate();
ShowResolveResultsInTree(csharpTreeView.Nodes, visitor);
csharpTreeView.EndUpdate();
MessageBox.Show("Found " + referenceCount + " references to " + entity.FullName);
}
}
}

Просмотреть файл

@ -28,9 +28,9 @@ namespace ICSharpCode.NRefactory.CSharp
[TestFixture]
public class CSharpAmbienceTests
{
IProjectContent mscorlib;
IProjectContent myLib;
CompositeTypeResolveContext compositeContext;
IUnresolvedAssembly mscorlib;
IUnresolvedAssembly myLib;
ICompilation compilation;
CSharpAmbience ambience;
public CSharpAmbienceTests()
@ -40,16 +40,16 @@ namespace ICSharpCode.NRefactory.CSharp
var loader = new CecilLoader();
loader.IncludeInternalMembers = true;
myLib = loader.LoadAssemblyFile(typeof(CSharpAmbienceTests).Assembly.Location);
compositeContext = new CompositeTypeResolveContext(new[] { mscorlib, myLib });
compilation = new SimpleCompilation(myLib, mscorlib);
}
#region ITypeDefinition tests
[Test]
public void GenericType()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(Dictionary<,>));
var typeDef = compilation.FindType(typeof(Dictionary<,>)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.UseFullyQualifiedMemberNames | ConversionFlags.ShowTypeParameterList;
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("System.Collections.Generic.Dictionary<TKey, TValue>", result);
}
@ -57,9 +57,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void GenericTypeShortName()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(Dictionary<,>));
var typeDef = compilation.FindType(typeof(Dictionary<,>)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("Dictionary<TKey, TValue>", result);
}
@ -67,9 +67,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void SimpleType()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(Object));
var typeDef = compilation.FindType(typeof(Object)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.UseFullyQualifiedMemberNames | ConversionFlags.ShowTypeParameterList;
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("System.Object", result);
}
@ -77,9 +77,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void SimpleTypeDefinition()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(Object));
var typeDef = compilation.FindType(typeof(Object)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.All & ~(ConversionFlags.UseFullyQualifiedMemberNames);
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("public class Object", result);
}
@ -87,9 +87,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void SimpleTypeDefinitionWithoutModifiers()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(Object));
var typeDef = compilation.FindType(typeof(Object)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.All & ~(ConversionFlags.UseFullyQualifiedMemberNames | ConversionFlags.ShowModifiers | ConversionFlags.ShowAccessibility);
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("class Object", result);
}
@ -97,9 +97,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void GenericTypeDefinitionFull()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(List<>));
var typeDef = compilation.FindType(typeof(List<>)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.All;
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("public class System.Collections.Generic.List<T>", result);
}
@ -107,9 +107,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void SimpleTypeShortName()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(Object));
var typeDef = compilation.FindType(typeof(Object)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("Object", result);
}
@ -117,9 +117,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void GenericTypeWithNested()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(List<>.Enumerator));
var typeDef = compilation.FindType(typeof(List<>.Enumerator)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.UseFullyQualifiedMemberNames | ConversionFlags.ShowTypeParameterList;
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("System.Collections.Generic.List<T>.Enumerator", result);
}
@ -127,9 +127,9 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void GenericTypeWithNestedShortName()
{
var typeDef = mscorlib.GetTypeDefinition(typeof(List<>.Enumerator));
var typeDef = compilation.FindType(typeof(List<>.Enumerator)).GetDefinition();
ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;
string result = ambience.ConvertEntity(typeDef, mscorlib);
string result = ambience.ConvertEntity(typeDef);
Assert.AreEqual("List<T>.Enumerator", result);
}
@ -139,34 +139,31 @@ namespace ICSharpCode.NRefactory.CSharp
[Test]
public void SimpleField()
{
var field = typeof(CSharpAmbienceTests.Program).ToTypeReference().Resolve(myLib)
.GetDefinition().Fields.Single(f => f.Name == "test");
var field = compilation.FindType(typeof(CSharpAmbienceTests.Program)).GetFields(f => f.Name == "test").Single();
ambience.ConversionFlags = ConversionFlags.All;
string result = ambience.ConvertEntity(field, compositeContext);
string result = ambience.ConvertEntity(field);
Assert.AreEqual("private int ICSharpCode.NRefactory.CSharp.CSharpAmbienceTests.Program.test", result);
Assert.AreEqual("private int ICSharpCode.NRefactory.CSharp.CSharpAmbienceTests.Program.test;", result);
}
[Test]
public void SimpleConstField()
{
var field = typeof(CSharpAmbienceTests.Program).ToTypeReference().Resolve(myLib)
.GetDefinition().Fields.Single(f => f.Name == "TEST2");
var field = compilation.FindType(typeof(CSharpAmbienceTests.Program)).GetFields(f => f.Name == "TEST2").Single();
ambience.ConversionFlags = ConversionFlags.All;
string result = ambience.ConvertEntity(field, compositeContext);
string result = ambience.ConvertEntity(field);
Assert.AreEqual("private const int ICSharpCode.NRefactory.CSharp.CSharpAmbienceTests.Program.TEST2", result);
Assert.AreEqual("private const int ICSharpCode.NRefactory.CSharp.CSharpAmbienceTests.Program.TEST2;", result);
}
[Test]
public void SimpleFieldWithoutModifiers()
{
var field = typeof(CSharpAmbienceTests.Program).ToTypeReference().Resolve(myLib)
.GetDefinition().Fields.Single(f => f.Name == "test");
var field = compilation.FindType(typeof(CSharpAmbienceTests.Program)).GetFields(f => f.Name == "test").Single();
ambience.ConversionFlags = ConversionFlags.All & ~(ConversionFlags.UseFullyQualifiedMemberNames | ConversionFlags.ShowModifiers | ConversionFlags.ShowAccessibility);
string result = ambience.ConvertEntity(field, compositeContext);
string result = ambience.ConvertEntity(field);
Assert.AreEqual("int test", result);
Assert.AreEqual("int test;", result);
}
#endregion

Просмотреть файл

@ -17,14 +17,8 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Text.RegularExpressions;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using Microsoft.CSharp;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp
@ -33,27 +27,32 @@ namespace ICSharpCode.NRefactory.CSharp
public class CodeDomConvertVisitorTests : ResolverTestBase
{
CodeDomConvertVisitor convertVisitor;
CSharpResolver resolver;
public override void SetUp()
{
base.SetUp();
AddUsing("System");
AddUsing("System.Collections.Generic");
AddUsing("System.Linq");
resolver.CurrentTypeDefinition = new DefaultTypeDefinition(project, string.Empty, "MyClass");
resolver = new CSharpResolver(compilation);
resolver.CurrentUsingScope = new UsingScope();
resolver.CurrentUsingScope.Usings.Add(MakeReference("System"));
resolver.CurrentUsingScope.Usings.Add(MakeReference("System.Collections.Generic"));
resolver.CurrentUsingScope.Usings.Add(MakeReference("System.Linq"));
convertVisitor = new CodeDomConvertVisitor();
convertVisitor.UseFullyQualifiedTypeNames = true;
}
string Convert(Expression expr)
{
throw new NotImplementedException();
/*
ResolveVisitor rv = new ResolveVisitor(resolver, null);
rv.Scan(expr);
var codeExpr = (CodeExpression)convertVisitor.Convert(expr, rv);
StringWriter writer = new StringWriter();
writer.NewLine = " ";
new CSharpCodeProvider().GenerateCodeFromExpression(codeExpr, writer, new CodeGeneratorOptions { IndentString = " " });
return Regex.Replace(writer.ToString(), @"\s+", " ");
return Regex.Replace(writer.ToString(), @"\s+", " ");*/
}
[Test]

Просмотреть файл

@ -19,7 +19,7 @@
using System;
using System.IO;
using ICSharpCode.NRefactory.Editor;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.TypeSystem;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Parser
@ -46,7 +46,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
[Test]
public void GenerateTypeSystem()
{
SimpleProjectContent pc = new SimpleProjectContent();
IProjectContent pc = new CSharpProjectContent();
CSharpParser parser = new CSharpParser();
parser.GenerateTypeSystemMode = true;
foreach (string fileName in fileNames) {
@ -54,8 +54,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan)) {
cu = parser.Parse(fs);
}
TypeSystemConvertVisitor cv = new TypeSystemConvertVisitor(pc, fileName);
pc.UpdateProjectContent(null, cv.Convert(cu));
pc = pc.UpdateProjectContent(null, cu.ToTypeSystem(fileName));
}
}

Просмотреть файл

@ -31,7 +31,7 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
[TestFixtureSetUp]
public void FixtureSetUp()
{
testCasePC = ParseTestCase();
compilation = ParseTestCase().CreateCompilation();
}
internal static IProjectContent ParseTestCase()
@ -44,11 +44,8 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
cu = parser.Parse(s);
}
var testCasePC = new SimpleProjectContent();
CSharpParsedFile parsedFile = new TypeSystemConvertVisitor(testCasePC, fileName).Convert(cu);
parsedFile.Freeze();
testCasePC.UpdateProjectContent(null, parsedFile);
return testCasePC;
var parsedFile = cu.ToTypeSystem(fileName);
return new CSharpProjectContent().UpdateProjectContent(null, parsedFile).AddAssemblyReferences(new[] { CecilLoaderTests.Mscorlib });
}
}
@ -62,7 +59,8 @@ namespace ICSharpCode.NRefactory.CSharp.Parser
using (MemoryStream ms = new MemoryStream()) {
serializer.Serialize(ms, TypeSystemConvertVisitorTests.ParseTestCase());
ms.Position = 0;
testCasePC = (IProjectContent)serializer.Deserialize(ms);
var pc = (IProjectContent)serializer.Deserialize(ms);
compilation = pc.CreateCompilation();
}
}
}

Просмотреть файл

@ -22,6 +22,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using NUnit.Framework;
@ -52,72 +53,71 @@ namespace OtherNS {
}
";
SimpleProjectContent pc;
ITypeResolveContext ctx;
IProjectContent pc;
ICompilation compilation;
ITypeDefinition baseClass, derivedClass, nestedClass, systemClass;
CSharpParsedFile parsedFile;
[SetUp]
public void SetUp()
{
pc = new SimpleProjectContent();
var cu = new CSharpParser().Parse(new StringReader(program));
parsedFile = new TypeSystemConvertVisitor(pc, "program.cs").Convert(cu);
pc.UpdateProjectContent(null, parsedFile);
pc = new CSharpProjectContent();
parsedFile = new CSharpParser().Parse(new StringReader(program)).ToTypeSystem("program.cs");
pc = pc.UpdateProjectContent(null, parsedFile);
pc = pc.AddAssemblyReferences(new [] { CecilLoaderTests.Mscorlib });
ctx = new CompositeTypeResolveContext(new[] { pc, CecilLoaderTests.Mscorlib });
compilation = pc.CreateCompilation();
baseClass = pc.GetTypeDefinition(string.Empty, "Base", 1, StringComparer.Ordinal);
baseClass = compilation.RootNamespace.GetTypeDefinition("Base", 1);
nestedClass = baseClass.NestedTypes.Single();
derivedClass = pc.GetTypeDefinition(string.Empty, "Derived", 2, StringComparer.Ordinal);
systemClass = pc.GetTypeDefinition("NS", "System", 0, StringComparer.Ordinal);
derivedClass = compilation.RootNamespace.GetTypeDefinition("Derived", 2);
systemClass = compilation.FindType("NS.System").GetDefinition();
}
TypeSystemAstBuilder CreateBuilder(ITypeDefinition currentTypeDef = null)
{
return new TypeSystemAstBuilder(
new CSharpResolver(ctx) {
new CSharpResolver(compilation) {
CurrentUsingScope = currentTypeDef != null ? parsedFile.GetUsingScope(currentTypeDef.Region.Begin) : parsedFile.RootUsingScope,
CurrentTypeDefinition = currentTypeDef
});
}
string TypeToString(ITypeReference type, ITypeDefinition currentTypeDef = null)
string TypeToString(IType type, ITypeDefinition currentTypeDef = null)
{
var builder = CreateBuilder(currentTypeDef);
IType resolvedType = type.Resolve(ctx);
AstType node = builder.ConvertType(resolvedType);
AstType node = builder.ConvertType(type);
return node.ToString();
}
[Test]
public void PrimitiveVoid()
{
Assert.AreEqual("void", TypeToString(KnownTypeReference.Void));
Assert.AreEqual("void", TypeToString(compilation.FindType(KnownTypeCode.Void)));
}
[Test]
public void PrimitiveInt()
{
Assert.AreEqual("int", TypeToString(KnownTypeReference.Int32));
Assert.AreEqual("int", TypeToString(compilation.FindType(KnownTypeCode.Int32)));
}
[Test]
public void PrimitiveDecimal()
{
Assert.AreEqual("decimal", TypeToString(KnownTypeReference.Decimal));
Assert.AreEqual("decimal", TypeToString(compilation.FindType(KnownTypeCode.Decimal)));
}
[Test]
public void SystemType()
{
Assert.AreEqual("Type", TypeToString(KnownTypeReference.Type));
Assert.AreEqual("Type", TypeToString(compilation.FindType(KnownTypeCode.Type)));
}
[Test]
public void ListOfNSSystem()
{
var type = new ParameterizedType(ctx.GetTypeDefinition(typeof(List<>)), new[] { systemClass });
var type = new ParameterizedType(compilation.FindType(typeof(List<>)).GetDefinition(), new[] { systemClass });
Assert.AreEqual("List<NS.System>", TypeToString(type));
Assert.AreEqual("List<System>", TypeToString(type, systemClass));
}
@ -125,26 +125,26 @@ namespace OtherNS {
[Test]
public void NonGenericIEnumerable()
{
Assert.AreEqual("System.Collections.IEnumerable", TypeToString(typeof(IEnumerable).ToTypeReference()));
Assert.AreEqual("System.Collections.IEnumerable", TypeToString(compilation.FindType(typeof(IEnumerable))));
}
[Test]
public void NonGenericIEnumerableWithSystemNamespaceCollision()
{
Assert.AreEqual("global::System.Collections.IEnumerable", TypeToString(typeof(IEnumerable).ToTypeReference(), systemClass));
Assert.AreEqual("global::System.Collections.IEnumerable", TypeToString(compilation.FindType(typeof(IEnumerable)), systemClass));
}
[Test]
public void AliasedNamespace()
{
var type = typeof(System.Reflection.Assembly).ToTypeReference();
var type = compilation.FindType(typeof(System.Reflection.Assembly));
Assert.AreEqual("R.Assembly", TypeToString(type, systemClass));
}
[Test]
public void AliasedType()
{
var type = new ParameterizedTypeReference(ctx.GetTypeDefinition(typeof(List<>)), new[] { KnownTypeReference.Char });
var type = new ParameterizedType(compilation.FindType(typeof(List<>)).GetDefinition(), new[] { compilation.FindType(KnownTypeCode.Char) });
Assert.AreEqual("List<char>", TypeToString(type));
Assert.AreEqual("L", TypeToString(type, systemClass));
}
@ -159,7 +159,7 @@ namespace OtherNS {
[Test]
public void NestedType()
{
var type = new ParameterizedTypeReference(nestedClass, new[] { KnownTypeReference.Char, KnownTypeReference.String });
var type = new ParameterizedType(nestedClass, new[] { compilation.FindType(KnownTypeCode.Char), compilation.FindType(KnownTypeCode.String) });
Assert.AreEqual("Base<char>.Nested<string>", TypeToString(type));
Assert.AreEqual("Base<char>.Nested<string>", TypeToString(type, baseClass));
Assert.AreEqual("Base<char>.Nested<string>", TypeToString(type, nestedClass));
@ -169,7 +169,7 @@ namespace OtherNS {
[Test]
public void NestedTypeInCurrentClass()
{
var type = new ParameterizedTypeReference(nestedClass, new[] { baseClass.TypeParameters[0], KnownTypeReference.String });
var type = new ParameterizedType(nestedClass, new[] { baseClass.TypeParameters[0], compilation.FindType(KnownTypeCode.String) });
Assert.AreEqual("Nested<string>", TypeToString(type, baseClass));
Assert.AreEqual("Nested<string>", TypeToString(type, nestedClass));
}
@ -177,36 +177,36 @@ namespace OtherNS {
[Test]
public void NestedTypeInDerivedClass()
{
var type1 = new ParameterizedTypeReference(nestedClass, new[] { derivedClass.TypeParameters[0], KnownTypeReference.String });
var type1 = new ParameterizedType(nestedClass, new[] { derivedClass.TypeParameters[0], compilation.FindType(KnownTypeCode.String) });
Assert.AreEqual("Base<T>.Nested<string>", TypeToString(type1, derivedClass));
var type2 = new ParameterizedTypeReference(nestedClass, new[] { derivedClass.TypeParameters[1], KnownTypeReference.String });
var type2 = new ParameterizedType(nestedClass, new[] { derivedClass.TypeParameters[1], compilation.FindType(KnownTypeCode.String) });
Assert.AreEqual("Nested<string>", TypeToString(type2, derivedClass));
}
[Test]
public void MultidimensionalArray()
{
Assert.AreEqual("byte[][,]", TypeToString(typeof(byte[][,]).ToTypeReference()));
Assert.AreEqual("byte[][,]", TypeToString(compilation.FindType(typeof(byte[][,]))));
}
[Test]
public void Pointer()
{
Assert.AreEqual("long*", TypeToString(typeof(long*).ToTypeReference()));
Assert.AreEqual("long*", TypeToString(compilation.FindType(typeof(long*))));
}
[Test]
public void NullableType()
{
Assert.AreEqual("ulong?", TypeToString(typeof(ulong?).ToTypeReference()));
Assert.AreEqual("ulong?", TypeToString(compilation.FindType(typeof(ulong?))));
}
[Test]
public void AmbiguousType()
{
Assert.AreEqual("System.Array", TypeToString(typeof(Array).ToTypeReference()));
Assert.AreEqual("OtherNS.Array", TypeToString(ctx.GetTypeDefinition("OtherNS", "Array", 0, StringComparer.Ordinal)));
Assert.AreEqual("System.Array", TypeToString(compilation.FindType(typeof(Array))));
Assert.AreEqual("OtherNS.Array", TypeToString(compilation.FindType("OtherNS.Array")));
}
}
}

Просмотреть файл

@ -58,7 +58,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
string program = "using System; [$LoaderOptimization(3)$] class Test { }";
var mrr = Resolve<CSharpInvocationResolveResult>(program);
Assert.AreEqual("System.LoaderOptimizationAttribute..ctor", mrr.Member.FullName);
Assert.AreEqual("System.Byte", mrr.Member.Parameters[0].Type.Resolve(context).FullName);
Assert.AreEqual("System.Byte", mrr.Member.Parameters[0].Type.FullName);
}
[Test]
@ -67,7 +67,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
string program = "using System; [$LoaderOptimization(LoaderOptimization.NotSpecified)$] class Test { }";
var mrr = Resolve<CSharpInvocationResolveResult>(program);
Assert.AreEqual("System.LoaderOptimizationAttribute..ctor", mrr.Member.FullName);
Assert.AreEqual("System.LoaderOptimization", mrr.Member.Parameters[0].Type.Resolve(context).FullName);
Assert.AreEqual("System.LoaderOptimization", mrr.Member.Parameters[0].Type.FullName);
}
[Test]
@ -103,7 +103,7 @@ enum E { A, B }
Assert.AreEqual("MyNamespace.E.A", result.Member.FullName);
}
[Test, Ignore("Not implemented in type system.")]
[Test]
public void SD_1384()
{
string program = @"using System;
@ -114,7 +114,7 @@ class Flags {
TypeResolveResult result = Resolve<TypeResolveResult>(program);
Assert.AreEqual("Flags.Test", result.Type.FullName);
var rt = result.Type.GetDefinition().Attributes[0].AttributeType.Resolve(context);
var rt = result.Type.GetDefinition().Attributes[0].AttributeType;
Assert.AreEqual("System.FlagsAttribute", rt.FullName);
}
}

Просмотреть файл

@ -29,6 +29,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public unsafe class BinaryOperatorTests : ResolverTestBase
{
CSharpResolver resolver;
public override void SetUp()
{
base.SetUp();
resolver = new CSharpResolver(compilation);
}
[Test]
public void Multiplication()
{
@ -509,7 +517,7 @@ class Test {
Assert.IsTrue(irr.IsLiftedOperatorInvocation);
Assert.AreEqual("A.op_Addition", irr.Member.FullName);
// even though we're calling the lifted operator, trr.Member should be the original operator method
Assert.AreEqual("S", irr.Member.ReturnType.Resolve(context).ReflectionName);
Assert.AreEqual("S", irr.Member.ReturnType.ReflectionName);
Assert.AreEqual("System.Nullable`1[[S]]", irr.Type.ReflectionName);
Conversion lhsConv = ((ConversionResolveResult)irr.Arguments[0]).Conversion;

Просмотреть файл

@ -29,9 +29,17 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public class CastTests : ResolverTestBase
{
CSharpResolver resolver;
public override void SetUp()
{
base.SetUp();
resolver = new CSharpResolver(compilation);
}
void TestCast(Type targetType, ResolveResult input, Conversion expectedConversion)
{
IType type = targetType.ToTypeReference().Resolve(context);
IType type = compilation.FindType(targetType);
ResolveResult rr = resolver.ResolveCast(type, input);
AssertType(targetType, rr);
Assert.AreEqual(typeof(ConversionResolveResult), rr.GetType());

Просмотреть файл

@ -29,6 +29,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public class ConditionalOperatorTests : ResolverTestBase
{
CSharpResolver resolver;
public override void SetUp()
{
base.SetUp();
resolver = new CSharpResolver(compilation);
}
void TestOperator(ResolveResult condition, ResolveResult trueExpr, ResolveResult falseExpr,
Conversion conditionConv, Conversion trueConv, Conversion falseConv,
Type expectedResultType)

Просмотреть файл

@ -35,20 +35,27 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public unsafe class ConversionsTest
{
ITypeResolveContext ctx = CecilLoaderTests.Mscorlib;
Conversions conversions = new Conversions(CecilLoaderTests.Mscorlib);
ICompilation compilation;
Conversions conversions;
[SetUp]
public void SetUp()
{
compilation = new SimpleCompilation(CecilLoaderTests.Mscorlib);
conversions = new Conversions(compilation);
}
Conversion ImplicitConversion(Type from, Type to)
{
IType from2 = from.ToTypeReference().Resolve(ctx);
IType to2 = to.ToTypeReference().Resolve(ctx);
IType from2 = compilation.FindType(from);
IType to2 = compilation.FindType(to);
return conversions.ImplicitConversion(from2, to2);
}
Conversion ExplicitConversion(Type from, Type to)
{
IType from2 = from.ToTypeReference().Resolve(ctx);
IType to2 = to.ToTypeReference().Resolve(ctx);
IType from2 = compilation.FindType(from);
IType to2 = compilation.FindType(to);
return conversions.ExplicitConversion(from2, to2);
}
@ -60,9 +67,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Assert.AreEqual(C.IdentityConversion, ImplicitConversion(typeof(object), typeof(object)));
Assert.AreEqual(C.None, ImplicitConversion(typeof(bool), typeof(char)));
Assert.AreEqual(C.IdentityConversion, conversions.ImplicitConversion(SharedTypes.Dynamic, SharedTypes.Dynamic));
Assert.AreEqual(C.IdentityConversion, conversions.ImplicitConversion(SharedTypes.UnknownType, SharedTypes.UnknownType));
Assert.AreEqual(C.IdentityConversion, conversions.ImplicitConversion(SharedTypes.Null, SharedTypes.Null));
Assert.AreEqual(C.IdentityConversion, conversions.ImplicitConversion(SpecialType.Dynamic, SpecialType.Dynamic));
Assert.AreEqual(C.IdentityConversion, conversions.ImplicitConversion(SpecialType.UnknownType, SpecialType.UnknownType));
Assert.AreEqual(C.IdentityConversion, conversions.ImplicitConversion(SpecialType.NullType, SpecialType.NullType));
}
[Test]
@ -246,14 +253,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[Test]
public void UnconstrainedTypeParameter()
{
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
DefaultTypeParameter t2 = new DefaultTypeParameter(EntityType.TypeDefinition, 1, "T2");
DefaultTypeParameter tm = new DefaultTypeParameter(EntityType.Method, 0, "TM");
ITypeParameter t = new DefaultResolvedTypeParameter(EntityType.TypeDefinition, 0, "T");
ITypeParameter t2 = new DefaultResolvedTypeParameter(EntityType.TypeDefinition, 1, "T2");
ITypeParameter tm = new DefaultResolvedTypeParameter(EntityType.Method, 0, "TM");
Assert.AreEqual(C.None, conversions.ImplicitConversion(SharedTypes.Null, t));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, KnownTypeReference.Object.Resolve(ctx)));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, SharedTypes.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(ValueType))));
Assert.AreEqual(C.None, conversions.ImplicitConversion(SpecialType.NullType, t));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, compilation.FindType(KnownTypeCode.Object)));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, SpecialType.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, compilation.FindType(typeof(ValueType))));
Assert.AreEqual(C.IdentityConversion, conversions.ImplicitConversion(t, t));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t2, t));
@ -265,65 +272,63 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[Test]
public void TypeParameterWithReferenceTypeConstraint()
{
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
t.HasReferenceTypeConstraint = true;
ITypeParameter t = new DefaultResolvedTypeParameter(EntityType.TypeDefinition, 0, "T", hasReferenceTypeConstraint: true);
Assert.AreEqual(C.NullLiteralConversion, conversions.ImplicitConversion(SharedTypes.Null, t));
Assert.AreEqual(C.ImplicitReferenceConversion, conversions.ImplicitConversion(t, KnownTypeReference.Object.Resolve(ctx)));
Assert.AreEqual(C.ImplicitReferenceConversion, conversions.ImplicitConversion(t, SharedTypes.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(ValueType))));
Assert.AreEqual(C.NullLiteralConversion, conversions.ImplicitConversion(SpecialType.NullType, t));
Assert.AreEqual(C.ImplicitReferenceConversion, conversions.ImplicitConversion(t, compilation.FindType(KnownTypeCode.Object)));
Assert.AreEqual(C.ImplicitReferenceConversion, conversions.ImplicitConversion(t, SpecialType.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, compilation.FindType(typeof(ValueType))));
}
[Test]
public void TypeParameterWithValueTypeConstraint()
{
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
t.HasValueTypeConstraint = true;
ITypeParameter t = new DefaultResolvedTypeParameter(EntityType.TypeDefinition, 0, "T", hasValueTypeConstraint: true);
Assert.AreEqual(C.None, conversions.ImplicitConversion(SharedTypes.Null, t));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, KnownTypeReference.Object.Resolve(ctx)));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, SharedTypes.Dynamic));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(ValueType))));
Assert.AreEqual(C.None, conversions.ImplicitConversion(SpecialType.NullType, t));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, compilation.FindType(KnownTypeCode.Object)));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, SpecialType.Dynamic));
Assert.AreEqual(C.BoxingConversion, conversions.ImplicitConversion(t, compilation.FindType(typeof(ValueType))));
}
[Test]
public void TypeParameterWithClassConstraint()
{
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
t.Constraints.Add(ctx.GetTypeDefinition(typeof(StringComparer)));
ITypeParameter t = new DefaultResolvedTypeParameter(EntityType.TypeDefinition, 0, "T",
constraints: new[] { compilation.FindType(typeof(StringComparer)) });
Assert.AreEqual(C.NullLiteralConversion,
conversions.ImplicitConversion(SharedTypes.Null, t));
conversions.ImplicitConversion(SpecialType.NullType, t));
Assert.AreEqual(C.ImplicitReferenceConversion,
conversions.ImplicitConversion(t, KnownTypeReference.Object.Resolve(ctx)));
conversions.ImplicitConversion(t, compilation.FindType(KnownTypeCode.Object)));
Assert.AreEqual(C.ImplicitReferenceConversion,
conversions.ImplicitConversion(t, SharedTypes.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(ValueType))));
conversions.ImplicitConversion(t, SpecialType.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, compilation.FindType(typeof(ValueType))));
Assert.AreEqual(C.ImplicitReferenceConversion,
conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(StringComparer))));
conversions.ImplicitConversion(t, compilation.FindType(typeof(StringComparer))));
Assert.AreEqual(C.ImplicitReferenceConversion,
conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(IComparer))));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, typeof(IComparer<int>).ToTypeReference().Resolve(ctx)));
conversions.ImplicitConversion(t, compilation.FindType(typeof(IComparer))));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, compilation.FindType(typeof(IComparer<int>))));
Assert.AreEqual(C.ImplicitReferenceConversion,
conversions.ImplicitConversion(t, typeof(IComparer<string>).ToTypeReference().Resolve(ctx)));
conversions.ImplicitConversion(t, compilation.FindType(typeof(IComparer<string>))));
}
[Test]
public void TypeParameterWithInterfaceConstraint()
{
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
t.Constraints.Add(ctx.GetTypeDefinition(typeof(IList)));
ITypeParameter t = new DefaultResolvedTypeParameter(EntityType.TypeDefinition, 0, "T",
constraints: new [] { compilation.FindType(typeof(IList)) });
Assert.AreEqual(C.None, conversions.ImplicitConversion(SharedTypes.Null, t));
Assert.AreEqual(C.None, conversions.ImplicitConversion(SpecialType.NullType, t));
Assert.AreEqual(C.BoxingConversion,
conversions.ImplicitConversion(t, KnownTypeReference.Object.Resolve(ctx)));
conversions.ImplicitConversion(t, compilation.FindType(KnownTypeCode.Object)));
Assert.AreEqual(C.BoxingConversion,
conversions.ImplicitConversion(t, SharedTypes.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(ValueType))));
conversions.ImplicitConversion(t, SpecialType.Dynamic));
Assert.AreEqual(C.None, conversions.ImplicitConversion(t, compilation.FindType(typeof(ValueType))));
Assert.AreEqual(C.BoxingConversion,
conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(IList))));
conversions.ImplicitConversion(t, compilation.FindType(typeof(IList))));
Assert.AreEqual(C.BoxingConversion,
conversions.ImplicitConversion(t, ctx.GetTypeDefinition(typeof(IEnumerable))));
conversions.ImplicitConversion(t, compilation.FindType(typeof(IEnumerable))));
}
[Test]
@ -349,9 +354,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Conversion IntegerLiteralConversion(object value, Type to)
{
IType fromType = value.GetType().ToTypeReference().Resolve(ctx);
IType fromType = compilation.FindType(value.GetType());
ConstantResolveResult crr = new ConstantResolveResult(fromType, value);
IType to2 = to.ToTypeReference().Resolve(ctx);
IType to2 = compilation.FindType(to);
return conversions.ImplicitConversion(crr, to2);
}
@ -426,18 +431,18 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
int BetterConversion(Type s, Type t1, Type t2)
{
IType sType = s.ToTypeReference().Resolve(ctx);
IType t1Type = t1.ToTypeReference().Resolve(ctx);
IType t2Type = t2.ToTypeReference().Resolve(ctx);
IType sType = compilation.FindType(s);
IType t1Type = compilation.FindType(t1);
IType t2Type = compilation.FindType(t2);
return conversions.BetterConversion(sType, t1Type, t2Type);
}
int BetterConversion(object value, Type t1, Type t2)
{
IType fromType = value.GetType().ToTypeReference().Resolve(ctx);
IType fromType = compilation.FindType(value.GetType());
ConstantResolveResult crr = new ConstantResolveResult(fromType, value);
IType t1Type = t1.ToTypeReference().Resolve(ctx);
IType t2Type = t2.ToTypeReference().Resolve(ctx);
IType t1Type = compilation.FindType(t1);
IType t2Type = compilation.FindType(t2);
return conversions.BetterConversion(crr, t1Type, t2Type);
}
@ -482,19 +487,25 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[Test]
public void ExpansiveInheritance()
{
SimpleProjectContent pc = new SimpleProjectContent();
DefaultTypeDefinition a = new DefaultTypeDefinition(pc, string.Empty, "A");
DefaultTypeDefinition b = new DefaultTypeDefinition(pc, string.Empty, "B");
var a = new DefaultUnresolvedTypeDefinition(string.Empty, "A");
var b = new DefaultUnresolvedTypeDefinition(string.Empty, "B");
// interface A<in U>
a.Kind = TypeKind.Interface;
a.TypeParameters.Add(new DefaultTypeParameter(EntityType.TypeDefinition, 0, "U") { Variance = VarianceModifier.Contravariant });
a.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "U") { Variance = VarianceModifier.Contravariant });
// interface B<X> : A<A<B<X>>> { }
DefaultTypeParameter x = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "X");
b.TypeParameters.Add(x);
b.BaseTypes.Add(new ParameterizedType(a, new[] { new ParameterizedType(a, new [] { new ParameterizedType(b, new [] { x }) } ) }));
b.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "X"));
b.BaseTypes.Add(new ParameterizedTypeReference(
a, new[] { new ParameterizedTypeReference(
a, new [] { new ParameterizedTypeReference(
b, new [] { new TypeParameterReference(EntityType.TypeDefinition, 0) }
) } ) }));
IType type1 = new ParameterizedType(b, new[] { KnownTypeReference.Double.Resolve(ctx) });
IType type2 = new ParameterizedType(a, new [] { new ParameterizedType(b, new[] { KnownTypeReference.String.Resolve(ctx) }) });
ICompilation compilation = new SimpleCompilation(CecilLoaderTests.Mscorlib);
ITypeDefinition resolvedA = a.Resolve(compilation.TypeResolveContext);
ITypeDefinition resolvedB = b.Resolve(compilation.TypeResolveContext);
IType type1 = new ParameterizedType(resolvedB, new[] { compilation.FindType(KnownTypeCode.Double) });
IType type2 = new ParameterizedType(resolvedA, new [] { new ParameterizedType(resolvedB, new[] { compilation.FindType(KnownTypeCode.String) }) });
Assert.IsFalse(conversions.ImplicitConversion(type1, type2));
}
}

Просмотреть файл

@ -53,18 +53,18 @@ namespace XN {
mrr = Resolve<CSharpInvocationResolveResult>(program.Replace("$", "$a.F(1)$"));
Assert.AreEqual("XN.XC.F", mrr.Member.FullName);
Assert.AreEqual("System.Int32", mrr.Member.Parameters[1].Type.Resolve(context).FullName);
Assert.AreEqual("System.Int32", mrr.Member.Parameters[1].Type.FullName);
mrr = Resolve<CSharpInvocationResolveResult>(program.Replace("$", "$a.F(\"text\")$"));
Assert.AreEqual("XN.XC.F", mrr.Member.FullName);
Assert.AreEqual("System.String", mrr.Member.Parameters[1].Type.Resolve(context).FullName);
Assert.AreEqual("System.String", mrr.Member.Parameters[1].Type.FullName);
mrr = Resolve<CSharpInvocationResolveResult>(program.Replace("$", "$b.F(1)$"));
Assert.AreEqual("B.F", mrr.Member.FullName);
mrr = Resolve<CSharpInvocationResolveResult>(program.Replace("$", "$b.F(\"text\")$"));
Assert.AreEqual("XN.XC.F", mrr.Member.FullName);
Assert.AreEqual("System.String", mrr.Member.Parameters[1].Type.Resolve(context).FullName);
Assert.AreEqual("System.String", mrr.Member.Parameters[1].Type.FullName);
mrr = Resolve<CSharpInvocationResolveResult>(program.Replace("$", "$c.F(1)$"));
Assert.AreEqual("C.F", mrr.Member.FullName);

Просмотреть файл

@ -60,9 +60,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Assert.AreEqual("System.String", result.TargetType.FullName);
Assert.AreEqual(1, result.Parameters.Count);
Assert.AreEqual("b", result.Parameters[0].Name);
Assert.AreEqual("System.String", result.Parameters[0].Type.Resolve(context).ReflectionName);
Assert.AreEqual("System.String", result.Parameters[0].Type.ReflectionName);
Assert.AreSame(SharedTypes.UnknownType, result.Type);
Assert.AreSame(SpecialType.UnknownType, result.Type);
}
[Test]
@ -304,8 +304,8 @@ class DerivedClass : MiddleClass {
var m = (SpecializedMethod)rr.Member;
Assert.AreEqual("X", m.TypeArguments.Single().Name);
Assert.AreEqual("T", m.Parameters[0].Type.Resolve(context).Name);
Assert.AreEqual("X", m.Parameters[1].Type.Resolve(context).Name);
Assert.AreEqual("T", m.Parameters[0].Type.Name);
Assert.AreEqual("X", m.Parameters[1].Type.Name);
}
[Test]

Просмотреть файл

@ -373,7 +373,7 @@ class TestClass {
Assert.IsFalse(rr.IsError);
SpecializedMethod m = (SpecializedMethod)rr.Member;
Assert.AreEqual("System.Int32", m.TypeArguments[0].ReflectionName);
Assert.AreEqual("System.Converter`2[[``0],[System.Int32]]", m.Parameters[0].Type.Resolve(context).ReflectionName);
Assert.AreEqual("System.Converter`2[[``0],[System.Int32]]", m.Parameters[0].Type.ReflectionName);
var crr = (ConversionResolveResult)rr.Arguments[0];
Assert.IsTrue(crr.Conversion.IsAnonymousFunctionConversion);

Просмотреть файл

@ -51,7 +51,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
}
";
var lrr = Resolve<LocalResolveResult>(program);
Assert.AreSame(SharedTypes.UnknownType, lrr.Type);
Assert.AreSame(SpecialType.UnknownType, lrr.Type);
}
[Test]
@ -65,7 +65,7 @@ class TestClass {
$contact$.ToString();
} }";
var lrr = Resolve<LocalResolveResult>(program);
Assert.AreEqual(SharedTypes.UnknownType, lrr.Type);
Assert.AreEqual(SpecialType.UnknownType, lrr.Type);
}
}
}

Просмотреть файл

@ -20,6 +20,7 @@ using System;
using System.IO;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using NUnit.Framework;
@ -34,14 +35,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public override void SetUp()
{
base.SetUp();
lookup = new MemberLookup(context, null, project);
lookup = new MemberLookup(null, compilation.MainAssembly);
}
CSharpParsedFile Parse(string program)
{
CompilationUnit cu = new CSharpParser().Parse(new StringReader(program));
CSharpParsedFile parsedFile = new TypeSystemConvertVisitor(project, "test.cs").Convert(cu);
project.UpdateProjectContent(null, parsedFile);
CSharpParsedFile parsedFile = cu.ToTypeSystem("test.cs");
project = project.UpdateProjectContent(null, parsedFile);
compilation = project.CreateCompilation();
return parsedFile;
}
@ -58,7 +60,7 @@ class Middle : Base {
class Derived : Middle {
public override void Method() {}
}";
ITypeDefinition derived = Parse(program).TopLevelTypeDefinitions[2];
ITypeDefinition derived = Parse(program).TopLevelTypeDefinitions[2].Resolve(compilation.TypeResolveContext);
var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
Assert.AreEqual(2, rr.MethodsGroupedByDeclaringType.Count());
@ -84,7 +86,7 @@ class Derived : Base<int> {
public override void Method(int a) {}
public override void Method(string a) {}
}";
ITypeDefinition derived = Parse(program).TopLevelTypeDefinitions[1];
ITypeDefinition derived = Parse(program).TopLevelTypeDefinitions[1].Resolve(compilation.TypeResolveContext);
var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
Assert.AreEqual(2, rr.MethodsGroupedByDeclaringType.Count());
@ -92,13 +94,13 @@ class Derived : Base<int> {
Assert.AreEqual("Base`1[[System.Int32]]", baseGroup.DeclaringType.ReflectionName);
Assert.AreEqual(1, baseGroup.Count);
Assert.AreEqual("Derived.Method", baseGroup[0].FullName);
Assert.AreEqual("System.Int32", baseGroup[0].Parameters[0].Type.Resolve(context).ReflectionName);
Assert.AreEqual("System.Int32", baseGroup[0].Parameters[0].Type.ReflectionName);
var derivedGroup = rr.MethodsGroupedByDeclaringType.ElementAt(1);
Assert.AreEqual("Derived", derivedGroup.DeclaringType.ReflectionName);
Assert.AreEqual(1, derivedGroup.Count);
Assert.AreEqual("Derived.Method", derivedGroup[0].FullName);
Assert.AreEqual("System.String", derivedGroup[0].Parameters[0].Type.Resolve(context).ReflectionName);
Assert.AreEqual("System.String", derivedGroup[0].Parameters[0].Type.ReflectionName);
}
[Test]
@ -111,7 +113,7 @@ class Base {
class Derived : Base {
public override void Method<S>(S a) {}
}";
ITypeDefinition derived = Parse(program).TopLevelTypeDefinitions[1];
ITypeDefinition derived = Parse(program).TopLevelTypeDefinitions[1].Resolve(compilation.TypeResolveContext);
var rr = lookup.Lookup(new ResolveResult(derived), "Method", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
Assert.AreEqual(1, rr.MethodsGroupedByDeclaringType.Count());
@ -119,7 +121,7 @@ class Derived : Base {
Assert.AreEqual("Base", baseGroup.DeclaringType.ReflectionName);
Assert.AreEqual(1, baseGroup.Count);
Assert.AreEqual("Derived.Method", baseGroup[0].FullName);
Assert.AreEqual("``0", baseGroup[0].Parameters[0].Type.Resolve(context).ReflectionName);
Assert.AreEqual("``0", baseGroup[0].Parameters[0].Type.ReflectionName);
}
[Test]

Просмотреть файл

@ -20,6 +20,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
@ -30,6 +31,25 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public class NameLookupTests : ResolverTestBase
{
CSharpResolver resolver;
public override void SetUp()
{
base.SetUp();
resolver = new CSharpResolver(compilation);
resolver.CurrentUsingScope = new UsingScope();
}
void AddUsing(string namespaceName)
{
resolver.CurrentUsingScope.Usings.Add(MakeReference(namespaceName));
}
void AddUsingAlias(string alias, string namespaceName)
{
resolver.CurrentUsingScope.UsingAliases.Add(new KeyValuePair<string, TypeOrNamespaceReference>(alias, MakeReference(namespaceName)));
}
[Test]
public void SimpleNameLookupWithoutContext()
{
@ -43,7 +63,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
NamespaceResolveResult nrr = (NamespaceResolveResult)resolver.ResolveSimpleName("System", new IType[0]);
Assert.AreEqual("System", nrr.NamespaceName);
Assert.AreSame(SharedTypes.UnknownType, nrr.Type);
Assert.AreSame(SpecialType.UnknownType, nrr.Type);
}
[Test]
@ -97,7 +117,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
AddUsingAlias("x", "String");
TypeResolveResult trr = (TypeResolveResult)resolver.ResolveSimpleName("x", new IType[0]);
// Unknown type (as String isn't looked up in System)
Assert.AreSame(SharedTypes.UnknownType, trr.Type);
Assert.AreSame(SpecialType.UnknownType, trr.Type);
}
[Test]
@ -151,7 +171,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public void FindTypeParameters()
{
resolver.CurrentUsingScope = MakeUsingScope("System.Collections.Generic");
resolver.CurrentTypeDefinition = context.GetTypeDefinition(typeof(List<>));
resolver.CurrentTypeDefinition = compilation.FindType(typeof(List<>)).GetDefinition();
resolver.CurrentMember = resolver.CurrentTypeDefinition.Methods.Single(m => m.Name == "ConvertAll");
TypeResolveResult trr;
@ -205,7 +225,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
UnknownIdentifierResolveResult result = Resolve<UnknownIdentifierResolveResult>(program);
Assert.AreEqual("StringBuilder", result.Identifier);
Assert.AreSame(SharedTypes.UnknownType, result.Type);
Assert.AreSame(SpecialType.UnknownType, result.Type);
}
const string propertyNameAmbiguousWithTypeNameProgram = @"class A {
@ -806,7 +826,7 @@ class Test {
}";
MemberResolveResult rr = Resolve<MemberResolveResult>(program);
Assert.AreEqual("System.Nullable.Value", rr.Member.FullName);
Assert.AreEqual("System.Int32", rr.Member.ReturnType.Resolve(context).FullName);
Assert.AreEqual("System.Int32", rr.Member.ReturnType.FullName);
}
[Test]
@ -857,8 +877,8 @@ class B
var m = (SpecializedMethod)rr.Methods.Single();
Assert.AreSame(rr.TypeArguments.Single(), m.TypeArguments.Single());
Assert.AreEqual("T", m.Parameters[0].Type.Resolve(context).Name);
Assert.AreEqual("X", m.Parameters[1].Type.Resolve(context).Name);
Assert.AreEqual("T", m.Parameters[0].Type.Name);
Assert.AreEqual("X", m.Parameters[1].Type.Name);
}
[Test]

Просмотреть файл

@ -52,7 +52,7 @@ class A {
}
";
ResolveResult result = Resolve<ErrorResolveResult>(program);
Assert.AreSame(SharedTypes.UnknownType, result.Type);
Assert.AreSame(SpecialType.UnknownType, result.Type);
}
[Test]
@ -66,7 +66,7 @@ class A {
";
UnknownIdentifierResolveResult result = Resolve<UnknownIdentifierResolveResult>(program);
Assert.AreEqual("ThisClassDoesNotExist", result.Identifier);
Assert.AreSame(SharedTypes.UnknownType, result.Type);
Assert.AreSame(SpecialType.UnknownType, result.Type);
}
[Test]

Просмотреть файл

@ -31,8 +31,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public class OverloadResolutionTests
{
readonly ITypeResolveContext context = new CompositeTypeResolveContext(
new[] { CecilLoaderTests.Mscorlib, CecilLoaderTests.SystemCore });
/*
readonly ICompilation compilation = new SimpleCompilation(
CecilLoaderTests.SystemCore, new[] { CecilLoaderTests.Mscorlib });
readonly DefaultTypeDefinition dummyClass = new DefaultTypeDefinition(CecilLoaderTests.Mscorlib, string.Empty, "DummyClass");
ResolveResult[] MakeArgumentList(params Type[] argumentTypes)
@ -302,5 +303,6 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Assert.AreEqual(OverloadResolutionErrors.None, r.AddCandidate(m2));
Assert.AreEqual(OverloadResolutionErrors.AmbiguousMatch, r.BestCandidateErrors);
}
*/
}
}

Просмотреть файл

@ -55,7 +55,7 @@ class A { void M() {
Console.W$riteLine(1);
}}");
Assert.AreEqual("System.Console.WriteLine", rr.Member.FullName);
Assert.AreEqual("System.Int32", rr.Member.Parameters[0].Type.Resolve(context).FullName);
Assert.AreEqual("System.Int32", rr.Member.Parameters[0].Type.FullName);
}
[Test]

Просмотреть файл

@ -21,8 +21,8 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Parser;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
@ -35,23 +35,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// </summary>
public abstract class ResolverTestBase
{
protected readonly IProjectContent mscorlib = CecilLoaderTests.Mscorlib;
protected SimpleProjectContent project;
protected ITypeResolveContext context;
protected CSharpResolver resolver;
protected readonly IUnresolvedAssembly mscorlib = CecilLoaderTests.Mscorlib;
protected IProjectContent project;
protected ICompilation compilation;
[SetUp]
public virtual void SetUp()
{
project = new SimpleProjectContent();
context = new CompositeTypeResolveContext(new [] { project, mscorlib, CecilLoaderTests.SystemCore });
resolver = new CSharpResolver(context);
resolver.CurrentUsingScope = MakeUsingScope("");
project = new CSharpProjectContent().AddAssemblyReferences(new [] { mscorlib });
compilation = project.CreateCompilation();
}
protected UsingScope MakeUsingScope(string namespaceName)
{
UsingScope u = new UsingScope(project);
UsingScope u = new UsingScope();
if (!string.IsNullOrEmpty(namespaceName)) {
foreach (string element in namespaceName.Split('.')) {
u = new UsingScope(u, string.IsNullOrEmpty(u.NamespaceName) ? element : u.NamespaceName + "." + element);
@ -60,36 +57,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
return u;
}
/// <summary>
/// Adds a using to the current using scope.
/// </summary>
protected void AddUsing(string namespaceName)
{
resolver.CurrentUsingScope.Usings.Add(MakeReference(namespaceName));
}
/// <summary>
/// Adds a using alias to the current using scope.
/// </summary>
protected void AddUsingAlias(string alias, string target)
{
resolver.CurrentUsingScope.UsingAliases.Add(new KeyValuePair<string, ITypeOrNamespaceReference>(alias, MakeReference(target)));
}
protected ITypeOrNamespaceReference MakeReference(string namespaceName)
protected TypeOrNamespaceReference MakeReference(string namespaceName)
{
string[] nameParts = namespaceName.Split('.');
ITypeOrNamespaceReference r = new SimpleTypeOrNamespaceReference(nameParts[0], new ITypeReference[0], resolver.CurrentTypeDefinition, resolver.CurrentUsingScope, SimpleNameLookupMode.TypeInUsingDeclaration);
TypeOrNamespaceReference r = new SimpleTypeOrNamespaceReference(nameParts[0], new ITypeReference[0], SimpleNameLookupMode.TypeInUsingDeclaration);
for (int i = 1; i < nameParts.Length; i++) {
r = new MemberTypeOrNamespaceReference(r, nameParts[i], new ITypeReference[0], resolver.CurrentTypeDefinition, resolver.CurrentUsingScope);
r = new MemberTypeOrNamespaceReference(r, nameParts[i], new ITypeReference[0]);
}
return r;
}
protected IType ResolveType(Type type)
{
IType t = type.ToTypeReference().Resolve(context);
if (SharedTypes.UnknownType.Equals(t))
IType t = compilation.FindType(type);
if (t.Kind == TypeKind.Unknown)
throw new InvalidOperationException("Could not resolve type");
return t;
}
@ -97,7 +78,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
protected ConstantResolveResult MakeConstant(object value)
{
if (value == null)
return new ConstantResolveResult(SharedTypes.Null, null);
return new ConstantResolveResult(SpecialType.NullType, null);
IType type = ResolveType(value.GetType());
if (type.Kind == TypeKind.Enum)
value = Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()));
@ -128,19 +109,20 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
Assert.IsFalse(rr.IsError, rr.ToString() + " is an error");
Assert.IsFalse(rr.IsCompileTimeConstant, rr.ToString() + " is a compile-time constant");
Assert.AreEqual(expectedType.ToTypeReference().Resolve(context), rr.Type);
Assert.AreEqual(compilation.FindType(expectedType), rr.Type);
}
protected void AssertError(Type expectedType, ResolveResult rr)
{
Assert.IsTrue(rr.IsError, rr.ToString() + " is not an error, but an error was expected");
Assert.IsFalse(rr.IsCompileTimeConstant, rr.ToString() + " is a compile-time constant");
Assert.AreEqual(expectedType.ToTypeReference().Resolve(context), rr.Type);
Assert.AreEqual(compilation.FindType(expectedType), rr.Type);
}
protected void TestOperator(UnaryOperatorType op, ResolveResult input,
Conversion expectedConversion, Type expectedResultType)
{
CSharpResolver resolver = new CSharpResolver(compilation);
var rr = resolver.ResolveUnaryOperator(op, input);
AssertType(expectedResultType, rr);
Assert.AreEqual(typeof(OperatorResolveResult), rr.GetType());
@ -151,6 +133,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
protected void TestOperator(ResolveResult lhs, BinaryOperatorType op, ResolveResult rhs,
Conversion expectedLeftConversion, Conversion expectedRightConversion, Type expectedResultType)
{
CSharpResolver resolver = new CSharpResolver(compilation);
var rr = resolver.ResolveBinaryOperator(op, lhs, rhs);
AssertType(expectedResultType, rr);
Assert.AreEqual(typeof(OperatorResolveResult), rr.GetType());
@ -196,10 +179,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
SetUp();
CSharpParsedFile parsedFile = new CSharpParsedFile("test.cs", resolver.CurrentUsingScope);
TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(parsedFile);
cu.AcceptVisitor(convertVisitor, null);
project.UpdateProjectContent(null, convertVisitor.ParsedFile);
CSharpParsedFile parsedFile = cu.ToTypeSystem("code.cs");
project = project.UpdateProjectContent(null, parsedFile);
compilation = project.CreateCompilation();
FindNodeVisitor fnv = new FindNodeVisitor(dollars[0], dollars[1]);
cu.AcceptVisitor(fnv, null);
@ -209,12 +191,9 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
Debug.WriteLine("Starting new resolver for " + fnv.ResultNode);
var navigator = new NodeListResolveVisitorNavigator(new[] { fnv.ResultNode });
ResolveResult rr;
using (var context = this.context.Synchronize()) {
ResolveVisitor rv = new ResolveVisitor(new CSharpResolver(context), convertVisitor.ParsedFile, navigator);
rv.Scan(cu);
rr = rv.GetResolveResult(fnv.ResultNode);
}
ResolveVisitor rv = new ResolveVisitor(new CSharpResolver(compilation), parsedFile, navigator);
rv.Scan(cu);
ResolveResult rr = rv.GetResolveResult(fnv.ResultNode);
Assert.IsNotNull(rr, "ResolveResult is null - did something go wrong while navigating to the target node?");
Debug.WriteLine("ResolveResult is " + rr);
return rr;
@ -261,12 +240,11 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
SetUp();
CSharpParsedFile parsedFile = new CSharpParsedFile("test.cs", resolver.CurrentUsingScope);
TypeSystemConvertVisitor convertVisitor = new TypeSystemConvertVisitor(parsedFile, resolver.CurrentUsingScope, null);
cu.AcceptVisitor(convertVisitor, null);
project.UpdateProjectContent(null, convertVisitor.ParsedFile);
CSharpParsedFile parsedFile = cu.ToTypeSystem("test.cs");
project = project.UpdateProjectContent(null, parsedFile);
compilation = project.CreateCompilation();
ResolveResult rr = Resolver.ResolveAtLocation.Resolve(this.context, parsedFile, cu, dollars[0]);
ResolveResult rr = Resolver.ResolveAtLocation.Resolve(compilation, parsedFile, cu, dollars[0]);
return rr;
}

Просмотреть файл

@ -32,13 +32,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public class TypeInferenceTests
{
readonly ITypeResolveContext ctx = CecilLoaderTests.Mscorlib;
readonly ICompilation compilation = new SimpleCompilation(CecilLoaderTests.Mscorlib);
TypeInference ti;
[SetUp]
public void Setup()
{
ti = new TypeInference(ctx);
ti = new TypeInference(compilation);
}
#region Type Inference
@ -46,8 +46,8 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
IType[] r = new IType[types.Length];
for (int i = 0; i < types.Length; i++) {
r[i] = types[i].ToTypeReference().Resolve(CecilLoaderTests.Mscorlib);
Assert.AreNotSame(r[i], SharedTypes.UnknownType);
r[i] = compilation.FindType(types[i]);
Assert.AreNotSame(r[i], SpecialType.UnknownType);
}
Array.Sort(r, (a,b)=>a.ReflectionName.CompareTo(b.ReflectionName));
return r;
@ -56,15 +56,15 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[Test]
public void ArrayToEnumerable()
{
ITypeParameter tp = new DefaultTypeParameter(EntityType.Method, 0, "T");
IType stringType = KnownTypeReference.String.Resolve(ctx);
ITypeDefinition enumerableType = ctx.GetTypeDefinition(typeof(IEnumerable<>));
ITypeParameter tp = new DefaultResolvedTypeParameter(EntityType.Method, 0, "T");
IType stringType = compilation.FindType(KnownTypeCode.String);
ITypeDefinition enumerableType = compilation.FindType(KnownTypeCode.IEnumerableOfT).GetDefinition();
bool success;
Assert.AreEqual(
new [] { stringType },
ti.InferTypeArguments(new [] { tp },
new [] { new ResolveResult(new ArrayType(stringType)) },
new [] { new ResolveResult(new ArrayType(compilation, stringType)) },
new [] { new ParameterizedType(enumerableType, new [] { tp }) },
out success));
Assert.IsTrue(success);
@ -73,13 +73,13 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[Test]
public void EnumerableToArrayInContravariantType()
{
ITypeParameter tp = new DefaultTypeParameter(EntityType.Method, 0, "T");
IType stringType = KnownTypeReference.String.Resolve(ctx);
ITypeDefinition enumerableType = ctx.GetTypeDefinition(typeof(IEnumerable<>));
ITypeDefinition comparerType = ctx.GetTypeDefinition(typeof(IComparer<>));
ITypeParameter tp = new DefaultResolvedTypeParameter(EntityType.Method, 0, "T");
IType stringType = compilation.FindType(KnownTypeCode.String);
ITypeDefinition enumerableType = compilation.FindType(typeof(IEnumerable<>)).GetDefinition();
ITypeDefinition comparerType = compilation.FindType(typeof(IComparer<>)).GetDefinition();
var comparerOfIEnumerableOfString = new ParameterizedType(comparerType, new [] { new ParameterizedType(enumerableType, new [] { stringType} ) });
var comparerOfTpArray = new ParameterizedType(comparerType, new [] { new ArrayType(tp) });
var comparerOfIEnumerableOfString = new ParameterizedType(comparerType, new [] { new ParameterizedType(enumerableType, new [] { stringType } ) });
var comparerOfTpArray = new ParameterizedType(comparerType, new [] { new ArrayType(compilation, tp) });
bool success;
Assert.AreEqual(
@ -98,16 +98,16 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
{
// static void M<A, B>(Func<A, B> f) {}
// M(int.Parse); // type inference fails
DefaultTypeParameter A = new DefaultTypeParameter(EntityType.Method, 0, "A");
DefaultTypeParameter B = new DefaultTypeParameter(EntityType.Method, 1, "B");
var A = new DefaultResolvedTypeParameter(EntityType.Method, 0, "A");
var B = new DefaultResolvedTypeParameter(EntityType.Method, 1, "B");
ITypeDefinition declType = ctx.GetTypeDefinition(typeof(int));
var methods = new MethodListWithDeclaringType(declType, declType.Methods.Where(m => m.Name == "Parse"));
IType declType = compilation.FindType(typeof(int));
var methods = new MethodListWithDeclaringType(declType, declType.GetMethods(m => m.Name == "Parse"));
var argument = new MethodGroupResolveResult(new TypeResolveResult(declType), "Parse", new[] { methods }, new IType[0]);
bool success;
ti.InferTypeArguments(new [] { A, B }, new [] { argument },
new [] { new ParameterizedType(ctx.GetTypeDefinition(typeof(Func<,>)), new[] { A, B }) },
new [] { new ParameterizedType(compilation.FindType(typeof(Func<,>)).GetDefinition(), new[] { A, B }) },
out success);
Assert.IsFalse(success);
}
@ -118,17 +118,17 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
// static void M<T>(Func<T> f) {}
// M(Console.ReadKey); // type inference produces ConsoleKeyInfo
DefaultTypeParameter T = new DefaultTypeParameter(EntityType.Method, 0, "T");
var T = new DefaultResolvedTypeParameter(EntityType.Method, 0, "T");
ITypeDefinition declType = ctx.GetTypeDefinition(typeof(Console));
var methods = new MethodListWithDeclaringType(declType, declType.Methods.Where(m => m.Name == "ReadKey"));
IType declType = compilation.FindType(typeof(Console));
var methods = new MethodListWithDeclaringType(declType, declType.GetMethods(m => m.Name == "ReadKey"));
var argument = new MethodGroupResolveResult(new TypeResolveResult(declType), "ReadKey", new[] { methods }, new IType[0]);
bool success;
Assert.AreEqual(
new [] { ctx.GetTypeDefinition(typeof(ConsoleKeyInfo)) },
new [] { compilation.FindType(typeof(ConsoleKeyInfo)) },
ti.InferTypeArguments(new [] { T }, new [] { argument },
new [] { new ParameterizedType(ctx.GetTypeDefinition(typeof(Func<>)), new[] { T }) },
new [] { new ParameterizedType(compilation.FindType(typeof(Func<>)).GetDefinition(), new[] { T }) },
out success));
Assert.IsTrue(success);
}
@ -149,7 +149,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
this.parameters = new IParameter[expectedParameterTypes.Length];
for (int i = 0; i < parameters.Length; i++) {
// UnknownType because this lambda is implicitly typed
parameters[i] = new DefaultParameter(SharedTypes.UnknownType, "X" + i);
parameters[i] = new DefaultParameter(SpecialType.UnknownType, "X" + i);
}
}
@ -200,28 +200,28 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
public void TestLambdaInference()
{
ITypeParameter[] typeParameters = {
new DefaultTypeParameter(EntityType.Method, 0, "X"),
new DefaultTypeParameter(EntityType.Method, 1, "Y"),
new DefaultTypeParameter(EntityType.Method, 2, "Z")
new DefaultResolvedTypeParameter(EntityType.Method, 0, "X"),
new DefaultResolvedTypeParameter(EntityType.Method, 1, "Y"),
new DefaultResolvedTypeParameter(EntityType.Method, 2, "Z")
};
IType[] parameterTypes = {
typeParameters[0],
new ParameterizedType(ctx.GetTypeDefinition(typeof(Func<,>)), new[] { typeParameters[0], typeParameters[1] }),
new ParameterizedType(ctx.GetTypeDefinition(typeof(Func<,>)), new[] { typeParameters[1], typeParameters[2] })
new ParameterizedType(compilation.FindType(typeof(Func<,>)).GetDefinition(), new[] { typeParameters[0], typeParameters[1] }),
new ParameterizedType(compilation.FindType(typeof(Func<,>)).GetDefinition(), new[] { typeParameters[1], typeParameters[2] })
};
// Signature: M<X,Y,Z>(X x, Func<X,Y> y, Func<Y,Z> z) {}
// Invocation: M(default(string), s => default(int), t => default(float));
ResolveResult[] arguments = {
new ResolveResult(KnownTypeReference.String.Resolve(ctx)),
new MockImplicitLambda(new[] { KnownTypeReference.String.Resolve(ctx) }, KnownTypeReference.Int32.Resolve(ctx)),
new MockImplicitLambda(new[] { KnownTypeReference.Int32.Resolve(ctx) }, KnownTypeReference.Single.Resolve(ctx))
new ResolveResult(compilation.FindType(KnownTypeCode.String)),
new MockImplicitLambda(new[] { compilation.FindType(KnownTypeCode.String) }, compilation.FindType(KnownTypeCode.Int32)),
new MockImplicitLambda(new[] { compilation.FindType(KnownTypeCode.Int32) }, compilation.FindType(KnownTypeCode.Single))
};
bool success;
Assert.AreEqual(
new [] {
KnownTypeReference.String.Resolve(ctx),
KnownTypeReference.Int32.Resolve(ctx),
KnownTypeReference.Single.Resolve(ctx)
compilation.FindType(KnownTypeCode.String),
compilation.FindType(KnownTypeCode.Int32),
compilation.FindType(KnownTypeCode.Single)
},
ti.InferTypeArguments(typeParameters, arguments, parameterTypes, out success));
Assert.IsTrue(success);
@ -230,26 +230,26 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[Test]
public void ConvertAllLambdaInference()
{
ITypeParameter[] classTypeParameters = { new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T") };
ITypeParameter[] methodTypeParameters = { new DefaultTypeParameter(EntityType.Method, 0, "R") };
ITypeParameter[] classTypeParameters = { new DefaultResolvedTypeParameter(EntityType.TypeDefinition, 0, "T") };
ITypeParameter[] methodTypeParameters = { new DefaultResolvedTypeParameter(EntityType.Method, 0, "R") };
IType[] parameterTypes = {
new ParameterizedType(ctx.GetTypeDefinition(typeof(Converter<,>)),
new ParameterizedType(compilation.FindType(typeof(Converter<,>)).GetDefinition(),
new[] { classTypeParameters[0], methodTypeParameters[0] })
};
// Signature: List<T>.ConvertAll<R>(Converter<T, R> converter);
// Invocation: listOfString.ConvertAll(s => default(int));
ResolveResult[] arguments = {
new MockImplicitLambda(new[] { KnownTypeReference.String.Resolve(ctx) }, KnownTypeReference.Int32.Resolve(ctx))
new MockImplicitLambda(new[] { compilation.FindType(KnownTypeCode.String) }, compilation.FindType(KnownTypeCode.Int32))
};
IType[] classTypeArguments = {
KnownTypeReference.String.Resolve(ctx)
compilation.FindType(KnownTypeCode.String)
};
bool success;
Assert.AreEqual(
new [] { KnownTypeReference.Int32.Resolve(ctx) },
new [] { compilation.FindType(KnownTypeCode.Int32) },
ti.InferTypeArguments(methodTypeParameters, arguments, parameterTypes, out success, classTypeArguments));
}
#endregion

Просмотреть файл

@ -28,6 +28,14 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
[TestFixture]
public unsafe class UnaryOperatorTests : ResolverTestBase
{
CSharpResolver resolver;
public override void SetUp()
{
base.SetUp();
resolver = new CSharpResolver(compilation);
}
[Test]
public void TestAddressOf()
{

Просмотреть файл

@ -30,6 +30,7 @@ namespace ICSharpCode.NRefactory.Documentation
[TestFixture]
public class IDStringTests
{
/*
class IDStringTestProjectContent : SimpleProjectContent, IDocumentationProvider
{
public string GetDocumentation(IEntity entity)
@ -330,6 +331,6 @@ namespace Acme
IDStringProvider.GetIDString(list.Methods.Single(m => m.Name == "AddRange")));
Assert.AreEqual("M:System.Collections.Generic.List`1.ConvertAll``1(System.Converter{`0,``0})",
IDStringProvider.GetIDString(list.Methods.Single(m => m.Name == "ConvertAll")));
}
}*/
}
}

Просмотреть файл

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{63D3B27A-D966-4902-90B3-30290E1692F1}</ProjectGuid>
@ -187,14 +187,6 @@
<Compile Include="Utils\TreeTraversalTests.cs" />
<Compile Include="FormattingTests\TextEditorTestAdapter.cs" />
<Compile Include="FormattingTests\TestBlankLineFormatting.cs" />
<Compile Include="CSharp\CodeCompletion\CodeCompletionAccessibleTests.cs" />
<Compile Include="CSharp\CodeCompletion\CodeCompletionBugTests.cs" />
<Compile Include="CSharp\CodeCompletion\CodeCompletionCSharp3Tests.cs" />
<Compile Include="CSharp\CodeCompletion\CodeCompletionCSharpTests.cs" />
<Compile Include="CSharp\CodeCompletion\CodeComplteionOperatorTests.cs" />
<Compile Include="CSharp\CodeCompletion\CompletionDataList.cs" />
<Compile Include="CSharp\CodeCompletion\ParameterCompletionTests.cs" />
<Compile Include="CSharp\CodeCompletion\TestBase.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ICSharpCode.NRefactory.CSharp\ICSharpCode.NRefactory.CSharp.csproj">
@ -212,7 +204,6 @@
<Folder Include="CSharp\Parser\" />
<Folder Include="CSharp\Parser\" />
<Folder Include="CSharp\Parser\" />
<Folder Include="CSharp\CodeCompletion\" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project>

Просмотреть файл

@ -28,42 +28,41 @@ namespace ICSharpCode.NRefactory.TypeSystem
[TestFixture]
public class CecilLoaderTests : TypeSystemTests
{
static readonly Lazy<IProjectContent> mscorlib = new Lazy<IProjectContent>(
static readonly Lazy<IUnresolvedAssembly> mscorlib = new Lazy<IUnresolvedAssembly>(
delegate {
return new CecilLoader().LoadAssemblyFile(typeof(object).Assembly.Location);
});
static readonly Lazy<IProjectContent> systemCore = new Lazy<IProjectContent>(
static readonly Lazy<IUnresolvedAssembly> systemCore = new Lazy<IUnresolvedAssembly>(
delegate {
return new CecilLoader().LoadAssemblyFile(typeof(System.Linq.Enumerable).Assembly.Location);
});
public static IProjectContent Mscorlib { get { return mscorlib.Value; } }
public static IProjectContent SystemCore { get { return systemCore.Value; } }
ITypeResolveContext ctx = Mscorlib;
public static IUnresolvedAssembly Mscorlib { get { return mscorlib.Value; } }
public static IUnresolvedAssembly SystemCore { get { return systemCore.Value; } }
[TestFixtureSetUp]
public void FixtureSetUp()
{
// use "IncludeInternalMembers" so that Cecil results match C# parser results
CecilLoader loader = new CecilLoader() { IncludeInternalMembers = true };
testCasePC = loader.LoadAssemblyFile(typeof(TestCase.SimplePublicClass).Assembly.Location);
IUnresolvedAssembly asm = loader.LoadAssemblyFile(typeof(TestCase.SimplePublicClass).Assembly.Location);
compilation = new SimpleCompilation(asm, CecilLoaderTests.Mscorlib);
}
[Test]
public void InheritanceTest()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(SystemException));
ITypeDefinition c2 = Mscorlib.GetTypeDefinition(typeof(Exception));
ITypeDefinition c = compilation.FindType(typeof(SystemException)).GetDefinition();
ITypeDefinition c2 = compilation.FindType(typeof(Exception)).GetDefinition();
Assert.IsNotNull(c, "c is null");
Assert.IsNotNull(c2, "c2 is null");
//Assert.AreEqual(3, c.BaseTypes.Count); // Inherited interfaces are not reported by Cecil
// which matches the behaviour of our C#/VB parsers
Assert.AreEqual("System.Exception", c.BaseTypes[0].Resolve(ctx).FullName);
Assert.AreSame(c2, c.BaseTypes[0]);
Assert.AreEqual("System.Exception", c.DirectBaseTypes.First().FullName);
Assert.AreSame(c2, c.DirectBaseTypes.First());
string[] superTypes = c.GetAllBaseTypes(ctx).Select(t => t.ToString()).ToArray();
string[] superTypes = c.GetAllBaseTypes().Select(t => t.ToString()).ToArray();
Assert.AreEqual(new string[] {
"System.Object",
"System.Runtime.Serialization.ISerializable", "System.Runtime.InteropServices._Exception",
@ -74,9 +73,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void GenericPropertyTest()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(Comparer<>));
IProperty def = c.Properties.Single(p => p.Name == "Default");
ParameterizedType pt = (ParameterizedType)def.ReturnType.Resolve(ctx);
ITypeDefinition c = compilation.FindType(typeof(Comparer<>)).GetDefinition();
IProperty def = c.Members.OfType<IProperty>().Single(p => p.Name == "Default");
ParameterizedType pt = (ParameterizedType)def.ReturnType;
Assert.AreEqual("System.Collections.Generic.Comparer", pt.FullName);
Assert.AreEqual(c.TypeParameters[0], pt.TypeArguments[0]);
}
@ -84,36 +83,36 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void PointerTypeTest()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(IntPtr));
ITypeDefinition c = compilation.FindType(typeof(IntPtr)).GetDefinition();
IMethod toPointer = c.Methods.Single(p => p.Name == "ToPointer");
Assert.AreEqual("System.Void*", toPointer.ReturnType.Resolve(ctx).ReflectionName);
Assert.IsTrue (toPointer.ReturnType.Resolve(ctx) is PointerType);
Assert.AreEqual("System.Void", ((PointerType)toPointer.ReturnType.Resolve(ctx)).ElementType.FullName);
Assert.AreEqual("System.Void*", toPointer.ReturnType.ReflectionName);
Assert.IsTrue (toPointer.ReturnType is PointerType);
Assert.AreEqual("System.Void", ((PointerType)toPointer.ReturnType).ElementType.FullName);
}
[Test]
public void DateTimeDefaultConstructor()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(DateTime));
ITypeDefinition c = compilation.FindType(typeof(DateTime)).GetDefinition();
Assert.IsFalse(c.Methods.Any(m => m.IsConstructor && m.Parameters.Count == 0)); // struct ctor isn't declared
// but it is implicit:
Assert.IsTrue(c.GetConstructors(ctx).Any(m => m.Parameters.Count == 0));
Assert.IsTrue(c.GetConstructors().Any(m => m.Parameters.Count == 0));
}
[Test]
public void NoEncodingInfoDefaultConstructor()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(EncodingInfo));
ITypeDefinition c = compilation.FindType(typeof(EncodingInfo)).GetDefinition();
// EncodingInfo only has an internal constructor
Assert.IsFalse(c.Methods.Any(m => m.IsConstructor));
// and no implicit ctor should be added:
Assert.AreEqual(0, c.GetConstructors(ctx).Count());
Assert.AreEqual(0, c.GetConstructors().Count());
}
[Test]
public void StaticModifierTest()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(Environment));
ITypeDefinition c = compilation.FindType(typeof(Environment)).GetDefinition();
Assert.IsNotNull(c, "System.Environment not found");
Assert.IsTrue(c.IsAbstract, "class should be abstract");
Assert.IsTrue(c.IsSealed, "class should be sealed");
@ -123,16 +122,16 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void InnerClassReferenceTest()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(Environment));
ITypeDefinition c = compilation.FindType(typeof(Environment)).GetDefinition();
Assert.IsNotNull(c, "System.Environment not found");
ITypeReference rt = c.Methods.First(m => m.Name == "GetFolderPath").Parameters[0].Type;
Assert.AreSame(c.NestedTypes.Single(ic => ic.Name == "SpecialFolder"), rt.Resolve(ctx));
IType rt = c.Members.OfType<IMethod>().First(m => m.Name == "GetFolderPath").Parameters[0].Type;
Assert.AreSame(c.NestedTypes.Single(ic => ic.Name == "SpecialFolder"), rt);
}
[Test]
public void NestedTypesTest()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(Environment.SpecialFolder));
ITypeDefinition c = compilation.FindType(typeof(Environment.SpecialFolder)).GetDefinition();
Assert.IsNotNull(c, "c is null");
Assert.AreEqual("System.Environment.SpecialFolder", c.FullName);
Assert.AreEqual("System.Environment+SpecialFolder", c.ReflectionName);
@ -141,12 +140,12 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void VoidTest()
{
ITypeDefinition c = Mscorlib.GetTypeDefinition(typeof(void));
ITypeDefinition c = compilation.FindType(typeof(void)).GetDefinition();
Assert.IsNotNull(c, "System.Void not found");
Assert.AreEqual(0, c.GetMethods(ctx).Count());
Assert.AreEqual(0, c.GetProperties(ctx).Count());
Assert.AreEqual(0, c.GetEvents(ctx).Count());
Assert.AreEqual(0, c.GetFields(ctx).Count());
Assert.AreEqual(0, c.GetMethods().Count());
Assert.AreEqual(0, c.GetProperties().Count());
Assert.AreEqual(0, c.GetEvents().Count());
Assert.AreEqual(0, c.GetFields().Count());
Assert.AreEqual(
new string[] {
"[System.SerializableAttribute]",
@ -159,13 +158,13 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void NestedClassInGenericClassTest()
{
ITypeDefinition dictionary = Mscorlib.GetTypeDefinition(typeof(Dictionary<,>));
ITypeDefinition dictionary = compilation.FindType(typeof(Dictionary<,>)).GetDefinition();
Assert.IsNotNull(dictionary);
ITypeDefinition valueCollection = Mscorlib.GetTypeDefinition(typeof(Dictionary<,>.ValueCollection));
ITypeDefinition valueCollection = compilation.FindType(typeof(Dictionary<,>.ValueCollection)).GetDefinition();
Assert.IsNotNull(valueCollection);
var dictionaryRT = new ParameterizedType(dictionary, new[] { Mscorlib.GetTypeDefinition(typeof(string)), Mscorlib.GetTypeDefinition(typeof(int)) });
IProperty valueProperty = dictionaryRT.GetProperties(ctx).Single(p => p.Name == "Values");
IType parameterizedValueCollection = valueProperty.ReturnType.Resolve(ctx);
var dictionaryRT = new ParameterizedType(dictionary, new[] { compilation.FindType(typeof(string)).GetDefinition(), compilation.FindType(typeof(int)).GetDefinition() });
IProperty valueProperty = dictionaryRT.GetProperties().Single(p => p.Name == "Values");
IType parameterizedValueCollection = valueProperty.ReturnType;
Assert.AreEqual("System.Collections.Generic.Dictionary`2+ValueCollection[[System.String],[System.Int32]]", parameterizedValueCollection.ReflectionName);
Assert.AreSame(valueCollection, parameterizedValueCollection.GetDefinition());
}
@ -173,7 +172,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void ValueCollectionCountModifiers()
{
ITypeDefinition valueCollection = Mscorlib.GetTypeDefinition(typeof(Dictionary<,>.ValueCollection));
ITypeDefinition valueCollection = compilation.FindType(typeof(Dictionary<,>.ValueCollection)).GetDefinition();
Assert.AreEqual(Accessibility.Public, valueCollection.Accessibility);
Assert.IsTrue(valueCollection.IsSealed);
Assert.IsFalse(valueCollection.IsAbstract);
@ -190,7 +189,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void MathAcosModifiers()
{
ITypeDefinition math = Mscorlib.GetTypeDefinition(typeof(Math));
ITypeDefinition math = compilation.FindType(typeof(Math)).GetDefinition();
Assert.AreEqual(Accessibility.Public, math.Accessibility);
Assert.IsTrue(math.IsSealed);
Assert.IsTrue(math.IsAbstract);
@ -208,7 +207,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void EncodingModifiers()
{
ITypeDefinition encoding = Mscorlib.GetTypeDefinition(typeof(Encoding));
ITypeDefinition encoding = compilation.FindType(typeof(Encoding)).GetDefinition();
Assert.AreEqual(Accessibility.Public, encoding.Accessibility);
Assert.IsFalse(encoding.IsSealed);
Assert.IsTrue(encoding.IsAbstract);
@ -241,7 +240,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void UnicodeEncodingModifiers()
{
ITypeDefinition encoding = Mscorlib.GetTypeDefinition(typeof(UnicodeEncoding));
ITypeDefinition encoding = compilation.FindType(typeof(UnicodeEncoding)).GetDefinition();
Assert.AreEqual(Accessibility.Public, encoding.Accessibility);
Assert.IsFalse(encoding.IsSealed);
Assert.IsFalse(encoding.IsAbstract);
@ -258,7 +257,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void UTF32EncodingModifiers()
{
ITypeDefinition encoding = Mscorlib.GetTypeDefinition(typeof(UTF32Encoding));
ITypeDefinition encoding = compilation.FindType(typeof(UTF32Encoding)).GetDefinition();
Assert.AreEqual(Accessibility.Public, encoding.Accessibility);
Assert.IsTrue(encoding.IsSealed);
Assert.IsFalse(encoding.IsAbstract);

Просмотреть файл

@ -31,17 +31,16 @@ namespace ICSharpCode.NRefactory.TypeSystem
[TestFixture]
public class GetAllBaseTypesTest
{
IProjectContent mscorlib = CecilLoaderTests.Mscorlib;
ITypeResolveContext context = CecilLoaderTests.Mscorlib;
ICompilation compilation = new SimpleCompilation(CecilLoaderTests.Mscorlib);
IType[] GetAllBaseTypes(Type type)
{
return type.ToTypeReference().Resolve(context).GetAllBaseTypes(context).OrderBy(t => t.ReflectionName).ToArray();
return compilation.FindType(type).GetAllBaseTypes().OrderBy(t => t.ReflectionName).ToArray();
}
IType[] GetTypes(params Type[] types)
{
return types.Select(t => t.ToTypeReference().Resolve(context)).OrderBy(t => t.ReflectionName).ToArray();;
return types.Select(t => compilation.FindType(t)).OrderBy(t => t.ReflectionName).ToArray();;
}
[Test]
@ -81,48 +80,53 @@ namespace ICSharpCode.NRefactory.TypeSystem
public void ClassDerivingFromItself()
{
// class C : C {}
DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C");
var c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
c.BaseTypes.Add(c);
Assert.AreEqual(new [] { c }, c.GetAllBaseTypes(context).ToArray());
ITypeDefinition resolvedC = c.Resolve(compilation.TypeResolveContext);
Assert.AreEqual(new [] { resolvedC }, resolvedC.GetAllBaseTypes().ToArray());
}
[Test]
public void TwoClassesDerivingFromEachOther()
{
// class C1 : C2 {} class C2 : C1 {}
DefaultTypeDefinition c1 = new DefaultTypeDefinition(mscorlib, string.Empty, "C1");
DefaultTypeDefinition c2 = new DefaultTypeDefinition(mscorlib, string.Empty, "C2");
var c1 = new DefaultUnresolvedTypeDefinition(string.Empty, "C1");
var c2 = new DefaultUnresolvedTypeDefinition(string.Empty, "C2");
c1.BaseTypes.Add(c2);
c2.BaseTypes.Add(c1);
Assert.AreEqual(new [] { c2, c1 }, c1.GetAllBaseTypes(context).ToArray());
ITypeDefinition resolvedC1 = c1.Resolve(compilation.TypeResolveContext);
ITypeDefinition resolvedC2 = c2.Resolve(compilation.TypeResolveContext);
Assert.AreEqual(new [] { resolvedC2, resolvedC1 }, resolvedC1.GetAllBaseTypes().ToArray());
}
[Test]
public void ClassDerivingFromParameterizedVersionOfItself()
{
// class C<X> : C<C<X>> {}
DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C");
c.TypeParameters.Add(new DefaultTypeParameter(EntityType.TypeDefinition, 0, "X"));
c.BaseTypes.Add(new ParameterizedType(c, new [] { new ParameterizedType(c, new [] { c.TypeParameters[0] }) }));
Assert.AreEqual(new [] { c }, c.GetAllBaseTypes(context).ToArray());
var c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
c.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "X"));
c.BaseTypes.Add(new ParameterizedTypeReference(c, new [] { new ParameterizedTypeReference(c, new [] { new TypeParameterReference(EntityType.TypeDefinition, 0) }) }));
ITypeDefinition resolvedC = c.Resolve(compilation.TypeResolveContext);
Assert.AreEqual(new [] { resolvedC }, resolvedC.GetAllBaseTypes().ToArray());
}
[Test]
public void ClassDerivingFromTwoInstanciationsOfIEnumerable()
{
// class C : IEnumerable<int>, IEnumerable<uint> {}
DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C");
var c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
c.BaseTypes.Add(typeof(IEnumerable<int>).ToTypeReference());
c.BaseTypes.Add(typeof(IEnumerable<uint>).ToTypeReference());
ITypeDefinition resolvedC = c.Resolve(compilation.TypeResolveContext);
IType[] expected = {
c,
c.BaseTypes[0].Resolve(context),
c.BaseTypes[1].Resolve(context),
mscorlib.GetTypeDefinition(typeof(IEnumerable)),
mscorlib.GetTypeDefinition(typeof(object))
resolvedC,
compilation.FindType(typeof(IEnumerable<int>)),
compilation.FindType(typeof(IEnumerable<uint>)),
compilation.FindType(typeof(IEnumerable)),
compilation.FindType(typeof(object))
};
Assert.AreEqual(expected,
c.GetAllBaseTypes(context).OrderBy(t => t.ReflectionName).ToArray());
resolvedC.GetAllBaseTypes().OrderBy(t => t.ReflectionName).ToArray());
}
[Test]
@ -130,17 +134,18 @@ namespace ICSharpCode.NRefactory.TypeSystem
{
// struct S : IEquatable<S> {}
// don't use a Cecil-loaded struct for this test; we're testing the implicit addition of System.ValueType
DefaultTypeDefinition s = new DefaultTypeDefinition(mscorlib, string.Empty, "S");
var s = new DefaultUnresolvedTypeDefinition(string.Empty, "S");
s.Kind = TypeKind.Struct;
s.BaseTypes.Add(new ParameterizedType(mscorlib.GetTypeDefinition(typeof(IEquatable<>)), new[] { s }));
s.BaseTypes.Add(new ParameterizedTypeReference(typeof(IEquatable<>).ToTypeReference(), new[] { s }));
ITypeDefinition resolvedS = s.Resolve(compilation.TypeResolveContext);
IType[] expected = {
s,
s.BaseTypes[0].Resolve(context),
mscorlib.GetTypeDefinition(typeof(object)),
mscorlib.GetTypeDefinition(typeof(ValueType))
resolvedS,
s.BaseTypes[0].Resolve(compilation.TypeResolveContext),
compilation.FindType(typeof(object)),
compilation.FindType(typeof(ValueType))
};
Assert.AreEqual(expected,
s.GetAllBaseTypes(context).OrderBy(t => t.ReflectionName).ToArray());
resolvedS.GetAllBaseTypes().OrderBy(t => t.ReflectionName).ToArray());
}
[Test]
@ -179,7 +184,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
GetTypes(typeof(List<>), typeof(object),
typeof(IList), typeof(ICollection), typeof(IEnumerable),
typeof(IEnumerable<>), typeof(ICollection<>), typeof(IList<>)),
typeof(List<string>).ToTypeReference().Resolve(context).GetAllBaseTypeDefinitions(context).OrderBy(t => t.ReflectionName).ToArray());
compilation.FindType(typeof(List<string>)).GetAllBaseTypeDefinitions().OrderBy(t => t.ReflectionName).ToArray());
}
[Test]
@ -190,7 +195,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
typeof(ICloneable), typeof(IStructuralComparable), typeof(IStructuralEquatable),
typeof(IList), typeof(ICollection), typeof(IEnumerable),
typeof(IEnumerable<>), typeof(ICollection<>), typeof(IList<>)),
typeof(string[]).ToTypeReference().Resolve(context).GetAllBaseTypeDefinitions(context).OrderBy(t => t.ReflectionName).ToArray());
compilation.FindType(typeof(string[])).GetAllBaseTypeDefinitions().OrderBy(t => t.ReflectionName).ToArray());
}
}
}

Просмотреть файл

@ -27,72 +27,73 @@ namespace ICSharpCode.NRefactory.TypeSystem
[TestFixture]
public class GetMembersTests
{
IProjectContent mscorlib = CecilLoaderTests.Mscorlib;
ICompilation compilation = new SimpleCompilation(CecilLoaderTests.Mscorlib);
[Test]
public void EmptyClassHasToString()
{
DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C");
Assert.AreEqual("System.Object.ToString", c.GetMethods(mscorlib, m => m.Name == "ToString").Single().FullName);
DefaultUnresolvedTypeDefinition c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
Assert.AreEqual("System.Object.ToString", c.Resolve(compilation.TypeResolveContext).GetMethods(m => m.Name == "ToString").Single().FullName);
}
[Test]
public void MultipleInheritanceTest()
{
DefaultTypeDefinition b1 = new DefaultTypeDefinition(mscorlib, string.Empty, "B1");
DefaultUnresolvedTypeDefinition b1 = new DefaultUnresolvedTypeDefinition(string.Empty, "B1");
b1.Kind = TypeKind.Interface;
b1.Properties.Add(new DefaultProperty(b1, "P1"));
b1.Members.Add(new DefaultUnresolvedProperty(b1, "P1"));
DefaultTypeDefinition b2 = new DefaultTypeDefinition(mscorlib, string.Empty, "B2");
DefaultUnresolvedTypeDefinition b2 = new DefaultUnresolvedTypeDefinition(string.Empty, "B2");
b2.Kind = TypeKind.Interface;
b2.Properties.Add(new DefaultProperty(b1, "P2"));
b2.Members.Add(new DefaultUnresolvedProperty(b2, "P2"));
DefaultTypeDefinition c = new DefaultTypeDefinition(mscorlib, string.Empty, "C");
DefaultUnresolvedTypeDefinition c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
c.Kind = TypeKind.Interface;
c.BaseTypes.Add(b1);
c.BaseTypes.Add(b2);
Assert.AreEqual(new[] { "P1", "P2" }, c.GetProperties(mscorlib).Select(p => p.Name).ToArray());
ITypeDefinition resolvedC = c.Resolve(compilation.TypeResolveContext);
Assert.AreEqual(new[] { "P1", "P2" }, resolvedC.GetProperties().Select(p => p.Name).ToArray());
// Test that there's only one copy of ToString():
Assert.AreEqual(1, c.GetMethods(mscorlib, m => m.Name == "ToString").Count());
Assert.AreEqual(1, resolvedC.GetMethods(m => m.Name == "ToString").Count());
}
[Test]
public void ArrayType()
{
IType arrayType = typeof(string[]).ToTypeReference().Resolve(mscorlib);
IType arrayType = compilation.FindType(typeof(string[]));
// Array inherits ToString() from System.Object
Assert.AreEqual("System.Object.ToString", arrayType.GetMethods(mscorlib, m => m.Name == "ToString").Single().FullName);
Assert.AreEqual("System.Array.GetLowerBound", arrayType.GetMethods(mscorlib, m => m.Name == "GetLowerBound").Single().FullName);
Assert.AreEqual("System.Array.Length", arrayType.GetProperties(mscorlib, p => p.Name == "Length").Single().FullName);
Assert.AreEqual("System.Object.ToString", arrayType.GetMethods(m => m.Name == "ToString").Single().FullName);
Assert.AreEqual("System.Array.GetLowerBound", arrayType.GetMethods(m => m.Name == "GetLowerBound").Single().FullName);
Assert.AreEqual("System.Array.Length", arrayType.GetProperties(p => p.Name == "Length").Single().FullName);
// test indexer
IProperty indexer = arrayType.GetProperties(mscorlib, p => p.IsIndexer).Single();
IProperty indexer = arrayType.GetProperties(p => p.IsIndexer).Single();
Assert.AreEqual("System.Array.Items", indexer.FullName);
Assert.AreEqual("System.String", indexer.ReturnType.Resolve(mscorlib).ReflectionName);
Assert.AreEqual("System.String", indexer.ReturnType.ReflectionName);
Assert.AreEqual(1, indexer.Parameters.Count);
Assert.AreEqual("System.Int32", indexer.Parameters[0].Type.Resolve(mscorlib).ReflectionName);
Assert.AreEqual("System.Int32", indexer.Parameters[0].Type.ReflectionName);
}
[Test]
public void MultidimensionalArrayType()
{
IType arrayType = typeof(string[,][]).ToTypeReference().Resolve(mscorlib);
IType arrayType = compilation.FindType(typeof(string[,][]));
// test indexer
IProperty indexer = arrayType.GetProperties(mscorlib, p => p.IsIndexer).Single();
IProperty indexer = arrayType.GetProperties(p => p.IsIndexer).Single();
Assert.AreEqual("System.Array.Items", indexer.FullName);
Assert.AreEqual("System.String[]", indexer.ReturnType.Resolve(mscorlib).ReflectionName);
Assert.AreEqual("System.String[]", indexer.ReturnType.ReflectionName);
Assert.AreEqual(2, indexer.Parameters.Count);
Assert.AreEqual("System.Int32", indexer.Parameters[0].Type.Resolve(mscorlib).ReflectionName);
Assert.AreEqual("System.Int32", indexer.Parameters[1].Type.Resolve(mscorlib).ReflectionName);
Assert.AreEqual("System.Int32", indexer.Parameters[0].Type.ReflectionName);
Assert.AreEqual("System.Int32", indexer.Parameters[1].Type.ReflectionName);
}
[Test]
public void GetNestedTypesOfUnboundGenericClass()
{
ITypeDefinition dictionary = mscorlib.GetTypeDefinition(typeof(Dictionary<,>));
IType keyCollection = dictionary.GetNestedTypes(mscorlib).Single(t => t.Name == "KeyCollection");
ITypeDefinition dictionary = compilation.FindType(typeof(Dictionary<,>)).GetDefinition();
IType keyCollection = dictionary.GetNestedTypes().Single(t => t.Name == "KeyCollection");
// the type should be parameterized
Assert.AreEqual("System.Collections.Generic.Dictionary`2+KeyCollection[[`0],[`1]]", keyCollection.ReflectionName);
}
@ -100,29 +101,32 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void GetNestedTypesOfBoundGenericClass()
{
IType dictionary = typeof(Dictionary<string, int>).ToTypeReference().Resolve(mscorlib);
IType keyCollection = dictionary.GetNestedTypes(mscorlib).Single(t => t.Name == "KeyCollection");
Assert.AreEqual(typeof(Dictionary<string, int>.KeyCollection).ToTypeReference().Resolve(mscorlib), keyCollection);
IType dictionary = compilation.FindType(typeof(Dictionary<string, int>));
IType keyCollection = dictionary.GetNestedTypes().Single(t => t.Name == "KeyCollection");
Assert.AreEqual(compilation.FindType(typeof(Dictionary<string, int>.KeyCollection)), keyCollection);
}
[Test]
public void GetGenericNestedTypeOfBoundGenericClass()
{
// class A<X> { class B<Y> { } }
DefaultTypeDefinition a = new DefaultTypeDefinition(mscorlib, string.Empty, "A");
a.TypeParameters.Add(new DefaultTypeParameter(EntityType.TypeDefinition, 0, "X"));
DefaultUnresolvedTypeDefinition a = new DefaultUnresolvedTypeDefinition(string.Empty, "A");
a.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "X"));
DefaultTypeDefinition b = new DefaultTypeDefinition(a, "B");
DefaultUnresolvedTypeDefinition b = new DefaultUnresolvedTypeDefinition(a, "B");
b.TypeParameters.Add(a.TypeParameters[0]);
b.TypeParameters.Add(new DefaultTypeParameter(EntityType.TypeDefinition, 1, "Y"));
b.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 1, "Y"));
a.NestedTypes.Add(b);
// A<> gets self-parameterized, B<> stays unbound
Assert.AreEqual("A`1+B`1[[`0],[]]", a.GetNestedTypes(mscorlib).Single().ReflectionName);
ITypeDefinition resolvedA = a.Resolve(compilation.TypeResolveContext);
ITypeDefinition resolvedB = b.Resolve(compilation.TypeResolveContext);
ParameterizedType pt = new ParameterizedType(a, new [] { KnownTypeReference.String.Resolve(mscorlib) });
Assert.AreEqual("A`1+B`1[[System.String],[]]", pt.GetNestedTypes(mscorlib).Single().ReflectionName);
// A<> gets self-parameterized, B<> stays unbound
Assert.AreEqual("A`1+B`1[[`0],[]]", resolvedA.GetNestedTypes().Single().ReflectionName);
ParameterizedType pt = new ParameterizedType(resolvedA, new [] { compilation.FindType(KnownTypeCode.String) });
Assert.AreEqual("A`1+B`1[[System.String],[]]", pt.GetNestedTypes().Single().ReflectionName);
}
}
}

Просмотреть файл

@ -20,6 +20,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.TypeSystem
@ -27,11 +28,11 @@ namespace ICSharpCode.NRefactory.TypeSystem
[TestFixture]
public unsafe class ReflectionHelperTests
{
ITypeResolveContext context = CecilLoaderTests.Mscorlib;
ICompilation compilation = new SimpleCompilation(CecilLoaderTests.Mscorlib);
void TestGetClass(Type type)
void TestFindType(Type type)
{
ITypeDefinition t = CecilLoaderTests.Mscorlib.GetTypeDefinition(type);
IType t = compilation.FindType(type);
Assert.IsNotNull(t, type.FullName);
Assert.AreEqual(type.FullName, t.ReflectionName);
}
@ -39,56 +40,56 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void TestGetInnerClass()
{
TestGetClass(typeof(Environment.SpecialFolder));
TestFindType(typeof(Environment.SpecialFolder));
}
[Test]
public void TestGetGenericClass1()
{
TestGetClass(typeof(Action<>));
TestFindType(typeof(Action<>));
}
[Test]
public void TestGetGenericClass2()
{
TestGetClass(typeof(Action<,>));
TestFindType(typeof(Action<,>));
}
[Test]
public void TestGetInnerClassInGenericClass1()
{
TestGetClass(typeof(Dictionary<,>.ValueCollection));
TestFindType(typeof(Dictionary<,>.ValueCollection));
}
[Test]
public void TestGetInnerClassInGenericClass2()
{
TestGetClass(typeof(Dictionary<,>.ValueCollection.Enumerator));
TestFindType(typeof(Dictionary<,>.ValueCollection.Enumerator));
}
[Test]
public void TestToTypeReferenceInnerClass()
{
Assert.AreEqual("System.Environment+SpecialFolder",
typeof(Environment.SpecialFolder).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(Environment.SpecialFolder)).ReflectionName);
}
[Test]
public void TestToTypeReferenceUnboundGenericClass()
{
Assert.AreEqual("System.Action`1",
typeof(Action<>).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(Action<>)).ReflectionName);
Assert.AreEqual("System.Action`2",
typeof(Action<,>).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(Action<,>)).ReflectionName);
}
[Test]
public void TestToTypeReferenceBoundGenericClass()
{
Assert.AreEqual("System.Action`1[[System.String]]",
typeof(Action<string>).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(Action<string>)).ReflectionName);
Assert.AreEqual("System.Action`2[[System.Int32],[System.Int16]]",
typeof(Action<int, short>).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(Action<int, short>)).ReflectionName);
}
@ -96,75 +97,77 @@ namespace ICSharpCode.NRefactory.TypeSystem
public void TestToTypeReferenceNullableType()
{
Assert.AreEqual("System.Nullable`1[[System.Int32]]",
typeof(int?).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(int?)).ReflectionName);
}
[Test]
public void TestToTypeReferenceInnerClassInUnboundGenericType()
{
Assert.AreEqual("System.Collections.Generic.Dictionary`2+ValueCollection",
typeof(Dictionary<,>.ValueCollection).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(Dictionary<,>.ValueCollection)).ReflectionName);
}
[Test]
public void TestToTypeReferenceInnerClassInBoundGenericType()
{
Assert.AreEqual("System.Collections.Generic.Dictionary`2+KeyCollection[[System.String],[System.Int32]]",
typeof(Dictionary<string, int>.KeyCollection).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(Dictionary<string, int>.KeyCollection)).ReflectionName);
}
[Test]
public void TestToTypeReferenceArrayType()
{
Assert.AreEqual(typeof(int[]).FullName,
typeof(int[]).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(int[])).ReflectionName);
}
[Test]
public void TestToTypeReferenceMultidimensionalArrayType()
{
Assert.AreEqual(typeof(int[,]).FullName,
typeof(int[,]).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(int[,])).ReflectionName);
}
[Test]
public void TestToTypeReferenceJaggedMultidimensionalArrayType()
{
Assert.AreEqual(typeof(int[,][,,]).FullName,
typeof(int[,][,,]).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(int[,][,,])).ReflectionName);
}
[Test]
public void TestToTypeReferencePointerType()
{
Assert.AreEqual(typeof(int*).FullName,
typeof(int*).ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(int*)).ReflectionName);
}
[Test]
public void TestToTypeReferenceByReferenceType()
{
Assert.AreEqual(typeof(int).MakeByRefType().FullName,
typeof(int).MakeByRefType().ToTypeReference().Resolve(context).ReflectionName);
compilation.FindType(typeof(int).MakeByRefType()).ReflectionName);
}
[Test]
public void TestToTypeReferenceGenericType()
{
MethodInfo convertAllInfo = typeof(List<>).GetMethod("ConvertAll");
Type parameterType = convertAllInfo.GetParameters()[0].ParameterType; // Converter[[`0],[``0]]
ITypeReference parameterType = convertAllInfo.GetParameters()[0].ParameterType.ToTypeReference(); // Converter[[`0],[``0]]
// cannot resolve generic types without knowing the parent entity:
Assert.AreEqual("System.Converter`2[[?],[?]]",
parameterType.ToTypeReference().Resolve(context).ReflectionName);
parameterType.Resolve(compilation.TypeResolveContext).ReflectionName);
// now try with parent entity:
IMethod convertAll = context.GetTypeDefinition(typeof(List<>)).Methods.Single(m => m.Name == "ConvertAll");
Assert.AreEqual("System.Converter`2[[`0],[``0]]",
parameterType.ToTypeReference(entity: convertAll).Resolve(context).ReflectionName);
IMethod convertAll = compilation.FindType(typeof(List<>)).GetMethods(m => m.Name == "ConvertAll").Single();
throw new NotImplementedException();
//Assert.AreEqual("System.Converter`2[[`0],[``0]]",
// parameterType.Resolve(convertAll.TypeResolveContext).ReflectionName);
}
[Test]
public void ParseReflectionName()
{
var context = compilation.TypeResolveContext;
Assert.AreEqual("System.Int32", ReflectionHelper.ParseReflectionName("System.Int32").Resolve(context).ReflectionName);
Assert.AreEqual("System.Int32&", ReflectionHelper.ParseReflectionName("System.Int32&").Resolve(context).ReflectionName);
Assert.AreEqual("System.Int32*&", ReflectionHelper.ParseReflectionName("System.Int32*&").Resolve(context).ReflectionName);
@ -178,9 +181,11 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void ParseOpenGenericReflectionName()
{
IMethod convertAll = context.GetTypeDefinition(typeof(List<>)).Methods.Single(m => m.Name == "ConvertAll");
Assert.AreEqual("System.Converter`2[[?],[?]]", ReflectionHelper.ParseReflectionName("System.Converter`2[[`0],[``0]]").Resolve(context).ReflectionName);
Assert.AreEqual("System.Converter`2[[`0],[``0]]", ReflectionHelper.ParseReflectionName("System.Converter`2[[`0],[``0]]", convertAll).Resolve(context).ReflectionName);
ITypeReference typeRef = ReflectionHelper.ParseReflectionName("System.Converter`2[[`0],[``0]]");
Assert.AreEqual("System.Converter`2[[?],[?]]", typeRef.Resolve(compilation.TypeResolveContext).ReflectionName);
IMethod convertAll = compilation.FindType(typeof(List<>)).GetMethods(m => m.Name == "ConvertAll").Single();
throw new NotImplementedException();
//Assert.AreEqual("System.Converter`2[[`0],[``0]]", typeRef.Resolve(convertAll).ReflectionName);
}
[Test, ExpectedException(typeof(ArgumentNullException))]

Просмотреть файл

@ -18,6 +18,7 @@
using System;
using System.IO;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
using NUnit.Framework;
@ -30,12 +31,13 @@ namespace ICSharpCode.NRefactory.TypeSystem
public void FixtureSetUp()
{
CecilLoader loader = new CecilLoader() { IncludeInternalMembers = true };
IProjectContent pc = loader.LoadAssemblyFile(typeof(TestCase.SimplePublicClass).Assembly.Location);
IUnresolvedAssembly pc = loader.LoadAssemblyFile(typeof(TestCase.SimplePublicClass).Assembly.Location);
FastSerializer serializer = new FastSerializer();
using (MemoryStream ms = new MemoryStream()) {
serializer.Serialize(ms, pc);
ms.Position = 0;
testCasePC = (IProjectContent)serializer.Deserialize(ms);
var asm = (IUnresolvedAssembly)serializer.Deserialize(ms);
base.compilation = new SimpleCompilation(asm, CecilLoaderTests.Mscorlib);
}
}
}

Просмотреть файл

@ -17,6 +17,7 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Reflection;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.TypeSystem
@ -33,5 +34,41 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
}
}
[Test]
public void System_TypeCode_corresponds_with_KnownTypeCode()
{
foreach (TypeCode typeCode in Enum.GetValues(typeof(System.TypeCode))) {
if (typeCode == TypeCode.Empty)
Assert.AreEqual("None", ((KnownTypeCode)typeCode).ToString());
else
Assert.AreEqual(typeCode.ToString(), ((KnownTypeCode)typeCode).ToString());
}
}
[Test]
public void KnownTypeReference_Get_returns_correct_KnownType()
{
foreach (KnownTypeCode typeCode in Enum.GetValues(typeof(KnownTypeCode))) {
if (typeCode == KnownTypeCode.None) {
Assert.IsNull(KnownTypeReference.Get(KnownTypeCode.None));
} else {
Assert.AreEqual(typeCode, KnownTypeReference.Get(typeCode).KnownTypeCode);
}
}
}
[Test]
public void KnownTypeReference_has_static_fields_for_KnownTypes()
{
foreach (KnownTypeCode typeCode in Enum.GetValues(typeof(KnownTypeCode))) {
if (typeCode == KnownTypeCode.None)
continue;
FieldInfo field = typeof(KnownTypeReference).GetField(typeCode.ToString());
Assert.IsNotNull(field, "Missing field for " + typeCode.ToString());
KnownTypeReference ktr = (KnownTypeReference)field.GetValue(null);
Assert.AreEqual(typeCode, ktr.KnownTypeCode);
}
}
}
}

Просмотреть файл

@ -30,58 +30,54 @@ namespace ICSharpCode.NRefactory.TypeSystem
public void TypeParameterDerivingFromOtherTypeParameterDoesNotInheritReferenceConstraint()
{
// class C<T, U> where T : class where U : T
DefaultTypeDefinition c = new DefaultTypeDefinition(MinimalResolveContext.Instance, string.Empty, "C");
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
DefaultTypeParameter u = new DefaultTypeParameter(EntityType.TypeDefinition, 1, "U");
c.TypeParameters.Add(t);
c.TypeParameters.Add(u);
t.HasReferenceTypeConstraint = true;
u.Constraints.Add(t);
var c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
c.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "T") { HasReferenceTypeConstraint = true });
c.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 1, "U") {
Constraints = { new TypeParameterReference(EntityType.TypeDefinition, 0) }
});
ITypeDefinition resolvedC = c.Resolve(new SimpleCompilation(CecilLoaderTests.Mscorlib).TypeResolveContext);
// At runtime, we might have T=System.ValueType and U=int, so C# can't inherit the 'class' constraint
// from one type parameter to another.
Assert.AreEqual(true, t.IsReferenceType(MinimalResolveContext.Instance));
Assert.IsNull(u.IsReferenceType(MinimalResolveContext.Instance));
Assert.AreEqual(true, resolvedC.TypeParameters[0].IsReferenceType);
Assert.IsNull(resolvedC.TypeParameters[1].IsReferenceType);
}
[Test]
public void ValueTypeParameterDerivingFromReferenceTypeParameter()
{
// class C<T, U> where T : class where U : T
DefaultTypeDefinition c = new DefaultTypeDefinition(MinimalResolveContext.Instance, string.Empty, "C");
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
DefaultTypeParameter u = new DefaultTypeParameter(EntityType.TypeDefinition, 1, "U");
c.TypeParameters.Add(t);
c.TypeParameters.Add(u);
t.HasReferenceTypeConstraint = true;
u.HasValueTypeConstraint = true;
u.Constraints.Add(t);
// class C<T, U> where T : class where U : struct, T
var c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
c.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "T") { HasReferenceTypeConstraint = true });
c.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 1, "U") {
HasValueTypeConstraint = true,
Constraints = { new TypeParameterReference(EntityType.TypeDefinition, 0) }
});
ITypeDefinition resolvedC = c.Resolve(new SimpleCompilation(CecilLoaderTests.Mscorlib).TypeResolveContext);
// At runtime, we might have T=System.ValueType and U=int, so C# can't inherit the 'class' constraint
// from one type parameter to another.
Assert.AreEqual(true, t.IsReferenceType(MinimalResolveContext.Instance));
Assert.AreEqual(false, u.IsReferenceType(MinimalResolveContext.Instance));
Assert.AreEqual(true, resolvedC.TypeParameters[0].IsReferenceType);
Assert.AreEqual(false, resolvedC.TypeParameters[1].IsReferenceType);
}
[Test]
public void TypeParameterDerivingFromOtherTypeParameterInheritsEffectiveBaseClass()
{
// class C<T, U> where T : class where U : T
ITypeResolveContext context = CecilLoaderTests.Mscorlib;
DefaultTypeDefinition c = new DefaultTypeDefinition(CecilLoaderTests.Mscorlib, string.Empty, "C");
DefaultTypeParameter t = new DefaultTypeParameter(EntityType.TypeDefinition, 0, "T");
DefaultTypeParameter u = new DefaultTypeParameter(EntityType.TypeDefinition, 1, "U");
c.TypeParameters.Add(t);
c.TypeParameters.Add(u);
t.Constraints.Add(typeof(List<string>).ToTypeReference());
u.Constraints.Add(t);
// class C<T, U> where T : List<string> where U : T
var c = new DefaultUnresolvedTypeDefinition(string.Empty, "C");
c.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 0, "T") {
Constraints = { typeof(List<string>).ToTypeReference() }
});
c.TypeParameters.Add(new DefaultUnresolvedTypeParameter(EntityType.TypeDefinition, 1, "U") {
Constraints = { new TypeParameterReference(EntityType.TypeDefinition, 0) }
});
// At runtime, we might have T=System.ValueType and U=int, so C# can't inherit the 'class' constraint
// from one type parameter to another.
Assert.AreEqual(true, t.IsReferenceType(context));
Assert.AreEqual(true, u.IsReferenceType(context));
Assert.AreEqual("System.Collections.Generic.List`1[[System.String]]", t.GetEffectiveBaseClass(context).ReflectionName);
Assert.AreEqual("System.Collections.Generic.List`1[[System.String]]", u.GetEffectiveBaseClass(context).ReflectionName);
ITypeDefinition resolvedC = c.Resolve(new SimpleCompilation(CecilLoaderTests.Mscorlib).TypeResolveContext);
Assert.AreEqual(true, resolvedC.TypeParameters[0].IsReferenceType);
Assert.AreEqual(true, resolvedC.TypeParameters[1].IsReferenceType);
Assert.AreEqual("System.Collections.Generic.List`1[[System.String]]", resolvedC.TypeParameters[0].EffectiveBaseClass);
Assert.AreEqual("System.Collections.Generic.List`1[[System.String]]", resolvedC.TypeParameters[1].EffectiveBaseClass);
}
}
}

Просмотреть файл

@ -35,25 +35,17 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary>
public abstract class TypeSystemTests
{
protected IProjectContent testCasePC;
protected ICompilation compilation;
ITypeResolveContext ctx;
[SetUpAttribute]
public void SetUp()
ITypeDefinition GetTypeDefinition(Type type)
{
ctx = CompositeTypeResolveContext.Combine(testCasePC, CecilLoaderTests.Mscorlib);
}
ITypeDefinition GetClass(Type type)
{
return testCasePC.GetTypeDefinition(type);
return compilation.FindType(type).GetDefinition();
}
[Test]
public void SimplePublicClassTest()
{
ITypeDefinition c = testCasePC.GetTypeDefinition(typeof(SimplePublicClass));
ITypeDefinition c = GetTypeDefinition(typeof(SimplePublicClass));
Assert.AreEqual(typeof(SimplePublicClass).Name, c.Name);
Assert.AreEqual(typeof(SimplePublicClass).FullName, c.FullName);
Assert.AreEqual(typeof(SimplePublicClass).Namespace, c.Namespace);
@ -69,7 +61,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void SimplePublicClassMethodTest()
{
ITypeDefinition c = testCasePC.GetTypeDefinition(typeof(SimplePublicClass));
ITypeDefinition c = GetTypeDefinition(typeof(SimplePublicClass));
IMethod method = c.Methods.Single(m => m.Name == "Method");
Assert.AreEqual(typeof(SimplePublicClass).FullName + ".Method", method.FullName);
@ -78,7 +70,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
Assert.AreEqual(EntityType.Method, method.EntityType);
Assert.IsFalse(method.IsVirtual);
Assert.IsFalse(method.IsStatic);
Assert.IsTrue(method.IsFrozen);
Assert.AreEqual(0, method.Parameters.Count);
Assert.AreEqual(0, method.Attributes.Count);
}
@ -86,43 +77,43 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void DynamicType()
{
ITypeDefinition testClass = testCasePC.GetTypeDefinition(typeof(DynamicTest));
Assert.AreEqual(SharedTypes.Dynamic, testClass.Properties.Single().ReturnType.Resolve(ctx));
ITypeDefinition testClass = GetTypeDefinition(typeof(DynamicTest));
Assert.AreEqual(SpecialType.Dynamic, testClass.Properties.Single().ReturnType);
Assert.AreEqual(0, testClass.Properties.Single().Attributes.Count);
}
[Test]
public void DynamicTypeInGenerics()
{
ITypeDefinition testClass = testCasePC.GetTypeDefinition(typeof(DynamicTest));
ITypeDefinition testClass = GetTypeDefinition(typeof(DynamicTest));
IMethod m1 = testClass.Methods.Single(me => me.Name == "DynamicGenerics1");
Assert.AreEqual("System.Collections.Generic.List`1[[dynamic]]", m1.ReturnType.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Action`3[[System.Object],[dynamic[]],[System.Object]]", m1.Parameters[0].Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Collections.Generic.List`1[[dynamic]]", m1.ReturnType.ReflectionName);
Assert.AreEqual("System.Action`3[[System.Object],[dynamic[]],[System.Object]]", m1.Parameters[0].Type.ReflectionName);
IMethod m2 = testClass.Methods.Single(me => me.Name == "DynamicGenerics2");
Assert.AreEqual("System.Action`3[[System.Object],[dynamic],[System.Object]]", m2.Parameters[0].Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Action`3[[System.Object],[dynamic],[System.Object]]", m2.Parameters[0].Type.ReflectionName);
IMethod m3 = testClass.Methods.Single(me => me.Name == "DynamicGenerics3");
Assert.AreEqual("System.Action`3[[System.Int32],[dynamic],[System.Object]]", m3.Parameters[0].Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Action`3[[System.Int32],[dynamic],[System.Object]]", m3.Parameters[0].Type.ReflectionName);
IMethod m4 = testClass.Methods.Single(me => me.Name == "DynamicGenerics4");
Assert.AreEqual("System.Action`3[[System.Int32[]],[dynamic],[System.Object]]", m4.Parameters[0].Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Action`3[[System.Int32[]],[dynamic],[System.Object]]", m4.Parameters[0].Type.ReflectionName);
IMethod m5 = testClass.Methods.Single(me => me.Name == "DynamicGenerics5");
Assert.AreEqual("System.Action`3[[System.Int32*[]],[dynamic],[System.Object]]", m5.Parameters[0].Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Action`3[[System.Int32*[]],[dynamic],[System.Object]]", m5.Parameters[0].Type.ReflectionName);
IMethod m6 = testClass.Methods.Single(me => me.Name == "DynamicGenerics6");
Assert.AreEqual("System.Action`3[[System.Object],[dynamic],[System.Object]]&", m6.Parameters[0].Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Action`3[[System.Object],[dynamic],[System.Object]]&", m6.Parameters[0].Type.ReflectionName);
IMethod m7 = testClass.Methods.Single(me => me.Name == "DynamicGenerics7");
Assert.AreEqual("System.Action`3[[System.Int32[][,]],[dynamic],[System.Object]]", m7.Parameters[0].Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("System.Action`3[[System.Int32[][,]],[dynamic],[System.Object]]", m7.Parameters[0].Type.ReflectionName);
}
[Test]
public void DynamicParameterHasNoAttributes()
{
ITypeDefinition testClass = testCasePC.GetTypeDefinition(typeof(DynamicTest));
ITypeDefinition testClass = GetTypeDefinition(typeof(DynamicTest));
IMethod m1 = testClass.Methods.Single(me => me.Name == "DynamicGenerics1");
Assert.AreEqual(0, m1.Parameters[0].Attributes.Count);
}
@ -130,19 +121,18 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void AssemblyAttribute()
{
var attributes = testCasePC.AssemblyAttributes;
var typeTest = attributes.Single(a => a.AttributeType.Resolve(ctx).FullName == typeof(TypeTestAttribute).FullName);
var posArgs = typeTest.GetPositionalArguments(ctx);
Assert.AreEqual(3, posArgs.Count);
var attributes = compilation.MainAssembly.AssemblyAttributes;
var typeTest = attributes.Single(a => a.AttributeType.FullName == typeof(TypeTestAttribute).FullName);
Assert.AreEqual(3, typeTest.PositionalArguments.Count);
// first argument is (int)42
Assert.AreEqual(42, (int)posArgs[0].ConstantValue);
Assert.AreEqual(42, (int)typeTest.PositionalArguments[0].ConstantValue);
// second argument is typeof(System.Action<>)
TypeOfResolveResult rt = (TypeOfResolveResult)posArgs[1];
TypeOfResolveResult rt = (TypeOfResolveResult)typeTest.PositionalArguments[1];
Assert.IsFalse(rt.ReferencedType is ParameterizedType); // rt must not be constructed - it's just an unbound type
Assert.AreEqual("System.Action", rt.ReferencedType.FullName);
Assert.AreEqual(1, rt.ReferencedType.TypeParameterCount);
// third argument is typeof(IDictionary<string, IList<TestAttribute>>)
rt = (TypeOfResolveResult)posArgs[2];
rt = (TypeOfResolveResult)typeTest.PositionalArguments[2];
ParameterizedType crt = (ParameterizedType)rt.ReferencedType;
Assert.AreEqual("System.Collections.Generic.IDictionary", crt.FullName);
Assert.AreEqual("System.String", crt.TypeArguments[0].FullName);
@ -153,27 +143,26 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void TypeForwardedTo_Attribute()
{
var attributes = testCasePC.AssemblyAttributes;
var forwardAttribute = attributes.Single(a => a.AttributeType.Resolve(ctx).FullName == typeof(TypeForwardedToAttribute).FullName);
var posArgs = forwardAttribute.GetPositionalArguments(ctx);
Assert.AreEqual(1, posArgs.Count);
TypeOfResolveResult rt = (TypeOfResolveResult)posArgs[0];
var attributes = compilation.MainAssembly.AssemblyAttributes;
var forwardAttribute = attributes.Single(a => a.AttributeType.FullName == typeof(TypeForwardedToAttribute).FullName);
Assert.AreEqual(1, forwardAttribute.PositionalArguments.Count);
TypeOfResolveResult rt = (TypeOfResolveResult)forwardAttribute.PositionalArguments[0];
Assert.AreEqual("System.Func`2", rt.ReferencedType.ReflectionName);
}
[Test]
public void TestClassTypeParameters()
{
var testClass = testCasePC.GetTypeDefinition(typeof(GenericClass<,>));
var testClass = GetTypeDefinition(typeof(GenericClass<,>));
Assert.AreEqual(EntityType.TypeDefinition, testClass.TypeParameters[0].OwnerType);
Assert.AreEqual(EntityType.TypeDefinition, testClass.TypeParameters[1].OwnerType);
Assert.AreSame(testClass.TypeParameters[1], testClass.TypeParameters[0].GetConstraints(ctx)[0].Resolve(ctx));
Assert.AreSame(testClass.TypeParameters[1], testClass.TypeParameters[0].DirectBaseTypes.First());
}
[Test]
public void TestMethod()
{
var testClass = testCasePC.GetTypeDefinition(typeof(GenericClass<,>));
var testClass = GetTypeDefinition(typeof(GenericClass<,>));
IMethod m = testClass.Methods.Single(me => me.Name == "TestMethod");
Assert.AreEqual("K", m.TypeParameters[0].Name);
@ -181,20 +170,20 @@ namespace ICSharpCode.NRefactory.TypeSystem
Assert.AreEqual(EntityType.Method, m.TypeParameters[0].OwnerType);
Assert.AreEqual(EntityType.Method, m.TypeParameters[1].OwnerType);
Assert.AreEqual("System.IComparable`1[[``1]]", m.TypeParameters[0].GetConstraints(ctx)[0].Resolve(ctx).ReflectionName);
Assert.AreSame(m.TypeParameters[0], m.TypeParameters[1].GetConstraints(ctx)[0].Resolve(ctx));
Assert.AreEqual("System.IComparable`1[[``1]]", m.TypeParameters[0].DirectBaseTypes.First().ReflectionName);
Assert.AreSame(m.TypeParameters[0], m.TypeParameters[1].DirectBaseTypes.First());
}
[Test]
public void GetIndex()
{
var testClass = testCasePC.GetTypeDefinition(typeof(GenericClass<,>));
var testClass = GetTypeDefinition(typeof(GenericClass<,>));
IMethod m = testClass.Methods.Single(me => me.Name == "GetIndex");
Assert.AreEqual("T", m.TypeParameters[0].Name);
Assert.AreEqual(EntityType.Method, m.TypeParameters[0].OwnerType);
ParameterizedType constraint = (ParameterizedType)m.TypeParameters[0].GetConstraints(ctx)[0].Resolve(ctx);
ParameterizedType constraint = (ParameterizedType)m.TypeParameters[0].DirectBaseTypes.First();
Assert.AreEqual("IEquatable", constraint.Name);
Assert.AreEqual(1, constraint.TypeParameterCount);
Assert.AreEqual(1, constraint.TypeArguments.Count);
@ -204,7 +193,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void PropertyWithProtectedSetter()
{
var testClass = testCasePC.GetTypeDefinition(typeof(PropertyTest));
var testClass = GetTypeDefinition(typeof(PropertyTest));
IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithProtectedSetter");
Assert.IsTrue(p.CanGet);
Assert.IsTrue(p.CanSet);
@ -216,7 +205,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void PropertyWithPrivateSetter()
{
var testClass = testCasePC.GetTypeDefinition(typeof(PropertyTest));
var testClass = GetTypeDefinition(typeof(PropertyTest));
IProperty p = testClass.Properties.Single(pr => pr.Name == "PropertyWithPrivateSetter");
Assert.IsTrue(p.CanGet);
Assert.IsTrue(p.CanSet);
@ -228,7 +217,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void Indexer()
{
var testClass = testCasePC.GetTypeDefinition(typeof(PropertyTest));
var testClass = GetTypeDefinition(typeof(PropertyTest));
IProperty p = testClass.Properties.Single(pr => pr.IsIndexer);
Assert.AreEqual("Item", p.Name);
Assert.IsTrue(p.CanGet);
@ -241,58 +230,59 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void EnumTest()
{
var e = testCasePC.GetTypeDefinition(typeof(MyEnum));
var e = GetTypeDefinition(typeof(MyEnum));
Assert.AreEqual(TypeKind.Enum, e.Kind);
Assert.AreEqual(false, e.IsReferenceType(ctx));
Assert.AreEqual("System.Int16", e.BaseTypes[0].Resolve(ctx).ReflectionName);
Assert.AreEqual(new[] { "System.Enum" }, e.GetBaseTypes(ctx).Select(t => t.ReflectionName).ToArray());
Assert.AreEqual(false, e.IsReferenceType);
Assert.AreEqual("System.Int16", e.EnumUnderlyingType.ReflectionName);
Assert.AreEqual(new[] { "System.Enum" }, e.DirectBaseTypes.Select(t => t.ReflectionName).ToArray());
}
[Test]
public void EnumFieldsTest()
{
var e = testCasePC.GetTypeDefinition(typeof(MyEnum));
Assert.AreEqual(5, e.Fields.Count);
var e = GetTypeDefinition(typeof(MyEnum));
IField[] fields = e.Fields.ToArray();
Assert.AreEqual(5, fields.Length);
foreach (IField f in e.Fields) {
foreach (IField f in fields) {
Assert.IsTrue(f.IsStatic);
Assert.IsTrue(f.IsConst);
Assert.AreEqual(Accessibility.Public, f.Accessibility);
Assert.AreSame(e, f.ConstantValue.Resolve(ctx).Type);
Assert.AreEqual(typeof(short), f.ConstantValue.Resolve(ctx).ConstantValue.GetType());
Assert.AreSame(e, f.Type);
Assert.AreEqual(typeof(short), f.ConstantValue.GetType());
}
Assert.AreEqual("First", e.Fields[0].Name);
Assert.AreEqual(0, e.Fields[0].ConstantValue.Resolve(ctx).ConstantValue);
Assert.AreEqual("First", fields[0].Name);
Assert.AreEqual(0, fields[0].ConstantValue);
Assert.AreEqual("Second", e.Fields[1].Name);
Assert.AreSame(e, e.Fields[1].ConstantValue.Resolve(ctx).Type);
Assert.AreEqual(1, e.Fields[1].ConstantValue.Resolve(ctx).ConstantValue);
Assert.AreEqual("Second", fields[1].Name);
Assert.AreSame(e, fields[1].Type);
Assert.AreEqual(1, fields[1].ConstantValue);
Assert.AreEqual("Flag1", e.Fields[2].Name);
Assert.AreEqual(0x10, e.Fields[2].ConstantValue.Resolve(ctx).ConstantValue);
Assert.AreEqual("Flag1", fields[2].Name);
Assert.AreEqual(0x10, fields[2].ConstantValue);
Assert.AreEqual("Flag2", e.Fields[3].Name);
Assert.AreEqual(0x20, e.Fields[3].ConstantValue.Resolve(ctx).ConstantValue);
Assert.AreEqual("Flag2", fields[3].Name);
Assert.AreEqual(0x20, fields[3].ConstantValue);
Assert.AreEqual("CombinedFlags", e.Fields[4].Name);
Assert.AreEqual(0x30, e.Fields[4].ConstantValue.Resolve(ctx).ConstantValue);
Assert.AreEqual("CombinedFlags", fields[4].Name);
Assert.AreEqual(0x30, fields[4].ConstantValue);
}
[Test]
public void GetNestedTypesFromBaseClassTest()
{
ITypeDefinition d = ctx.GetTypeDefinition(typeof(Derived<,>));
ITypeDefinition d = GetTypeDefinition(typeof(Derived<,>));
IType pBase = d.BaseTypes.Single().Resolve(ctx);
IType pBase = d.DirectBaseTypes.Single();
Assert.AreEqual(typeof(Base<>).FullName + "[[`1]]", pBase.ReflectionName);
// Base[`1].GetNestedTypes() = { Base`1+Nested`1[`1, unbound] }
Assert.AreEqual(new[] { typeof(Base<>.Nested<>).FullName + "[[`1],[]]" },
pBase.GetNestedTypes(ctx).Select(n => n.ReflectionName).ToArray());
pBase.GetNestedTypes().Select(n => n.ReflectionName).ToArray());
// Derived.GetNestedTypes() = { Base`1+Nested`1[`1, unbound] }
Assert.AreEqual(new[] { typeof(Base<>.Nested<>).FullName + "[[`1],[]]" },
d.GetNestedTypes(ctx).Select(n => n.ReflectionName).ToArray());
d.GetNestedTypes().Select(n => n.ReflectionName).ToArray());
// This is 'leaking' the type parameter from B as is usual when retrieving any members from an unbound type.
}
@ -300,29 +290,27 @@ namespace ICSharpCode.NRefactory.TypeSystem
public void ParameterizedTypeGetNestedTypesFromBaseClassTest()
{
// Derived[string,int].GetNestedTypes() = { Base`1+Nested`1[int, unbound] }
var d = typeof(Derived<string, int>).ToTypeReference().Resolve(ctx);
var d = compilation.FindType(typeof(Derived<string, int>));
Assert.AreEqual(new[] { typeof(Base<>.Nested<>).FullName + "[[System.Int32],[]]" },
d.GetNestedTypes(ctx).Select(n => n.ReflectionName).ToArray());
d.GetNestedTypes().Select(n => n.ReflectionName).ToArray());
}
[Test]
public void ConstraintsOnOverrideAreInherited()
{
ITypeDefinition d = ctx.GetTypeDefinition(typeof(Derived<,>));
ITypeDefinition d = GetTypeDefinition(typeof(Derived<,>));
ITypeParameter tp = d.Methods.Single(m => m.Name == "GenericMethodWithConstraints").TypeParameters.Single();
Assert.AreEqual("Y", tp.Name);
ITypeParameterConstraints constraints = tp.GetConstraints(ctx);
Assert.IsFalse(constraints.HasValueTypeConstraint);
Assert.IsFalse(constraints.HasReferenceTypeConstraint);
Assert.IsTrue(constraints.HasDefaultConstructorConstraint);
Assert.AreEqual(1, constraints.Count);
Assert.AreEqual("System.Collections.Generic.IComparer`1[[`1]]", constraints[0].ReflectionName);
Assert.IsFalse(tp.HasValueTypeConstraint);
Assert.IsFalse(tp.HasReferenceTypeConstraint);
Assert.IsTrue(tp.HasDefaultConstructorConstraint);
Assert.AreEqual(new string[] { "System.Collections.Generic.IComparer`1[[`1]]" }, tp.DirectBaseTypes.Select(t => t.ReflectionName).ToArray());
}
[Test]
public void DefaultConstructorAddedToStruct()
{
var ctors = typeof(MyStructWithCtor).ToTypeReference().Resolve(ctx).GetConstructors(ctx);
var ctors = compilation.FindType(typeof(MyStructWithCtor)).GetConstructors();
Assert.AreEqual(2, ctors.Count());
Assert.IsFalse(ctors.Any(c => c.IsStatic));
}
@ -330,33 +318,32 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void SerializableAttribute()
{
IAttribute attr = ctx.GetTypeDefinition(typeof(NonCustomAttributes)).Attributes.Single();
Assert.AreEqual("System.SerializableAttribute", attr.AttributeType.Resolve(ctx).FullName);
IAttribute attr = GetTypeDefinition(typeof(NonCustomAttributes)).Attributes.Single();
Assert.AreEqual("System.SerializableAttribute", attr.AttributeType.FullName);
}
[Test]
public void NonSerializedAttribute()
{
IField field = ctx.GetTypeDefinition(typeof(NonCustomAttributes)).Fields.Single(f => f.Name == "NonSerializedField");
Assert.AreEqual("System.NonSerializedAttribute", field.Attributes.Single().AttributeType.Resolve(ctx).FullName);
IField field = GetTypeDefinition(typeof(NonCustomAttributes)).Fields.Single(f => f.Name == "NonSerializedField");
Assert.AreEqual("System.NonSerializedAttribute", field.Attributes.Single().AttributeType.FullName);
}
[Test]
public void ExplicitStructLayoutAttribute()
{
IAttribute attr = ctx.GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Attributes.Single();
Assert.AreEqual("System.Runtime.InteropServices.StructLayoutAttribute", attr.AttributeType.Resolve(ctx).FullName);
ResolveResult arg1 = attr.GetPositionalArguments(ctx).Single();
IAttribute attr = GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Attributes.Single();
Assert.AreEqual("System.Runtime.InteropServices.StructLayoutAttribute", attr.AttributeType.FullName);
ResolveResult arg1 = attr.PositionalArguments.Single();
Assert.AreEqual("System.Runtime.InteropServices.LayoutKind", arg1.Type.FullName);
Assert.AreEqual((int)LayoutKind.Explicit, arg1.ConstantValue);
var namedArgs = attr.GetNamedArguments(ctx);
var arg2 = namedArgs[0];
var arg2 = attr.NamedArguments[0];
Assert.AreEqual("CharSet", arg2.Key);
Assert.AreEqual("System.Runtime.InteropServices.CharSet", arg2.Value.Type.FullName);
Assert.AreEqual((int)CharSet.Unicode, arg2.Value.ConstantValue);
var arg3 = namedArgs[1];
var arg3 = attr.NamedArguments[1];
Assert.AreEqual("Pack", arg3.Key);
Assert.AreEqual("System.Int32", arg3.Value.Type.FullName);
Assert.AreEqual(8, arg3.Value.ConstantValue);
@ -365,15 +352,15 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void FieldOffsetAttribute()
{
IField field = ctx.GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Fields.Single(f => f.Name == "Field0");
Assert.AreEqual("System.Runtime.InteropServices.FieldOffsetAttribute", field.Attributes.Single().AttributeType.Resolve(ctx).FullName);
ResolveResult arg = field.Attributes.Single().GetPositionalArguments(ctx).Single();
IField field = GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Fields.Single(f => f.Name == "Field0");
Assert.AreEqual("System.Runtime.InteropServices.FieldOffsetAttribute", field.Attributes.Single().AttributeType.FullName);
ResolveResult arg = field.Attributes.Single().PositionalArguments.Single();
Assert.AreEqual("System.Int32", arg.Type.FullName);
Assert.AreEqual(0, arg.ConstantValue);
field = ctx.GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Fields.Single(f => f.Name == "Field100");
Assert.AreEqual("System.Runtime.InteropServices.FieldOffsetAttribute", field.Attributes.Single().AttributeType.Resolve(ctx).FullName);
arg = field.Attributes.Single().GetPositionalArguments(ctx).Single();
field = GetTypeDefinition(typeof(ExplicitFieldLayoutStruct)).Fields.Single(f => f.Name == "Field100");
Assert.AreEqual("System.Runtime.InteropServices.FieldOffsetAttribute", field.Attributes.Single().AttributeType.FullName);
arg = field.Attributes.Single().PositionalArguments.Single();
Assert.AreEqual("System.Int32", arg.Type.FullName);
Assert.AreEqual(100, arg.ConstantValue);
}
@ -381,92 +368,92 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void DllImportAttribute()
{
IMethod method = ctx.GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod");
IMethod method = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod");
IAttribute dllImport = method.Attributes.Single();
Assert.AreEqual("System.Runtime.InteropServices.DllImportAttribute", dllImport.AttributeType.Resolve(ctx).FullName);
Assert.AreEqual("unmanaged.dll", dllImport.GetPositionalArguments(ctx)[0].ConstantValue);
Assert.AreEqual((int)CharSet.Unicode, dllImport.GetNamedArguments(ctx).Single().Value.ConstantValue);
Assert.AreEqual("System.Runtime.InteropServices.DllImportAttribute", dllImport.AttributeType.FullName);
Assert.AreEqual("unmanaged.dll", dllImport.PositionalArguments[0].ConstantValue);
Assert.AreEqual((int)CharSet.Unicode, dllImport.NamedArguments.Single().Value.ConstantValue);
}
[Test]
public void InOutParametersOnRefMethod()
{
IParameter p = ctx.GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod").Parameters.Single();
IParameter p = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod").Parameters.Single();
Assert.IsTrue(p.IsRef);
Assert.IsFalse(p.IsOut);
Assert.AreEqual(2, p.Attributes.Count);
Assert.AreEqual("System.Runtime.InteropServices.InAttribute", p.Attributes[0].AttributeType.Resolve(ctx).FullName);
Assert.AreEqual("System.Runtime.InteropServices.OutAttribute", p.Attributes[1].AttributeType.Resolve(ctx).FullName);
Assert.AreEqual("System.Runtime.InteropServices.InAttribute", p.Attributes[0].AttributeType.FullName);
Assert.AreEqual("System.Runtime.InteropServices.OutAttribute", p.Attributes[1].AttributeType.FullName);
}
[Test]
public void MarshalAsAttributeOnMethod()
{
IMethod method = ctx.GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod");
IMethod method = GetTypeDefinition(typeof(NonCustomAttributes)).Methods.Single(m => m.Name == "DllMethod");
IAttribute marshalAs = method.ReturnTypeAttributes.Single();
Assert.AreEqual((int)UnmanagedType.Bool, marshalAs.GetPositionalArguments(ctx).Single().ConstantValue);
Assert.AreEqual((int)UnmanagedType.Bool, marshalAs.PositionalArguments.Single().ConstantValue);
}
[Test]
public void MethodWithOutParameter()
{
IParameter p = ctx.GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOutParameter").Parameters.Single();
IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithOutParameter").Parameters.Single();
Assert.IsFalse(p.IsRef);
Assert.IsTrue(p.IsOut);
Assert.AreEqual(0, p.Attributes.Count);
Assert.IsTrue(p.Type is ByReferenceTypeReference);
Assert.IsTrue(p.Type.Kind == TypeKind.ByReference);
}
[Test]
public void MethodWithParamsArray()
{
IParameter p = ctx.GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithParamsArray").Parameters.Single();
IParameter p = GetTypeDefinition(typeof(ParameterTests)).Methods.Single(m => m.Name == "MethodWithParamsArray").Parameters.Single();
Assert.IsFalse(p.IsRef);
Assert.IsFalse(p.IsOut);
Assert.IsTrue(p.IsParams);
Assert.AreEqual(0, p.Attributes.Count);
Assert.IsTrue(p.Type is ArrayTypeReference);
Assert.IsTrue(p.Type.Kind == TypeKind.Array);
}
[Test]
public void GenericDelegate_Variance()
{
ITypeDefinition type = ctx.GetTypeDefinition(typeof(GenericDelegate<,>));
ITypeDefinition type = GetTypeDefinition(typeof(GenericDelegate<,>));
Assert.AreEqual(VarianceModifier.Contravariant, type.TypeParameters[0].Variance);
Assert.AreEqual(VarianceModifier.Covariant, type.TypeParameters[1].Variance);
Assert.AreSame(type.TypeParameters[1], type.TypeParameters[0].GetConstraints(ctx)[0].Resolve(ctx));
Assert.AreSame(type.TypeParameters[1], type.TypeParameters[0].DirectBaseTypes.FirstOrDefault());
}
[Test]
public void GenericDelegate_ReferenceTypeConstraints()
{
ITypeDefinition type = ctx.GetTypeDefinition(typeof(GenericDelegate<,>));
Assert.IsFalse(type.TypeParameters[0].GetConstraints(ctx).HasReferenceTypeConstraint);
Assert.IsTrue(type.TypeParameters[1].GetConstraints(ctx).HasReferenceTypeConstraint);
ITypeDefinition type = GetTypeDefinition(typeof(GenericDelegate<,>));
Assert.IsFalse(type.TypeParameters[0].HasReferenceTypeConstraint);
Assert.IsTrue(type.TypeParameters[1].HasReferenceTypeConstraint);
Assert.IsNull(type.TypeParameters[0].IsReferenceType(ctx));
Assert.AreEqual(true, type.TypeParameters[1].IsReferenceType(ctx));
Assert.IsNull(type.TypeParameters[0].IsReferenceType);
Assert.AreEqual(true, type.TypeParameters[1].IsReferenceType);
}
[Test]
public void GenericDelegate_GetInvokeMethod()
{
IType type = typeof(GenericDelegate<string, object>).ToTypeReference().Resolve(ctx);
IType type = compilation.FindType(typeof(GenericDelegate<string, object>));
IMethod m = type.GetDelegateInvokeMethod();
Assert.AreEqual("Invoke", m.Name);
Assert.AreEqual("System.Object", m.ReturnType.Resolve(ctx).FullName);
Assert.AreEqual("System.String", m.Parameters[0].Type.Resolve(ctx).FullName);
Assert.AreEqual("System.Object", m.ReturnType.FullName);
Assert.AreEqual("System.String", m.Parameters[0].Type.FullName);
}
[Test]
public void ComInterfaceTest()
{
ITypeDefinition type = ctx.GetTypeDefinition(typeof(IAssemblyEnum));
ITypeDefinition type = GetTypeDefinition(typeof(IAssemblyEnum));
// [ComImport]
Assert.AreEqual(1, type.Attributes.Count(a => a.AttributeType.Resolve(ctx).FullName == typeof(ComImportAttribute).FullName));
Assert.AreEqual(1, type.Attributes.Count(a => a.AttributeType.FullName == typeof(ComImportAttribute).FullName));
IMethod m = type.Methods.Single();
IMethod m = type.Members.OfType<IMethod>().Single();
Assert.AreEqual("GetNextAssembly", m.Name);
Assert.AreEqual(Accessibility.Public, m.Accessibility);
Assert.IsTrue(m.IsAbstract);
@ -476,33 +463,33 @@ namespace ICSharpCode.NRefactory.TypeSystem
[Test]
public void ConstantAnswer()
{
ITypeDefinition type = ctx.GetTypeDefinition(typeof(ConstantTest));
IField answer = type.Fields.Single(f => f.Name == "Answer");
ITypeDefinition type = GetTypeDefinition(typeof(ConstantTest));
IField answer = type.Members.OfType<IField>().Single(f => f.Name == "Answer");
Assert.IsTrue(answer.IsConst);
Assert.AreEqual(42, answer.ConstantValue.Resolve(ctx).ConstantValue);
Assert.AreEqual(42, answer.ConstantValue);
}
[Test]
public void ConstantNullString()
{
ITypeDefinition type = ctx.GetTypeDefinition(typeof(ConstantTest));
IField answer = type.Fields.Single(f => f.Name == "NullString");
ITypeDefinition type = GetTypeDefinition(typeof(ConstantTest));
IField answer = type.Members.OfType<IField>().Single(f => f.Name == "NullString");
Assert.IsTrue(answer.IsConst);
Assert.IsNull(answer.ConstantValue.Resolve(ctx).ConstantValue);
Assert.IsNull(answer.ConstantValue);
}
[Test]
public void InnerClassInGenericClassIsReferencedUsingParameterizedType()
{
ITypeDefinition type = ctx.GetTypeDefinition(typeof(OuterGeneric<>));
IField field1 = type.Fields.Single(f => f.Name == "Field1");
IField field2 = type.Fields.Single(f => f.Name == "Field2");
IField field3 = type.Fields.Single(f => f.Name == "Field3");
ITypeDefinition type = GetTypeDefinition(typeof(OuterGeneric<>));
IField field1 = type.Members.OfType<IField>().Single(f => f.Name == "Field1");
IField field2 = type.Members.OfType<IField>().Single(f => f.Name == "Field2");
IField field3 = type.Members.OfType<IField>().Single(f => f.Name == "Field3");
// types must be self-parameterized
Assert.AreEqual("ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[`0]]", field1.Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[`0]]", field2.Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[`0]]]]", field3.Type.Resolve(ctx).ReflectionName);
Assert.AreEqual("ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[`0]]", field1.Type.ReflectionName);
Assert.AreEqual("ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[`0]]", field2.Type.ReflectionName);
Assert.AreEqual("ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[ICSharpCode.NRefactory.TypeSystem.TestCase.OuterGeneric`1+Inner[[`0]]]]", field3.Type.ReflectionName);
}
}
}

Просмотреть файл

@ -18,7 +18,7 @@ namespace ICSharpCode.NRefactory.VB.Visitors
TypeKind GetTypeKindForAstType(CSharp.AstType type);
TypeCode ResolveExpression(CSharp.Expression expression);
bool? IsReferenceType(CSharp.Expression expression);
ITypeResolveContext ResolveContext { get; }
//ITypeResolveContext ResolveContext { get; }
IType ResolveType(AstType type, TypeDeclaration entity = null);
}
@ -1624,7 +1624,7 @@ namespace ICSharpCode.NRefactory.VB.Visitors
foreach (var type in current.ImplementsTypes) {
var resolved = provider.ResolveType(type, current);
var found = resolved.GetMembers(provider.ResolveContext, m => m.EntityType == EntityType.Method && m.Name == result.Name.Name);
var found = resolved.GetMembers(m => m.EntityType == EntityType.Method && m.Name == result.Name.Name);
if (found.FirstOrDefault() != null) {
result.ImplementsClause.Add(new InterfaceMemberSpecifier((AstType)type.Clone(), found.FirstOrDefault().Name));
}
@ -1640,7 +1640,7 @@ namespace ICSharpCode.NRefactory.VB.Visitors
foreach (var type in current.ImplementsTypes) {
var resolved = provider.ResolveType(type, current);
var found = resolved.GetMembers(provider.ResolveContext, m => m.EntityType == EntityType.Event && m.Name == result.Name.Name);
var found = resolved.GetMembers(m => m.EntityType == EntityType.Event && m.Name == result.Name.Name);
if (found.FirstOrDefault() != null) {
result.ImplementsClause.Add(new InterfaceMemberSpecifier((AstType)type.Clone(), found.FirstOrDefault().Name));
}

Просмотреть файл

@ -33,12 +33,7 @@ namespace ICSharpCode.NRefactory.Documentation
/// <summary>
/// Gets the ID string (C# 4.0 spec, §A.3.1) for the specified entity.
/// </summary>
/// <remarks>
/// The type resolve context is optional and is not needed for entities loaded from assemblies:
/// This method can get the ID string for any type reference produced by the CecilLoader without
/// having to resolve the type reference.
/// </remarks>
public static string GetIDString(IEntity entity, ITypeResolveContext context = null)
public static string GetIDString(IEntity entity)
{
StringBuilder b = new StringBuilder();
switch (entity.EntityType) {
@ -75,13 +70,13 @@ namespace ICSharpCode.NRefactory.Documentation
var parameters = parameterizedMember.Parameters;
for (int i = 0; i < parameters.Count; i++) {
if (i > 0) b.Append(',');
AppendTypeName(b, parameters[i].Type, context);
AppendTypeName(b, parameters[i].Type);
}
b.Append(')');
}
if (member.EntityType == EntityType.Operator && (member.Name == "op_Implicit" || member.Name == "op_Explicit")) {
b.Append('~');
AppendTypeName(b, member.ReturnType, context);
AppendTypeName(b, member.ReturnType);
}
return b.ToString();
}
@ -162,123 +157,5 @@ namespace ICSharpCode.NRefactory.Documentation
}
}
}
static void AppendTypeName(StringBuilder b, ITypeReference type, ITypeResolveContext context)
{
IType resolvedType = type as IType;
if (resolvedType != null) {
AppendTypeName(b, resolvedType);
return;
}
KnownTypeReference knownType = type as KnownTypeReference;
if (knownType != null) {
if (!string.IsNullOrEmpty(knownType.Namespace)) {
b.Append(knownType.Namespace);
b.Append('.');
}
b.Append(knownType.Name);
return;
}
GetClassTypeReference gctr = type as GetClassTypeReference;
if (gctr != null) {
if (!string.IsNullOrEmpty(gctr.Namespace)) {
b.Append(gctr.Namespace);
b.Append('.');
}
b.Append(gctr.Name);
if (gctr.TypeParameterCount > 0) {
b.Append('`');
b.Append(gctr.TypeParameterCount);
}
return;
}
NestedTypeReference ntr = type as NestedTypeReference;
if (ntr != null) {
AppendTypeName(b, ntr.DeclaringTypeReference, context);
b.Append('.');
b.Append(ntr.Name);
if (ntr.AdditionalTypeParameterCount > 0) {
b.Append('`');
b.Append(ntr.AdditionalTypeParameterCount);
}
return;
}
ParameterizedTypeReference pt = type as ParameterizedTypeReference;
if (pt != null && IsGetClassTypeReference(pt.GenericType)) {
AppendParameterizedTypeName(b, pt.GenericType, pt.TypeArguments, context);
return;
}
ArrayTypeReference array = type as ArrayTypeReference;
if (array != null) {
AppendTypeName(b, array.ElementType, context);
b.Append('[');
if (array.Dimensions > 1) {
for (int i = 0; i < array.Dimensions; i++) {
if (i > 0) b.Append(',');
b.Append("0:");
}
}
b.Append(']');
return;
}
PointerTypeReference ptr = type as PointerTypeReference;
if (ptr != null) {
AppendTypeName(b, ptr.ElementType, context);
b.Append('*');
return;
}
ByReferenceTypeReference brtr = type as ByReferenceTypeReference;
if (brtr != null) {
AppendTypeName(b, brtr.ElementType, context);
b.Append('@');
return;
}
if (context == null)
b.Append('?');
else
AppendTypeName(b, type.Resolve(context));
}
static bool IsGetClassTypeReference(ITypeReference type)
{
NestedTypeReference ntr;
while ((ntr = type as NestedTypeReference) != null)
type = ntr.DeclaringTypeReference;
return type is GetClassTypeReference;
}
static int AppendParameterizedTypeName(StringBuilder b, ITypeReference type, IList<ITypeReference> typeArguments, ITypeResolveContext context)
{
GetClassTypeReference gctr = type as GetClassTypeReference;
if (gctr != null) {
if (!string.IsNullOrEmpty(gctr.Namespace)) {
b.Append(gctr.Namespace);
b.Append('.');
}
b.Append(gctr.Name);
if (gctr.TypeParameterCount > 0) {
b.Append('{');
for (int i = 0; i < gctr.TypeParameterCount && i < typeArguments.Count; i++) {
if (i > 0) b.Append(',');
AppendTypeName(b, typeArguments[i], context);
}
b.Append('}');
}
return gctr.TypeParameterCount;
} else {
NestedTypeReference ntr = (NestedTypeReference)type;
int outerTpc = AppendParameterizedTypeName(b, ntr.DeclaringTypeReference, typeArguments, context);
b.Append('.');
if (ntr.AdditionalTypeParameterCount > 0) {
b.Append('{');
for (int i = 0; i < ntr.AdditionalTypeParameterCount && i + outerTpc < typeArguments.Count; i++) {
if (i > 0) b.Append(',');
AppendTypeName(b, typeArguments[i + outerTpc], context);
}
b.Append('}');
}
return outerTpc + ntr.AdditionalTypeParameterCount;
}
}
}
}

Просмотреть файл

@ -268,68 +268,6 @@ namespace ICSharpCode.NRefactory.Documentation
}
#endregion
#region Save index / Restore from index
// TODO: consider removing this code, we're just using serialization instead
// FILE FORMAT FOR BINARY DOCUMENTATION
// long magic = 0x4244636f446c6d58 (identifies file type = 'XmlDocDB')
const long magic = 0x4244636f446c6d58;
// short version = 5 (file format version)
const short version = 5;
// string fileName (full name of .xml file)
// long fileDate (last change date of xml file in DateTime ticks)
// int testHashCode = magicTestString.GetHashCode() // (check if hash-code implementation is compatible)
// int entryCount (count of entries)
// int indexPointer (points to location where index starts in the file)
// {
// int hashcode
// int positionInFile (byte number where the docu string starts in the .xml file)
// }
const string magicTestString = "XmlDoc-Test-String";
/// <summary>
/// Saves the index into a binary file.
/// Use <see cref="LoadFromIndex"/> to load the saved file.
/// </summary>
public void SaveIndex(BinaryWriter w)
{
if (w == null)
throw new ArgumentNullException("w");
w.Write(magic);
w.Write(version);
w.Write(fileName);
w.Write(lastWriteDate.Ticks);
w.Write(magicTestString.GetHashCode());
w.Write(index.Length);
foreach (var entry in index) {
w.Write(entry.HashCode);
w.Write(entry.PositionInFile);
}
}
/// <summary>
/// Restores XmlDocumentationProvider from the index file (created by <see cref="SaveIndex"/>).
/// </summary>
public static XmlDocumentationProvider LoadFromIndex(BinaryReader r)
{
if (r.ReadInt64() != magic)
throw new InvalidDataException("File is not a stored XmlDoc index");
if (r.ReadInt16() != version)
throw new InvalidDataException("Index file was created by incompatible version");
string fileName = r.ReadString();
DateTime lastWriteDate = new DateTime(r.ReadInt64(), DateTimeKind.Utc);
if (r.ReadInt32() != magicTestString.GetHashCode())
throw new InvalidDataException("Index file was created by another hash code algorithm");
int indexLength = r.ReadInt32();
IndexEntry[] index = new IndexEntry[indexLength];
for (int i = 0; i < index.Length; i++) {
index[i] = new IndexEntry(r.ReadInt32(), r.ReadInt32());
}
return new XmlDocumentationProvider(fileName, lastWriteDate, index);
}
#endregion
#region GetDocumentation
/// <inheritdoc/>
public string GetDocumentation(IEntity entity)
@ -355,6 +293,7 @@ namespace ICSharpCode.NRefactory.Documentation
while (--m >= 0 && index[m].HashCode == hashcode);
// m is now 1 before the first item with the correct hash
XmlDocumentationCache cache = this.cache;
lock (cache) {
string val = cache.Get(key);
if (val == null) {

Просмотреть файл

@ -67,6 +67,7 @@
<Compile Include="Editor\ReadOnlyDocument.cs" />
<Compile Include="Editor\StringTextSource.cs" />
<Compile Include="Editor\TextChangeEventArgs.cs" />
<Compile Include="IAnnotatable.cs" />
<Compile Include="PatternMatching\BacktrackingInfo.cs" />
<Compile Include="PatternMatching\Choice.cs" />
<Compile Include="PatternMatching\AnyNode.cs" />
@ -85,6 +86,7 @@
<Compile Include="Semantics\ArrayCreateResolveResult.cs" />
<Compile Include="Semantics\ByReferenceResolveResult.cs" />
<Compile Include="Semantics\ConstantResolveResult.cs" />
<Compile Include="Semantics\ErrorResolveResult.cs" />
<Compile Include="Semantics\InvocationResolveResult.cs" />
<Compile Include="Semantics\LocalResolveResult.cs" />
<Compile Include="Semantics\MemberResolveResult.cs" />
@ -104,40 +106,44 @@
<Compile Include="TypeSystem\ExtensionMethods.cs" />
<Compile Include="TypeSystem\IAccessor.cs" />
<Compile Include="TypeSystem\IAmbience.cs" />
<Compile Include="TypeSystem\IAssembly.cs" />
<Compile Include="TypeSystem\IAttribute.cs" />
<Compile Include="TypeSystem\ICompilation.cs" />
<Compile Include="TypeSystem\IConstantValue.cs" />
<Compile Include="TypeSystem\IDocumentationProvider.cs" />
<Compile Include="TypeSystem\IEntity.cs" />
<Compile Include="TypeSystem\IEvent.cs" />
<Compile Include="TypeSystem\IExplicitInterfaceImplementation.cs" />
<Compile Include="TypeSystem\IField.cs" />
<Compile Include="TypeSystem\IFreezable.cs" />
<Compile Include="TypeSystem\IInterningProvider.cs" />
<Compile Include="TypeSystem\IMember.cs" />
<Compile Include="TypeSystem\IMethod.cs" />
<Compile Include="TypeSystem\Implementation\AbstractFreezable.cs" />
<Compile Include="TypeSystem\Implementation\AbstractMember.cs" />
<Compile Include="TypeSystem\Implementation\AbstractUnresolvedEntity.cs" />
<Compile Include="TypeSystem\Implementation\AbstractUnresolvedMember.cs" />
<Compile Include="TypeSystem\Implementation\AbstractType.cs" />
<Compile Include="TypeSystem\Implementation\AbstractTypeParameter.cs" />
<Compile Include="TypeSystem\Implementation\AbstractResolvedTypeParameter.cs" />
<Compile Include="TypeSystem\Implementation\BaseTypeCollector.cs" />
<Compile Include="TypeSystem\Implementation\CompoundTypeDefinition.cs" />
<Compile Include="TypeSystem\Implementation\DefaultAccessor.cs" />
<Compile Include="TypeSystem\Implementation\DefaultAttribute.cs" />
<Compile Include="TypeSystem\Implementation\DefaultEvent.cs" />
<Compile Include="TypeSystem\Implementation\DefaultExplicitInterfaceImplementation.cs" />
<Compile Include="TypeSystem\Implementation\DefaultField.cs" />
<Compile Include="TypeSystem\Implementation\DefaultMethod.cs" />
<Compile Include="TypeSystem\Implementation\DefaultParameter.cs" />
<Compile Include="TypeSystem\Implementation\DefaultProperty.cs" />
<Compile Include="TypeSystem\Implementation\DefaultTypeParameter.cs" />
<Compile Include="TypeSystem\Implementation\DefaultTypeParameterConstraints.cs" />
<Compile Include="TypeSystem\Implementation\DefaultResolvedTypeParameter.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedAccessor.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedAttribute.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedEvent.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedField.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedMethod.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedParameter.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedProperty.cs" />
<Compile Include="TypeSystem\Implementation\DefaultResolvedAccessor.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedTypeParameter.cs" />
<Compile Include="TypeSystem\Implementation\DefaultUnresolvedTypeDefinition.cs" />
<Compile Include="TypeSystem\Implementation\GetClassTypeReference.cs" />
<Compile Include="TypeSystem\Implementation\CompositeTypeResolveContext.cs" />
<Compile Include="TypeSystem\Implementation\GetMembersHelper.cs" />
<Compile Include="TypeSystem\Implementation\MinimalResolveContext.cs" />
<Compile Include="TypeSystem\Implementation\DefaultParameter.cs" />
<Compile Include="TypeSystem\Implementation\SimpleCompilation.cs" />
<Compile Include="TypeSystem\Implementation\TypeParameterReference.cs" />
<Compile Include="TypeSystem\Implementation\TypeParameterSubstitution.cs" />
<Compile Include="TypeSystem\Implementation\NestedTypeReference.cs" />
<Compile Include="TypeSystem\Implementation\ProxyTypeResolveContext.cs" />
<Compile Include="TypeSystem\Implementation\DefaultTypeDefinition.cs" />
<Compile Include="TypeSystem\Implementation\SimpleConstantValue.cs" />
<Compile Include="TypeSystem\Implementation\SimpleInterningProvider.cs" />
@ -147,12 +153,9 @@
<Compile Include="TypeSystem\Implementation\SpecializedMember.cs" />
<Compile Include="TypeSystem\Implementation\SpecializedMethod.cs" />
<Compile Include="TypeSystem\Implementation\SpecializedProperty.cs" />
<Compile Include="TypeSystem\Implementation\SubstitutionTypeReference.cs" />
<Compile Include="TypeSystem\Implementation\TypeParameterWithInheritedConstraints.cs" />
<Compile Include="TypeSystem\Implementation\TypeStorage.cs" />
<Compile Include="TypeSystem\Implementation\TypeWithElementType.cs" />
<Compile Include="TypeSystem\Implementation\VoidTypeDefinition.cs" />
<Compile Include="TypeSystem\INamedElement.cs" />
<Compile Include="TypeSystem\INamespace.cs" />
<Compile Include="TypeSystem\InheritanceHelper.cs" />
<Compile Include="TypeSystem\IntersectionType.cs" />
<Compile Include="TypeSystem\IParameter.cs" />
@ -161,12 +164,10 @@
<Compile Include="TypeSystem\IProjectContent.cs" />
<Compile Include="TypeSystem\IProperty.cs" />
<Compile Include="TypeSystem\ISupportsInterning.cs" />
<Compile Include="TypeSystem\ISynchronizedTypeResolveContext.cs" />
<Compile Include="TypeSystem\IType.cs" />
<Compile Include="TypeSystem\ITypeDefinition.cs" />
<Compile Include="TypeSystem\ITypeParameter.cs" />
<Compile Include="TypeSystem\ITypeReference.cs" />
<Compile Include="TypeSystem\ITypeResolveContext.cs" />
<Compile Include="TypeSystem\KnownTypeReference.cs" />
<Compile Include="TypeSystem\NullableType.cs" />
<Compile Include="TypeSystem\ParameterizedType.cs" />
@ -187,18 +188,19 @@
<Compile Include="Utils\ExtensionMethods.cs" />
<Compile Include="Utils\FastSerializer.cs" />
<Compile Include="Utils\GraphVizGraph.cs" />
<Compile Include="Utils\ImmutableStack.cs" />
<Compile Include="Utils\LazyInit.cs" />
<Compile Include="Utils\Platform.cs" />
<Compile Include="Utils\ProjectedList.cs" />
<Compile Include="Utils\ReferenceComparer.cs" />
<Compile Include="Utils\TreeTraversal.cs" />
<Compile Include="TypeSystem\Error.cs" />
<Compile Include="TypeSystem\IAnnotatable.cs" />
<Compile Include="Completion\ICompletionData.cs" />
<Compile Include="Completion\DisplayFlags.cs" />
<Compile Include="Completion\IEntityCompletionData.cs" />
<Compile Include="Completion\CompletionCategory.cs" />
<Compile Include="Completion\IParameterDataProvider.cs" />
<Compile Include="Completion\IVariableCompletionData.cs" />
<Compile Include="Semantics\UnknownTypeResolveResult.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Completion\" />

Просмотреть файл

@ -37,7 +37,7 @@ namespace ICSharpCode.NRefactory.Semantics
public class AmbiguousMemberResolveResult : MemberResolveResult
{
public AmbiguousMemberResolveResult(ResolveResult targetResult, IMember member, IType returnType) : base(targetResult, member, returnType)
public AmbiguousMemberResolveResult(ResolveResult targetResult, IMember member) : base(targetResult, member)
{
}

Просмотреть файл

@ -17,10 +17,9 @@
// DEALINGS IN THE SOFTWARE.
using System;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.CSharp.Resolver
namespace ICSharpCode.NRefactory.Semantics
{
/// <summary>
/// Represents a resolve error.
@ -30,7 +29,7 @@ namespace ICSharpCode.NRefactory.CSharp.Resolver
/// <summary>
/// Gets an ErrorResolveResult instance with Type = SharedTypes.UnknownType.
/// </summary>
public static readonly ErrorResolveResult UnknownError = new ErrorResolveResult(SharedTypes.UnknownType);
public static readonly ErrorResolveResult UnknownError = new ErrorResolveResult(SpecialType.UnknownType);
public ErrorResolveResult(IType type) : base(type)
{

Просмотреть файл

@ -35,10 +35,8 @@ namespace ICSharpCode.NRefactory.Semantics
/// </summary>
public readonly IList<ResolveResult> Arguments;
public InvocationResolveResult(
ResolveResult targetResult, IParameterizedMember member, IType returnType,
IList<ResolveResult> arguments)
: base(targetResult, member, returnType)
public InvocationResolveResult(ResolveResult targetResult, IParameterizedMember member, IList<ResolveResult> arguments)
: base(targetResult, member)
{
this.Arguments = arguments ?? EmptyList<ResolveResult>.Instance;
}

Просмотреть файл

@ -27,21 +27,20 @@ namespace ICSharpCode.NRefactory.Semantics
public class LocalResolveResult : ResolveResult
{
readonly IVariable variable;
readonly object constantValue;
public LocalResolveResult(IVariable variable, IType type, object constantValue = null)
: base(UnpackTypeIfByRefParameter(type, variable))
public LocalResolveResult(IVariable variable)
: base(UnpackTypeIfByRefParameter(variable))
{
this.variable = variable;
}
static IType UnpackTypeIfByRefParameter(IVariable variable)
{
if (variable == null)
throw new ArgumentNullException("variable");
this.variable = variable;
this.constantValue = constantValue;
}
static IType UnpackTypeIfByRefParameter(IType type, IVariable v)
{
IType type = variable.Type;
if (type.Kind == TypeKind.ByReference) {
IParameter p = v as IParameter;
IParameter p = variable as IParameter;
if (p != null && (p.IsRef || p.IsOut))
return ((ByReferenceType)type).ElementType;
}
@ -61,7 +60,7 @@ namespace ICSharpCode.NRefactory.Semantics
}
public override object ConstantValue {
get { return constantValue; }
get { return variable.ConstantValue; }
}
public override string ToString()

Просмотреть файл

@ -33,26 +33,8 @@ namespace ICSharpCode.NRefactory.Semantics
readonly object constantValue;
readonly ResolveResult targetResult;
public MemberResolveResult(ResolveResult targetResult, IMember member, IType returnType) : base(returnType)
{
if (member == null)
throw new ArgumentNullException("member");
this.targetResult = targetResult;
this.member = member;
}
public MemberResolveResult(ResolveResult targetResult, IMember member, IType returnType, object constantValue) : base(returnType)
{
if (member == null)
throw new ArgumentNullException("member");
this.targetResult = targetResult;
this.member = member;
this.isConstant = true;
this.constantValue = constantValue;
}
public MemberResolveResult(ResolveResult targetResult, IMember member, ITypeResolveContext context)
: base(member.EntityType == EntityType.Constructor ? member.DeclaringType : member.ReturnType.Resolve(context))
public MemberResolveResult(ResolveResult targetResult, IMember member)
: base(member.EntityType == EntityType.Constructor ? member.DeclaringType : member.ReturnType)
{
this.targetResult = targetResult;
this.member = member;
@ -60,7 +42,7 @@ namespace ICSharpCode.NRefactory.Semantics
if (field != null) {
isConstant = field.IsConst;
if (isConstant)
constantValue = field.ConstantValue.Resolve(context).ConstantValue;
constantValue = field.ConstantValue;
}
}

Просмотреть файл

@ -26,20 +26,24 @@ namespace ICSharpCode.NRefactory.Semantics
/// </summary>
public class NamespaceResolveResult : ResolveResult
{
readonly string namespaceName;
readonly INamespace ns;
public NamespaceResolveResult(string namespaceName) : base(SharedTypes.UnknownType)
public NamespaceResolveResult(INamespace ns) : base(SpecialType.UnknownType)
{
this.namespaceName = namespaceName;
this.ns = ns;
}
public INamespace Namespace {
get { return ns; }
}
public string NamespaceName {
get { return namespaceName; }
get { return ns.FullName; }
}
public override string ToString()
{
return string.Format("[{0} {1}]", GetType().Name, namespaceName);
return string.Format("[{0} {1}]", GetType().Name, ns);
}
}
}

Просмотреть файл

@ -31,6 +31,10 @@ namespace ICSharpCode.NRefactory.Semantics
{
}
public override bool IsError {
get { return this.Type.Kind == TypeKind.Unknown; }
}
public override DomRegion GetDefinitionRegion()
{
ITypeDefinition def = this.Type.GetDefinition();

Просмотреть файл

@ -33,7 +33,8 @@ namespace ICSharpCode.NRefactory.Semantics
readonly string memberName;
readonly ReadOnlyCollection<IType> typeArguments;
public UnknownMemberResolveResult(IType targetType, string memberName, IEnumerable<IType> typeArguments) : base(SharedTypes.UnknownType)
public UnknownMemberResolveResult(IType targetType, string memberName, IEnumerable<IType> typeArguments)
: base(SpecialType.UnknownType)
{
if (targetType == null)
throw new ArgumentNullException("targetType");
@ -74,7 +75,7 @@ namespace ICSharpCode.NRefactory.Semantics
{
readonly ReadOnlyCollection<IParameter> parameters;
public UnknownMethodResolveResult(IType targetType, string methodName, IEnumerable<IType> typeArguments, IEnumerable<IParameter> parameters)
public UnknownMethodResolveResult(IType targetType, string methodName, IEnumerable<IType> typeArguments, IEnumerable<IParameter> parameters)
: base(targetType, methodName, typeArguments)
{
this.parameters = new ReadOnlyCollection<IParameter>(parameters.ToArray());
@ -91,17 +92,23 @@ namespace ICSharpCode.NRefactory.Semantics
public class UnknownIdentifierResolveResult : ResolveResult
{
readonly string identifier;
readonly int typeArgumentCount;
public UnknownIdentifierResolveResult(string identifier)
: base(SharedTypes.UnknownType)
public UnknownIdentifierResolveResult(string identifier, int typeArgumentCount = 0)
: base(SpecialType.UnknownType)
{
this.identifier = identifier;
this.typeArgumentCount = typeArgumentCount;
}
public string Identifier {
get { return identifier; }
}
public int TypeArgumentCount {
get { return typeArgumentCount; }
}
public override bool IsError {
get { return true; }
}

Просмотреть файл

@ -1,67 +0,0 @@
//
// UnknownTypeResolveResult.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc. (http://xamarin.com)
//
// 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.Collections.ObjectModel;
using System.Linq;
using ICSharpCode.NRefactory.TypeSystem;
namespace ICSharpCode.NRefactory.Semantics
{
/// <summary>
/// Represents an unknown type with type parameters.
/// </summary>
public class UnknownTypeResolveResult : ResolveResult
{
readonly string identifier;
readonly int typeParameterCount;
public UnknownTypeResolveResult(string identifier, int typeParameterCount)
: base(SharedTypes.UnknownType)
{
this.identifier = identifier;
this.typeParameterCount = typeParameterCount;
}
public string Identifier {
get { return identifier; }
}
public int TypeParameterCount {
get { return typeParameterCount; }
}
public override bool IsError {
get { return true; }
}
public override string ToString()
{
return string.Format("[{0} {1}~{2}]", GetType().Name, identifier, typeParameterCount);
}
}
}

Просмотреть файл

@ -58,4 +58,60 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <remarks>C# does not support this accessibility.</remarks>
ProtectedAndInternal,
}
public interface IHasAccessibility
{
/// <summary>
/// Gets the accessibility of this entity.
/// </summary>
Accessibility Accessibility { get; }
/// <summary>
/// Gets a value indicating whether this instance is private.
/// </summary>
/// <value>
/// <c>true</c> if this instance is private; otherwise, <c>false</c>.
/// </value>
bool IsPrivate { get; }
/// <summary>
/// Gets a value indicating whether this instance is public.
/// </summary>
/// <value>
/// <c>true</c> if this instance is public; otherwise, <c>false</c>.
/// </value>
bool IsPublic { get; }
/// <summary>
/// Gets a value indicating whether this instance is protected.
/// </summary>
/// <value>
/// <c>true</c> if this instance is protected; otherwise, <c>false</c>.
/// </value>
bool IsProtected { get; }
/// <summary>
/// Gets a value indicating whether this instance is internal.
/// </summary>
/// <value>
/// <c>true</c> if this instance is internal; otherwise, <c>false</c>.
/// </value>
bool IsInternal { get; }
/// <summary>
/// Gets a value indicating whether this instance is protected or internal.
/// </summary>
/// <value>
/// <c>true</c> if this instance is protected or internal; otherwise, <c>false</c>.
/// </value>
bool IsProtectedOrInternal { get; }
/// <summary>
/// Gets a value indicating whether this instance is protected and internal.
/// </summary>
/// <value>
/// <c>true</c> if this instance is protected and internal; otherwise, <c>false</c>.
/// </value>
bool IsProtectedAndInternal { get; }
}
}

Просмотреть файл

@ -25,15 +25,18 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary>
/// Represents an array type.
/// </summary>
[Serializable]
public sealed class ArrayType : TypeWithElementType, ISupportsInterning
public sealed class ArrayType : TypeWithElementType
{
readonly int dimensions;
readonly ICompilation compilation;
public ArrayType(IType elementType, int dimensions = 1) : base(elementType)
public ArrayType(ICompilation compilation, IType elementType, int dimensions = 1) : base(elementType)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
if (dimensions <= 0)
throw new ArgumentOutOfRangeException("dimensions", dimensions, "dimensions must be positive");
this.compilation = compilation;
this.dimensions = dimensions;
}
@ -51,9 +54,8 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
}
public override bool? IsReferenceType(ITypeResolveContext context)
{
return true;
public override bool? IsReferenceType {
get { return true; }
}
public override int GetHashCode()
@ -67,40 +69,44 @@ namespace ICSharpCode.NRefactory.TypeSystem
return a != null && elementType.Equals(a.elementType) && a.dimensions == dimensions;
}
static readonly GetClassTypeReference systemArray = new GetClassTypeReference("System", "Array", 0);
static readonly GetClassTypeReference listInterface = new GetClassTypeReference("System.Collections.Generic", "IList", 1);
public override IEnumerable<IType> GetBaseTypes(ITypeResolveContext context)
public override ITypeReference ToTypeReference()
{
List<IType> baseTypes = new List<IType>();
IType t = systemArray.Resolve(context);
if (t != SharedTypes.UnknownType)
baseTypes.Add(t);
if (dimensions == 1) { // single-dimensional arrays implement IList<T>
ITypeDefinition def = listInterface.Resolve(context) as ITypeDefinition;
if (def != null)
baseTypes.Add(new ParameterizedType(def, new[] { elementType }));
return new ArrayTypeReference(elementType.ToTypeReference(), dimensions);
}
public override IEnumerable<IType> DirectBaseTypes {
get {
List<IType> baseTypes = new List<IType>();
IType t = compilation.FindType(KnownTypeCode.Array);
if (t.Kind != TypeKind.Unknown)
baseTypes.Add(t);
if (dimensions == 1) { // single-dimensional arrays implement IList<T>
ITypeDefinition def = compilation.FindType(KnownTypeCode.IListOfT) as ITypeDefinition;
if (def != null)
baseTypes.Add(new ParameterizedType(def, new[] { elementType }));
}
return baseTypes;
}
return baseTypes;
}
public override IEnumerable<IMethod> GetMethods(ITypeResolveContext context, Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
public override IEnumerable<IMethod> GetMethods(Predicate<IMethod> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
return systemArray.Resolve(context).GetMethods(context, filter, options);
return compilation.FindType(KnownTypeCode.Array).GetMethods(filter, options);
}
static readonly DefaultParameter indexerParam = new DefaultParameter(KnownTypeReference.Int32, string.Empty);
//static readonly DefaultUnresolvedParameter indexerParam = new DefaultUnresolvedParameter(KnownTypeReference.Int32, string.Empty);
public override IEnumerable<IProperty> GetProperties(ITypeResolveContext context, Predicate<IProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
public override IEnumerable<IProperty> GetProperties(Predicate<IProperty> filter = null, GetMemberOptions options = GetMemberOptions.None)
{
ITypeDefinition arrayDef = systemArray.Resolve(context) as ITypeDefinition;
ITypeDefinition arrayDef = compilation.FindType(KnownTypeCode.Array) as ITypeDefinition;
if (arrayDef != null) {
if ((options & GetMemberOptions.IgnoreInheritedMembers) == 0) {
foreach (IProperty p in arrayDef.GetProperties(context, filter, options)) {
foreach (IProperty p in arrayDef.GetProperties(filter, options)) {
yield return p;
}
}
DefaultProperty indexer = new DefaultProperty(arrayDef, "Items") {
throw new NotImplementedException();
/*DefaultProperty indexer = new DefaultProperty(arrayDef, "Items") {
EntityType = EntityType.Indexer,
ReturnType = elementType,
Accessibility = Accessibility.Public,
@ -114,11 +120,11 @@ namespace ICSharpCode.NRefactory.TypeSystem
indexer.Freeze();
if (filter == null || filter(indexer)) {
yield return indexer;
}
}*/
}
}
// Events, Fields: System.Array doesn't have any; so we can use the AbstractType default implementation
// NestedTypes, Events, Fields: System.Array doesn't have any; so we can use the AbstractType default implementation
// that simply returns an empty list
public override IType AcceptVisitor(TypeVisitor visitor)
@ -132,23 +138,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
if (e == elementType)
return this;
else
return new ArrayType(e, dimensions);
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
elementType = provider.Intern(elementType);
}
int ISupportsInterning.GetHashCodeForInterning()
{
return elementType.GetHashCode() ^ dimensions;
}
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
ArrayType o = other as ArrayType;
return o != null && elementType == o.elementType && dimensions == o.dimensions;
return new ArrayType(compilation, e, dimensions);
}
}
@ -178,7 +168,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
public IType Resolve(ITypeResolveContext context)
{
return new ArrayType(elementType.Resolve(context), dimensions);
return new ArrayType(context.Compilation, elementType.Resolve(context), dimensions);
}
public override string ToString()
@ -186,14 +176,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
return elementType.ToString() + "[" + new string(',', dimensions - 1) + "]";
}
public static ITypeReference Create(ITypeReference elementType, int dimensions)
{
if (elementType is IType)
return new ArrayType((IType)elementType, dimensions);
else
return new ArrayTypeReference(elementType, dimensions);
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
elementType = provider.Intern(elementType);

Просмотреть файл

@ -21,7 +21,6 @@ using ICSharpCode.NRefactory.TypeSystem.Implementation;
namespace ICSharpCode.NRefactory.TypeSystem
{
[Serializable]
public sealed class ByReferenceType : TypeWithElementType, ISupportsInterning
{
public ByReferenceType(IType elementType) : base(elementType)
@ -38,9 +37,8 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
}
public override bool? IsReferenceType(ITypeResolveContext context)
{
return null;
public override bool? IsReferenceType {
get { return null; }
}
public override int GetHashCode()
@ -68,6 +66,11 @@ namespace ICSharpCode.NRefactory.TypeSystem
return new ByReferenceType(e);
}
public override ITypeReference ToTypeReference()
{
return new ByReferenceTypeReference(elementType.ToTypeReference());
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
elementType = provider.Intern(elementType);
@ -111,14 +114,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
return elementType.ToString() + "&";
}
public static ITypeReference Create(ITypeReference elementType)
{
if (elementType is IType)
return new ByReferenceType((IType)elementType);
else
return new ByReferenceTypeReference(elementType);
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
elementType = provider.Intern(elementType);

Просмотреть файл

@ -25,7 +25,9 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
using Mono.Cecil;
namespace ICSharpCode.NRefactory.TypeSystem
@ -38,14 +40,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
public class CecilLoader
{
#region Options
/// <summary>
/// Gets/Sets the early bind context.
/// This context is used to pre-resolve type references - setting this property will cause the CecilLoader
/// to directly reference the resolved types, and create links (<see cref="GetClassTypeReference"/>) to types
/// that could not be resolved.
/// </summary>
public ITypeResolveContext EarlyBindContext { get; set; }
/// <summary>
/// Specifies whether to include internal members. The default is false.
/// </summary>
@ -96,58 +90,51 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// </summary>
/// <returns>IProjectContent that represents the assembly</returns>
[CLSCompliant(false)]
public IProjectContent LoadAssembly(AssemblyDefinition assemblyDefinition)
public IUnresolvedAssembly LoadAssembly(AssemblyDefinition assemblyDefinition)
{
if (assemblyDefinition == null)
throw new ArgumentNullException("assemblyDefinition");
ITypeResolveContext oldEarlyBindContext = this.EarlyBindContext;
try {
// Read assembly and module attributes
IList<IAttribute> assemblyAttributes = new List<IAttribute>();
IList<IAttribute> moduleAttributes = new List<IAttribute>();
AddAttributes(assemblyDefinition, assemblyAttributes);
AddAttributes(assemblyDefinition.MainModule, moduleAttributes);
if (this.InterningProvider != null) {
assemblyAttributes = this.InterningProvider.InternList(assemblyAttributes);
moduleAttributes = this.InterningProvider.InternList(moduleAttributes);
} else {
assemblyAttributes = new ReadOnlyCollection<IAttribute>(assemblyAttributes);
moduleAttributes = new ReadOnlyCollection<IAttribute>(moduleAttributes);
}
TypeStorage typeStorage = new TypeStorage();
CecilProjectContent pc = new CecilProjectContent(typeStorage, assemblyDefinition.Name.FullName, assemblyAttributes, moduleAttributes, this.DocumentationProvider);
this.EarlyBindContext = CompositeTypeResolveContext.Combine(pc, this.EarlyBindContext);
List<CecilTypeDefinition> types = new List<CecilTypeDefinition>();
foreach (ModuleDefinition module in assemblyDefinition.Modules) {
foreach (TypeDefinition td in module.Types) {
this.CancellationToken.ThrowIfCancellationRequested();
if (this.IncludeInternalMembers || (td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public) {
string name = td.FullName;
if (name.Length == 0 || name[0] == '<')
continue;
if (name == "System.Void") {
var c = new VoidTypeDefinition(pc);
AddAttributes(td, c);
typeStorage.UpdateType(c);
} else {
CecilTypeDefinition c = new CecilTypeDefinition(pc, td);
types.Add(c);
typeStorage.UpdateType(c);
}
}
// Read assembly and module attributes
IList<IUnresolvedAttribute> assemblyAttributes = new List<IUnresolvedAttribute>();
IList<IUnresolvedAttribute> moduleAttributes = new List<IUnresolvedAttribute>();
AddAttributes(assemblyDefinition, assemblyAttributes);
AddAttributes(assemblyDefinition.MainModule, moduleAttributes);
if (this.InterningProvider != null) {
assemblyAttributes = this.InterningProvider.InternList(assemblyAttributes);
moduleAttributes = this.InterningProvider.InternList(moduleAttributes);
}
assemblyAttributes = FreezableHelper.FreezeListAndElements(assemblyAttributes);
moduleAttributes = FreezableHelper.FreezeListAndElements(moduleAttributes);
/*
TypeStorage typeStorage = new TypeStorage();
CecilProjectContent pc = new CecilProjectContent(typeStorage, assemblyDefinition.Name.FullName, assemblyAttributes, moduleAttributes, this.DocumentationProvider);
this.EarlyBindContext = CompositeTypeResolveContext.Combine(pc, this.EarlyBindContext);
List<CecilTypeDefinition> types = new List<CecilTypeDefinition>();
foreach (ModuleDefinition module in assemblyDefinition.Modules) {
foreach (TypeDefinition td in module.Types) {
this.CancellationToken.ThrowIfCancellationRequested();
if (this.IncludeInternalMembers || (td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public) {
string name = td.FullName;
if (name.Length == 0 || name[0] == '<')
continue;
CecilTypeDefinition c = new CecilTypeDefinition(td);
types.Add(c);
typeStorage.UpdateType(c);
}
}
foreach (CecilTypeDefinition c in types) {
c.Init(this);
}
if (HasCecilReferences)
typeSystemTranslationTable[pc] = assemblyDefinition;
return pc;
} finally {
this.EarlyBindContext = oldEarlyBindContext;
}
foreach (CecilTypeDefinition c in types) {
c.Init(this);
}
if (HasCecilReferences)
typeSystemTranslationTable[pc] = assemblyDefinition;
return pc;*/
throw new NotImplementedException();
}
/// <summary>
@ -157,21 +144,21 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <param name="projectContent">The project content used as parent for the new type.</param>
/// <returns>ITypeDefinition representing the Cecil type.</returns>
[CLSCompliant(false)]
public ITypeDefinition LoadType(TypeDefinition typeDefinition, IProjectContent projectContent)
public ITypeDefinition LoadType(TypeDefinition typeDefinition)
{
if (typeDefinition == null)
throw new ArgumentNullException("typeDefinition");
if (projectContent == null)
throw new ArgumentNullException("projectContent");
var c = new CecilTypeDefinition(projectContent, typeDefinition);
throw new NotImplementedException();
/*var c = new CecilTypeDefinition(typeDefinition);
c.Init(this);
return c;
return c;*/
}
#endregion
#region IProjectContent implementation
#region IUnresolvedAssembly implementation
/*
[Serializable]
sealed class CecilProjectContent : ProxyTypeResolveContext, IProjectContent, ISynchronizedTypeResolveContext, IDocumentationProvider
sealed class CecilProjectContent : IUnresolvedAssembly, IDocumentationProvider
{
readonly string assemblyName;
readonly IList<IAttribute> assemblyAttributes;
@ -207,17 +194,6 @@ namespace ICSharpCode.NRefactory.TypeSystem
return "[CecilProjectContent " + assemblyName + "]";
}
public override ISynchronizedTypeResolveContext Synchronize()
{
// CecilProjectContent is immutable, so we don't need to synchronize
return this;
}
void IDisposable.Dispose()
{
// Disposing the synchronization context has no effect
}
IParsedFile IProjectContent.GetFile(string fileName)
{
return null;
@ -229,7 +205,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
}
void IProjectContent.UpdateProjectContent(IParsedFile oldFile, IParsedFile newFile)
IProjectContent IProjectContent.UpdateProjectContent(IParsedFile oldFile, IParsedFile newFile)
{
throw new NotSupportedException();
}
@ -269,10 +245,11 @@ namespace ICSharpCode.NRefactory.TypeSystem
{
}
}
*/
#endregion
#region Load Assembly From Disk
public IProjectContent LoadAssemblyFile(string fileName)
public IUnresolvedAssembly LoadAssemblyFile(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
@ -320,76 +297,54 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <param name="entity">The entity that owns this type reference.
/// Used for generic type references.</param>
[CLSCompliant(false)]
public ITypeReference ReadTypeReference(
TypeReference type,
ICustomAttributeProvider typeAttributes = null,
IEntity entity = null)
public ITypeReference ReadTypeReference(TypeReference type, ICustomAttributeProvider typeAttributes = null)
{
int typeIndex = 0;
return CreateType(type, entity, typeAttributes, ref typeIndex);
return CreateType(type, typeAttributes, ref typeIndex);
}
ITypeReference CreateType(
TypeReference type,
IEntity entity,
ICustomAttributeProvider typeAttributes, ref int typeIndex)
ITypeReference CreateType(TypeReference type, ICustomAttributeProvider typeAttributes, ref int typeIndex)
{
while (type is OptionalModifierType || type is RequiredModifierType) {
type = ((TypeSpecification)type).ElementType;
}
if (type == null) {
return SharedTypes.UnknownType;
return SpecialType.UnknownType;
}
if (type is Mono.Cecil.ByReferenceType) {
typeIndex++;
return ByReferenceTypeReference.Create(
return new ByReferenceTypeReference(
CreateType(
(type as Mono.Cecil.ByReferenceType).ElementType,
entity, typeAttributes, ref typeIndex));
typeAttributes, ref typeIndex));
} else if (type is Mono.Cecil.PointerType) {
typeIndex++;
return PointerTypeReference.Create(
return new PointerTypeReference(
CreateType(
(type as Mono.Cecil.PointerType).ElementType,
entity, typeAttributes, ref typeIndex));
typeAttributes, ref typeIndex));
} else if (type is Mono.Cecil.ArrayType) {
typeIndex++;
return ArrayTypeReference.Create(
return new ArrayTypeReference(
CreateType(
(type as Mono.Cecil.ArrayType).ElementType,
entity, typeAttributes, ref typeIndex),
typeAttributes, ref typeIndex),
(type as Mono.Cecil.ArrayType).Rank);
} else if (type is GenericInstanceType) {
GenericInstanceType gType = (GenericInstanceType)type;
ITypeReference baseType = CreateType(gType.ElementType, entity, typeAttributes, ref typeIndex);
ITypeReference baseType = CreateType(gType.ElementType, typeAttributes, ref typeIndex);
ITypeReference[] para = new ITypeReference[gType.GenericArguments.Count];
for (int i = 0; i < para.Length; ++i) {
typeIndex++;
para[i] = CreateType(gType.GenericArguments[i], entity, typeAttributes, ref typeIndex);
para[i] = CreateType(gType.GenericArguments[i], typeAttributes, ref typeIndex);
}
return ParameterizedTypeReference.Create(baseType, para);
return new ParameterizedTypeReference(baseType, para);
} else if (type is GenericParameter) {
GenericParameter typeGP = type as GenericParameter;
if (typeGP.Owner is MethodDefinition) {
IMethod method = entity as IMethod;
if (method != null) {
if (typeGP.Position < method.TypeParameters.Count) {
return method.TypeParameters[typeGP.Position];
}
}
return SharedTypes.UnknownType;
} else {
ITypeDefinition c = (entity as ITypeDefinition) ?? (entity is IMember ? ((IMember)entity).DeclaringTypeDefinition : null);
if (c != null && typeGP.Position < c.TypeParameters.Count) {
if (c.TypeParameters[typeGP.Position].Name == type.Name) {
return c.TypeParameters[typeGP.Position];
}
}
return SharedTypes.UnknownType;
}
GenericParameter typeGP = (GenericParameter)type;
return new TypeParameterReference(typeGP.Owner is MethodDefinition ? EntityType.Method : EntityType.TypeDefinition, typeGP.Position);
} else if (type.IsNested) {
ITypeReference typeRef = CreateType(type.DeclaringType, entity, typeAttributes, ref typeIndex);
ITypeReference typeRef = CreateType(type.DeclaringType, typeAttributes, ref typeIndex);
int partTypeParameterCount;
string namepart = ReflectionHelper.SplitTypeParameterCountFromReflectionName(type.Name, out partTypeParameterCount);
return new NestedTypeReference(typeRef, namepart, partTypeParameterCount);
@ -400,17 +355,18 @@ namespace ICSharpCode.NRefactory.TypeSystem
throw new InvalidOperationException("type.Name returned null. Type: " + type.ToString());
if (name == "Object" && ns == "System" && HasDynamicAttribute(typeAttributes, typeIndex)) {
return SharedTypes.Dynamic;
return SpecialType.Dynamic;
} else {
int typeParameterCount;
name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(name, out typeParameterCount);
var earlyBindContext = this.EarlyBindContext;
/*var earlyBindContext = this.EarlyBindContext;
if (earlyBindContext != null) {
IType c = earlyBindContext.GetTypeDefinition(ns, name, typeParameterCount, StringComparer.Ordinal);
if (c != null)
return c;
}
return new GetClassTypeReference(ns, name, typeParameterCount);
return new GetClassTypeReference(ns, name, typeParameterCount);*/
throw new NotImplementedException();
}
}
}
@ -439,7 +395,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
static readonly ITypeReference typeForwardedToAttributeTypeRef = typeof(TypeForwardedToAttribute).ToTypeReference();
static readonly ITypeReference assemblyVersionAttributeTypeRef = typeof(System.Reflection.AssemblyVersionAttribute).ToTypeReference();
void AddAttributes(AssemblyDefinition assembly, IList<IAttribute> outputList)
void AddAttributes(AssemblyDefinition assembly, IList<IUnresolvedAttribute> outputList)
{
if (assembly.HasCustomAttributes) {
AddCustomAttributes(assembly.CustomAttributes, outputList);
@ -450,7 +406,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
// AssemblyVersionAttribute
if (assembly.Name.Version != null) {
var assemblyVersion = new DefaultAttribute(assemblyVersionAttributeTypeRef, new[] { KnownTypeReference.String });
var assemblyVersion = new DefaultUnresolvedAttribute(assemblyVersionAttributeTypeRef, new[] { KnownTypeReference.String });
assemblyVersion.PositionalArguments.Add(new SimpleConstantValue(KnownTypeReference.String, assembly.Name.Version.ToString()));
outputList.Add(assemblyVersion);
}
@ -460,7 +416,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
if (type.IsForwarder) {
int typeParameterCount;
string name = ReflectionHelper.SplitTypeParameterCountFromReflectionName(type.Name, out typeParameterCount);
var typeForwardedTo = new DefaultAttribute(typeForwardedToAttributeTypeRef, new[] { KnownTypeReference.Type });
var typeForwardedTo = new DefaultUnresolvedAttribute(typeForwardedToAttributeTypeRef, new[] { KnownTypeReference.Type });
var typeRef = new GetClassTypeReference(type.Namespace, name, typeParameterCount);
typeForwardedTo.PositionalArguments.Add(new SimpleConstantValue(KnownTypeReference.Type, typeRef));
outputList.Add(typeForwardedTo);
@ -470,7 +426,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion
#region Module Attributes
void AddAttributes(ModuleDefinition module, IList<IAttribute> outputList)
void AddAttributes(ModuleDefinition module, IList<IUnresolvedAttribute> outputList)
{
if (module.HasCustomAttributes) {
AddCustomAttributes(module.CustomAttributes, outputList);
@ -479,10 +435,10 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion
#region Parameter Attributes
static readonly IAttribute inAttribute = new DefaultAttribute(typeof(InAttribute).ToTypeReference(), null);
static readonly IAttribute outAttribute = new DefaultAttribute(typeof(OutAttribute).ToTypeReference(), null);
static readonly IUnresolvedAttribute inAttribute = new DefaultUnresolvedAttribute(typeof(InAttribute).ToTypeReference());
static readonly IUnresolvedAttribute outAttribute = new DefaultUnresolvedAttribute(typeof(OutAttribute).ToTypeReference());
void AddAttributes(ParameterDefinition parameter, DefaultParameter targetParameter)
void AddAttributes(ParameterDefinition parameter, DefaultUnresolvedParameter targetParameter)
{
if (!targetParameter.IsOut) {
if (parameter.IsIn)
@ -502,9 +458,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
#region Method Attributes
static readonly ITypeReference dllImportAttributeTypeRef = typeof(DllImportAttribute).ToTypeReference();
static readonly SimpleConstantValue trueValue = new SimpleConstantValue(KnownTypeReference.Boolean, true);
static readonly SimpleConstantValue falseValue = new SimpleConstantValue(KnownTypeReference.Boolean, true);
static readonly SimpleConstantValue falseValue = new SimpleConstantValue(KnownTypeReference.Boolean, false);
static readonly ITypeReference callingConventionTypeRef = typeof(CallingConvention).ToTypeReference();
static readonly IAttribute preserveSigAttribute = new DefaultAttribute(typeof(PreserveSigAttribute).ToTypeReference(), null);
static readonly IUnresolvedAttribute preserveSigAttribute = new DefaultUnresolvedAttribute(typeof(PreserveSigAttribute).ToTypeReference());
static readonly ITypeReference methodImplAttributeTypeRef = typeof(MethodImplAttribute).ToTypeReference();
static readonly ITypeReference methodImplOptionsTypeRef = typeof(MethodImplOptions).ToTypeReference();
@ -519,20 +475,20 @@ namespace ICSharpCode.NRefactory.TypeSystem
return methodDefinition.HasCustomAttributes || methodDefinition.MethodReturnType.HasCustomAttributes;
}
void AddAttributes(MethodDefinition methodDefinition, IList<IAttribute> attributes, IList<IAttribute> returnTypeAttributes)
void AddAttributes(MethodDefinition methodDefinition, IList<IUnresolvedAttribute> attributes, IList<IUnresolvedAttribute> returnTypeAttributes)
{
MethodImplAttributes implAttributes = methodDefinition.ImplAttributes & ~MethodImplAttributes.CodeTypeMask;
#region DllImportAttribute
if (methodDefinition.HasPInvokeInfo) {
PInvokeInfo info = methodDefinition.PInvokeInfo;
DefaultAttribute dllImport = new DefaultAttribute(dllImportAttributeTypeRef, new[] { KnownTypeReference.String });
var dllImport = new DefaultUnresolvedAttribute(dllImportAttributeTypeRef, new[] { KnownTypeReference.String });
dllImport.PositionalArguments.Add(new SimpleConstantValue(KnownTypeReference.String, info.Module.Name));
if (info.IsBestFitDisabled)
dllImport.AddNamedArgument("BestFitMapping", falseValue);
dllImport.AddNamedFieldArgument("BestFitMapping", falseValue);
if (info.IsBestFitEnabled)
dllImport.AddNamedArgument("BestFitMapping", trueValue);
dllImport.AddNamedFieldArgument("BestFitMapping", trueValue);
CallingConvention callingConvention;
switch (info.Attributes & PInvokeAttributes.CallConvMask) {
@ -555,7 +511,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
throw new NotSupportedException("unknown calling convention");
}
if (callingConvention != CallingConvention.Winapi)
dllImport.AddNamedArgument("CallingConvention", callingConventionTypeRef, (int)callingConvention);
dllImport.AddNamedFieldArgument("CallingConvention", callingConventionTypeRef, (int)callingConvention);
CharSet charSet = CharSet.None;
switch (info.Attributes & PInvokeAttributes.CharSetMask) {
@ -570,26 +526,26 @@ namespace ICSharpCode.NRefactory.TypeSystem
break;
}
if (charSet != CharSet.None)
dllImport.AddNamedArgument("CharSet", charSetTypeRef, (int)charSet);
dllImport.AddNamedFieldArgument("CharSet", charSetTypeRef, (int)charSet);
if (!string.IsNullOrEmpty(info.EntryPoint) && info.EntryPoint != methodDefinition.Name)
dllImport.AddNamedArgument("EntryPoint", KnownTypeReference.String, info.EntryPoint);
dllImport.AddNamedFieldArgument("EntryPoint", KnownTypeReference.String, info.EntryPoint);
if (info.IsNoMangle)
dllImport.AddNamedArgument("ExactSpelling", trueValue);
dllImport.AddNamedFieldArgument("ExactSpelling", trueValue);
if ((implAttributes & MethodImplAttributes.PreserveSig) == MethodImplAttributes.PreserveSig)
implAttributes &= ~MethodImplAttributes.PreserveSig;
else
dllImport.AddNamedArgument("PreserveSig", falseValue);
dllImport.AddNamedFieldArgument("PreserveSig", falseValue);
if (info.SupportsLastError)
dllImport.AddNamedArgument("SetLastError", trueValue);
dllImport.AddNamedFieldArgument("SetLastError", trueValue);
if (info.IsThrowOnUnmappableCharDisabled)
dllImport.AddNamedArgument("ThrowOnUnmappableChar", falseValue);
dllImport.AddNamedFieldArgument("ThrowOnUnmappableChar", falseValue);
if (info.IsThrowOnUnmappableCharEnabled)
dllImport.AddNamedArgument("ThrowOnUnmappableChar", trueValue);
dllImport.AddNamedFieldArgument("ThrowOnUnmappableChar", trueValue);
attributes.Add(dllImport);
}
@ -604,7 +560,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
#region MethodImplAttribute
if (implAttributes != 0) {
DefaultAttribute methodImpl = new DefaultAttribute(methodImplAttributeTypeRef, new[] { methodImplOptionsTypeRef });
var methodImpl = new DefaultUnresolvedAttribute(methodImplAttributeTypeRef, new[] { methodImplOptionsTypeRef });
methodImpl.PositionalArguments.Add(new SimpleConstantValue(methodImplOptionsTypeRef, (int)implAttributes));
attributes.Add(methodImpl);
}
@ -626,13 +582,13 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion
#region Type Attributes
static readonly DefaultAttribute serializableAttribute = new DefaultAttribute(typeof(SerializableAttribute).ToTypeReference(), null);
static readonly DefaultAttribute comImportAttribute = new DefaultAttribute(typeof(ComImportAttribute).ToTypeReference(), null);
static readonly DefaultUnresolvedAttribute serializableAttribute = new DefaultUnresolvedAttribute(typeof(SerializableAttribute).ToTypeReference());
static readonly DefaultUnresolvedAttribute comImportAttribute = new DefaultUnresolvedAttribute(typeof(ComImportAttribute).ToTypeReference());
static readonly ITypeReference structLayoutAttributeTypeRef = typeof(StructLayoutAttribute).ToTypeReference();
static readonly ITypeReference layoutKindTypeRef = typeof(LayoutKind).ToTypeReference();
static readonly ITypeReference charSetTypeRef = typeof(CharSet).ToTypeReference();
void AddAttributes(TypeDefinition typeDefinition, ITypeDefinition targetEntity)
void AddAttributes(TypeDefinition typeDefinition, IUnresolvedTypeDefinition targetEntity)
{
// SerializableAttribute
if (typeDefinition.IsSerializable)
@ -666,16 +622,16 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
LayoutKind defaultLayoutKind = (typeDefinition.IsValueType && !typeDefinition.IsEnum) ? LayoutKind.Sequential: LayoutKind.Auto;
if (layoutKind != defaultLayoutKind || charSet != CharSet.Ansi || typeDefinition.PackingSize > 0 || typeDefinition.ClassSize > 0) {
DefaultAttribute structLayout = new DefaultAttribute(structLayoutAttributeTypeRef, new[] { layoutKindTypeRef });
DefaultUnresolvedAttribute structLayout = new DefaultUnresolvedAttribute(structLayoutAttributeTypeRef, new[] { layoutKindTypeRef });
structLayout.PositionalArguments.Add(new SimpleConstantValue(layoutKindTypeRef, (int)layoutKind));
if (charSet != CharSet.Ansi) {
structLayout.AddNamedArgument("CharSet", charSetTypeRef, (int)charSet);
structLayout.AddNamedFieldArgument("CharSet", charSetTypeRef, (int)charSet);
}
if (typeDefinition.PackingSize > 0) {
structLayout.AddNamedArgument("Pack", KnownTypeReference.Int32, (int)typeDefinition.PackingSize);
structLayout.AddNamedFieldArgument("Pack", KnownTypeReference.Int32, (int)typeDefinition.PackingSize);
}
if (typeDefinition.ClassSize > 0) {
structLayout.AddNamedArgument("Size", KnownTypeReference.Int32, (int)typeDefinition.ClassSize);
structLayout.AddNamedFieldArgument("Size", KnownTypeReference.Int32, (int)typeDefinition.ClassSize);
}
targetEntity.Attributes.Add(structLayout);
}
@ -692,13 +648,13 @@ namespace ICSharpCode.NRefactory.TypeSystem
#region Field Attributes
static readonly ITypeReference fieldOffsetAttributeTypeRef = typeof(FieldOffsetAttribute).ToTypeReference();
static readonly DefaultAttribute nonSerializedAttribute = new DefaultAttribute(typeof(NonSerializedAttribute).ToTypeReference(), null);
static readonly IUnresolvedAttribute nonSerializedAttribute = new DefaultUnresolvedAttribute(typeof(NonSerializedAttribute).ToTypeReference());
void AddAttributes(FieldDefinition fieldDefinition, IEntity targetEntity)
void AddAttributes(FieldDefinition fieldDefinition, IUnresolvedEntity targetEntity)
{
// FieldOffsetAttribute
if (fieldDefinition.HasLayoutInfo) {
DefaultAttribute fieldOffset = new DefaultAttribute(fieldOffsetAttributeTypeRef, new[] { KnownTypeReference.Int32 });
DefaultUnresolvedAttribute fieldOffset = new DefaultUnresolvedAttribute(fieldOffsetAttributeTypeRef, new[] { KnownTypeReference.Int32 });
fieldOffset.PositionalArguments.Add(new SimpleConstantValue(KnownTypeReference.Int32, fieldDefinition.Offset));
targetEntity.Attributes.Add(fieldOffset);
}
@ -719,7 +675,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion
#region Event Attributes
void AddAttributes(EventDefinition eventDefinition, IEntity targetEntity)
void AddAttributes(EventDefinition eventDefinition, IUnresolvedEntity targetEntity)
{
if (eventDefinition.HasCustomAttributes) {
AddCustomAttributes(eventDefinition.CustomAttributes, targetEntity.Attributes);
@ -728,7 +684,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion
#region Property Attributes
void AddAttributes(PropertyDefinition propertyDefinition, IEntity targetEntity)
void AddAttributes(PropertyDefinition propertyDefinition, IUnresolvedEntity targetEntity)
{
if (propertyDefinition.HasCustomAttributes) {
AddCustomAttributes(propertyDefinition.CustomAttributes, targetEntity.Attributes);
@ -740,39 +696,39 @@ namespace ICSharpCode.NRefactory.TypeSystem
static readonly ITypeReference marshalAsAttributeTypeRef = typeof(MarshalAsAttribute).ToTypeReference();
static readonly ITypeReference unmanagedTypeTypeRef = typeof(UnmanagedType).ToTypeReference();
static IAttribute ConvertMarshalInfo(MarshalInfo marshalInfo)
static IUnresolvedAttribute ConvertMarshalInfo(MarshalInfo marshalInfo)
{
DefaultAttribute attr = new DefaultAttribute(marshalAsAttributeTypeRef, new[] { unmanagedTypeTypeRef });
DefaultUnresolvedAttribute attr = new DefaultUnresolvedAttribute(marshalAsAttributeTypeRef, new[] { unmanagedTypeTypeRef });
attr.PositionalArguments.Add(new SimpleConstantValue(unmanagedTypeTypeRef, (int)marshalInfo.NativeType));
FixedArrayMarshalInfo fami = marshalInfo as FixedArrayMarshalInfo;
if (fami != null) {
attr.AddNamedArgument("SizeConst", KnownTypeReference.Int32, (int)fami.Size);
attr.AddNamedFieldArgument("SizeConst", KnownTypeReference.Int32, (int)fami.Size);
if (fami.ElementType != NativeType.None)
attr.AddNamedArgument("ArraySubType", unmanagedTypeTypeRef, (int)fami.ElementType);
attr.AddNamedFieldArgument("ArraySubType", unmanagedTypeTypeRef, (int)fami.ElementType);
}
SafeArrayMarshalInfo sami = marshalInfo as SafeArrayMarshalInfo;
if (sami != null && sami.ElementType != VariantType.None) {
attr.AddNamedArgument("SafeArraySubType", typeof(VarEnum).ToTypeReference(), (int)sami.ElementType);
attr.AddNamedFieldArgument("SafeArraySubType", typeof(VarEnum).ToTypeReference(), (int)sami.ElementType);
}
ArrayMarshalInfo ami = marshalInfo as ArrayMarshalInfo;
if (ami != null) {
if (ami.ElementType != NativeType.Max)
attr.AddNamedArgument("ArraySubType", unmanagedTypeTypeRef, (int)ami.ElementType);
attr.AddNamedFieldArgument("ArraySubType", unmanagedTypeTypeRef, (int)ami.ElementType);
if (ami.Size >= 0)
attr.AddNamedArgument("SizeConst", KnownTypeReference.Int32, (int)ami.Size);
attr.AddNamedFieldArgument("SizeConst", KnownTypeReference.Int32, (int)ami.Size);
if (ami.SizeParameterMultiplier != 0 && ami.SizeParameterIndex >= 0)
attr.AddNamedArgument("SizeParamIndex", KnownTypeReference.Int16, (short)ami.SizeParameterIndex);
attr.AddNamedFieldArgument("SizeParamIndex", KnownTypeReference.Int16, (short)ami.SizeParameterIndex);
}
CustomMarshalInfo cmi = marshalInfo as CustomMarshalInfo;
if (cmi != null) {
attr.AddNamedArgument("MarshalType", KnownTypeReference.String, cmi.ManagedType.FullName);
attr.AddNamedFieldArgument("MarshalType", KnownTypeReference.String, cmi.ManagedType.FullName);
if (!string.IsNullOrEmpty(cmi.Cookie))
attr.AddNamedArgument("MarshalCookie", KnownTypeReference.String, cmi.Cookie);
attr.AddNamedFieldArgument("MarshalCookie", KnownTypeReference.String, cmi.Cookie);
}
FixedSysStringMarshalInfo fssmi = marshalInfo as FixedSysStringMarshalInfo;
if (fssmi != null) {
attr.AddNamedArgument("SizeConst", KnownTypeReference.Int32, (int)fssmi.Size);
attr.AddNamedFieldArgument("SizeConst", KnownTypeReference.Int32, (int)fssmi.Size);
}
return attr;
@ -780,7 +736,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
#endregion
#region Custom Attributes (ReadAttribute)
void AddCustomAttributes(Mono.Collections.Generic.Collection<CustomAttribute> attributes, IList<IAttribute> targetCollection)
void AddCustomAttributes(Mono.Collections.Generic.Collection<CustomAttribute> attributes, IList<IUnresolvedAttribute> targetCollection)
{
foreach (var cecilAttribute in attributes) {
TypeReference type = cecilAttribute.AttributeType;
@ -795,48 +751,188 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
[CLSCompliant(false)]
public IAttribute ReadAttribute(CustomAttribute attribute)
public IUnresolvedAttribute ReadAttribute(CustomAttribute attribute)
{
if (attribute == null)
throw new ArgumentNullException("attribute");
MethodReference ctor = attribute.Constructor;
ITypeReference[] ctorParameters = null;
ITypeReference attributeType = ReadTypeReference(attribute.AttributeType);
IList<ITypeReference> ctorParameterTypes = null;
if (ctor.HasParameters) {
ctorParameters = new ITypeReference[ctor.Parameters.Count];
for (int i = 0; i < ctorParameters.Length; i++) {
ctorParameters[i] = ReadTypeReference(ctor.Parameters[i].ParameterType);
ctorParameterTypes = new ITypeReference[ctor.Parameters.Count];
for (int i = 0; i < ctorParameterTypes.Count; i++) {
ctorParameterTypes[i] = ReadTypeReference(ctor.Parameters[i].ParameterType);
}
}
DefaultAttribute a = new DefaultAttribute(ReadTypeReference(attribute.AttributeType), ctorParameters);
if (attribute.HasConstructorArguments) {
foreach (var arg in attribute.ConstructorArguments) {
a.PositionalArguments.Add(ReadConstantValue(arg));
if (this.InterningProvider != null) {
attributeType = this.InterningProvider.Intern(attributeType);
ctorParameterTypes = this.InterningProvider.InternList(ctorParameterTypes);
}
return new CecilUnresolvedAttribute(attributeType, ctorParameterTypes, attribute.GetBlob());
}
#endregion
#region CecilUnresolvedAttribute
[Serializable]
sealed class CecilUnresolvedAttribute : IUnresolvedAttribute, ISupportsInterning
{
readonly ITypeReference attributeType;
internal readonly IList<ITypeReference> ctorParameterTypes;
internal readonly byte[] blob;
public CecilUnresolvedAttribute(ITypeReference attributeType, IList<ITypeReference> ctorParameterTypes, byte[] blob)
{
this.attributeType = attributeType;
this.ctorParameterTypes = ctorParameterTypes;
this.blob = blob;
}
public DomRegion Region {
get { return DomRegion.Empty; }
}
public ITypeReference AttributeType {
get { return attributeType; }
}
public IAttribute CreateResolvedAttribute(ITypeResolveContext context)
{
throw new NotImplementedException();
}
void ISupportsInterning.PrepareForInterning(IInterningProvider provider)
{
// We already interned our child elements in ReadAttribute().
}
int ISupportsInterning.GetHashCodeForInterning()
{
unchecked {
int hash = attributeType.GetHashCode() ^ ctorParameterTypes.GetHashCode();
foreach (byte b in blob) {
hash *= 257;
hash += b;
}
return hash;
}
}
if (attribute.HasFields || attribute.HasProperties) {
foreach (var arg in attribute.Fields) {
a.NamedArguments.Add(new KeyValuePair<string, IConstantValue>(arg.Name, ReadConstantValue(arg.Argument)));
}
foreach (var arg in attribute.Properties) {
a.NamedArguments.Add(new KeyValuePair<string, IConstantValue>(arg.Name, ReadConstantValue(arg.Argument)));
bool ISupportsInterning.EqualsForInterning(ISupportsInterning other)
{
CecilUnresolvedAttribute o = other as CecilUnresolvedAttribute;
if (o != null && attributeType == o.attributeType && ctorParameterTypes == o.ctorParameterTypes && blob.Length == o.blob.Length) {
for (int i = 0; i < blob.Length; i++) {
if (blob[i] != o.blob[i])
return false;
}
return true;
} else {
return false;
}
}
return a;
}
#endregion
#region CecilResolvedAttribute
sealed class CecilResolvedAttribute : IAttribute
{
readonly ITypeResolveContext context;
readonly CecilUnresolvedAttribute unresolved;
readonly IType attributeType;
IMethod constructor;
volatile bool constructorResolved;
volatile IList<ResolveResult> positionalArguments;
volatile IList<KeyValuePair<IMember, ResolveResult>> namedArguments;
public CecilResolvedAttribute(ITypeResolveContext context, CecilUnresolvedAttribute unresolved)
{
this.context = context;
this.unresolved = unresolved;
this.attributeType = unresolved.AttributeType.Resolve(context);
}
public DomRegion Region {
get { return unresolved.Region; }
}
public IType AttributeType {
get { return attributeType; }
}
public IMethod Constructor {
get {
if (!constructorResolved) {
constructor = ResolveConstructor();
constructorResolved = true;
}
return constructor;
}
}
IMethod ResolveConstructor()
{
var parameterTypes = unresolved.ctorParameterTypes.Resolve(context);
foreach (var ctor in attributeType.GetConstructors(m => m.Parameters.Count == parameterTypes.Count)) {
bool ok = true;
for (int i = 0; i < parameterTypes.Count; i++) {
if (!ctor.Parameters[i].Type.Equals(parameterTypes[i])) {
ok = false;
break;
}
}
if (ok)
return ctor;
}
return null;
}
public IList<ResolveResult> PositionalArguments {
get {
var result = this.positionalArguments;
if (result != null)
return result;
DecodeBlob();
return positionalArguments;
}
}
public IList<KeyValuePair<IMember, ResolveResult>> NamedArguments {
get {
var result = this.namedArguments;
if (result != null)
return result;
DecodeBlob();
return namedArguments;
}
}
public ICompilation Compilation {
get { return context.Compilation; }
}
void DecodeBlob()
{
throw new NotImplementedException();
}
}
#endregion
#region Security Attributes
static readonly ITypeReference securityActionTypeReference = typeof(SecurityAction).ToTypeReference();
void AddSecurityAttributes(Mono.Collections.Generic.Collection<SecurityDeclaration> securityDeclarations, IList<IAttribute> targetCollection)
void AddSecurityAttributes(Mono.Collections.Generic.Collection<SecurityDeclaration> securityDeclarations, IList<IUnresolvedAttribute> targetCollection)
{
foreach (var secDecl in securityDeclarations) {
try {
foreach (var secAttribute in secDecl.SecurityAttributes) {
ITypeReference attributeType = ReadTypeReference(secAttribute.AttributeType);
var a = new DefaultAttribute(attributeType, new[] { securityActionTypeReference });
var a = new DefaultUnresolvedAttribute(attributeType, new[] { securityActionTypeReference });
a.PositionalArguments.Add(new SimpleConstantValue(securityActionTypeReference, (ushort)secDecl.Action));
throw new NotImplementedException();
/*
if (secAttribute.HasFields || secAttribute.HasProperties) {
foreach (var arg in secAttribute.Fields) {
a.NamedArguments.Add(new KeyValuePair<string, IConstantValue>(arg.Name, ReadConstantValue(arg.Argument)));
@ -845,41 +941,18 @@ namespace ICSharpCode.NRefactory.TypeSystem
a.NamedArguments.Add(new KeyValuePair<string, IConstantValue>(arg.Name, ReadConstantValue(arg.Argument)));
}
}
targetCollection.Add(a);
targetCollection.Add(a);*/
}
} catch (ResolutionException) {
// occurs when Cecil can't decode an argument
// TODO: use CecilAttribute so that we can do the blob decoding ourselves
}
}
}
#endregion
#endregion
#region Read Constant Value
[CLSCompliant(false)]
public IConstantValue ReadConstantValue(CustomAttributeArgument arg)
{
object value = arg.Value;
if (value is CustomAttributeArgument) {
// Cecil uses this representation for boxed values
arg = (CustomAttributeArgument)value;
value = arg.Value;
}
ITypeReference type = ReadTypeReference(arg.Type);
CustomAttributeArgument[] array = value as CustomAttributeArgument[];
if (array != null) {
// TODO: write unit test for this
// TODO: are multi-dimensional arrays possible as well?
throw new NotImplementedException();
}
TypeReference valueType = value as TypeReference;
if (valueType != null)
value = ReadTypeReference(valueType);
return new SimpleConstantValue(type, value);
}
#endregion
/*
#region Read Type Definition
[Serializable]
sealed class CecilTypeDefinition : DefaultTypeDefinition
@ -1401,7 +1474,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
member.ApplyInterningProvider(this.InterningProvider);
if (HasCecilReferences)
typeSystemTranslationTable[member] = cecilDefinition;
}
}*/
#region Type system translation table
Dictionary<object, object> typeSystemTranslationTable;
@ -1419,42 +1492,39 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
[CLSCompliant(false)]
public AssemblyDefinition GetCecilObject (IProjectContent content)
public AssemblyDefinition GetCecilObject (IUnresolvedAssembly content)
{
return InternalGetCecilObject<AssemblyDefinition> (content);
}
[CLSCompliant(false)]
public TypeDefinition GetCecilObject (ITypeDefinition type)
public TypeDefinition GetCecilObject (IUnresolvedTypeDefinition type)
{
if (type == null)
throw new ArgumentNullException ("type");
var cecilType = type as CecilTypeDefinition;
if (cecilType == null)
throw new ArgumentException ("type is no cecil type definition.");
return cecilType.typeDefinition;
return InternalGetCecilObject<TypeDefinition> (type);
}
[CLSCompliant(false)]
public MethodDefinition GetCecilObject (IMethod method)
public MethodDefinition GetCecilObject (IUnresolvedMethod method)
{
return InternalGetCecilObject<MethodDefinition> (method);
}
[CLSCompliant(false)]
public FieldDefinition GetCecilObject (IField field)
public FieldDefinition GetCecilObject (IUnresolvedField field)
{
return InternalGetCecilObject<FieldDefinition> (field);
}
[CLSCompliant(false)]
public EventDefinition GetCecilObject (IEvent evt)
public EventDefinition GetCecilObject (IUnresolvedEvent evt)
{
return InternalGetCecilObject<EventDefinition> (evt);
}
[CLSCompliant(false)]
public PropertyDefinition GetCecilObject (IProperty property)
public PropertyDefinition GetCecilObject (IUnresolvedProperty property)
{
return InternalGetCecilObject<PropertyDefinition> (property);
}

Просмотреть файл

@ -30,7 +30,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
readonly int beginColumn;
readonly int endColumn;
public readonly static DomRegion Empty = new DomRegion(null, -1, -1);
public readonly static DomRegion Empty = new DomRegion();
public bool IsEmpty {
get {
@ -161,8 +161,8 @@ namespace ICSharpCode.NRefactory.TypeSystem
{
return string.Format(
CultureInfo.InvariantCulture,
"[DomRegion FileName={0}, BeginLine={1}, EndLine={2}, BeginColumn={3}, EndColumn={4}]",
fileName, beginLine, endLine, beginColumn, endColumn);
"[DomRegion FileName={0}, Begin=({1}, {2}), End=({3}, {4})]",
fileName, beginLine, beginColumn, endLine, endColumn);
}
public override bool Equals(object obj)
@ -174,15 +174,15 @@ namespace ICSharpCode.NRefactory.TypeSystem
{
unchecked {
int hashCode = fileName != null ? fileName.GetHashCode() : 0;
hashCode ^= BeginColumn + 1100009 * BeginLine + 1200007 * BeginColumn + 1300021 * EndColumn;
hashCode ^= beginColumn + 1100009 * beginLine + 1200007 * endLine + 1300021 * endColumn;
return hashCode;
}
}
public bool Equals(DomRegion other)
{
return BeginLine == other.BeginLine && BeginColumn == other.BeginColumn
&& EndLine == other.EndLine && EndColumn == other.EndColumn
return beginLine == other.beginLine && beginColumn == other.beginColumn
&& endLine == other.endLine && endColumn == other.endColumn
&& fileName == other.fileName;
}

Просмотреть файл

@ -19,6 +19,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
@ -39,9 +40,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
///
/// The output is ordered so that base types occur before derived types.
/// </remarks>
public static IEnumerable<IType> GetAllBaseTypes(this IType type, ITypeResolveContext context)
public static IEnumerable<IType> GetAllBaseTypes(this IType type)
{
BaseTypeCollector collector = new BaseTypeCollector(context);
BaseTypeCollector collector = new BaseTypeCollector();
collector.CollectBaseTypes(type);
return collector;
}
@ -54,9 +55,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
///
/// The output is ordered so that base types occur before derived types.
/// </remarks>
public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type, ITypeResolveContext context)
public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type)
{
BaseTypeCollector collector = new BaseTypeCollector(context);
BaseTypeCollector collector = new BaseTypeCollector();
collector.SkipImplementedInterfaces = true;
collector.CollectBaseTypes(type);
return collector;
@ -70,16 +71,14 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <remarks>
/// This is equivalent to type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct().
/// </remarks>
public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type, ITypeResolveContext context)
public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type)
{
if (type == null)
throw new ArgumentNullException("type");
if (context == null)
throw new ArgumentNullException("context");
HashSet<ITypeDefinition> typeDefinitions = new HashSet<ITypeDefinition>();
Func<ITypeDefinition, IEnumerable<ITypeDefinition>> recursion =
t => t.GetBaseTypes(context).Select(b => b.GetDefinition()).Where(d => d != null && typeDefinitions.Add(d));
t => t.DirectBaseTypes.Select(b => b.GetDefinition()).Where(d => d != null && typeDefinitions.Add(d));
ITypeDefinition typeDef = type.GetDefinition();
if (typeDef != null) {
@ -87,7 +86,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
return TreeTraversal.PreOrder(typeDef, recursion);
} else {
return TreeTraversal.PreOrder(
type.GetBaseTypes(context).Select(b => b.GetDefinition()).Where(d => d != null && typeDefinitions.Add(d)),
type.DirectBaseTypes.Select(b => b.GetDefinition()).Where(d => d != null && typeDefinitions.Add(d)),
recursion);
}
}
@ -95,9 +94,9 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary>
/// Gets whether this type definition is derived from the base type defintiion.
/// </summary>
public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType, ITypeResolveContext context)
public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType)
{
return GetAllBaseTypeDefinitions(type, context).Contains(baseType);
return GetAllBaseTypeDefinitions(type).Contains(baseType);
}
#endregion
@ -151,50 +150,7 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
#endregion
#region IsEnum / IsDelegate
/// <summary>
/// Gets whether the type is an enumeration type.
/// </summary>
[Obsolete("Use type.Kind == TypeKind.Enum instead")]
public static bool IsEnum(this IType type)
{
if (type == null)
throw new ArgumentNullException("type");
return type.Kind == TypeKind.Enum;
}
/// <summary>
/// Gets the underlying type for this enum type.
/// </summary>
public static IType GetEnumUnderlyingType(this IType enumType, ITypeResolveContext context)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
if (context == null)
throw new ArgumentNullException("context");
ITypeDefinition def = enumType.GetDefinition();
if (def != null && def.Kind == TypeKind.Enum) {
if (def.BaseTypes.Count == 1)
return def.BaseTypes[0].Resolve(context);
else
return KnownTypeReference.Int32.Resolve(context);
} else {
return SharedTypes.UnknownType;
}
}
/// <summary>
/// Gets whether the type is an delegate type.
/// </summary>
/// <remarks>This method returns <c>false</c> for System.Delegate itself</remarks>
[Obsolete("Use type.Kind == TypeKind.Delegate instead")]
public static bool IsDelegate(this IType type)
{
if (type == null)
throw new ArgumentNullException("type");
return type.Kind == TypeKind.Delegate;
}
#region GetDelegateInvokeMethod
/// <summary>
/// Gets the invoke method for a delegate type.
/// </summary>
@ -207,13 +163,13 @@ namespace ICSharpCode.NRefactory.TypeSystem
throw new ArgumentNullException("type");
ITypeDefinition def = type.GetDefinition();
if (def != null && def.Kind == TypeKind.Delegate) {
foreach (IMethod method in def.Methods) {
if (method.Name == "Invoke") {
foreach (IMember member in def.Members) {
if (member.Name == "Invoke" && member is IMethod) {
ParameterizedType pt = type as ParameterizedType;
if (pt != null) {
return new SpecializedMethod(pt, method);
return new SpecializedMethod(pt, (IMethod)member);
}
return method;
return (IMethod)member;
}
}
}
@ -221,37 +177,12 @@ namespace ICSharpCode.NRefactory.TypeSystem
}
#endregion
#region InternalsVisibleTo
/// <summary>
/// Gets whether the internals of this project are visible to the other project
/// </summary>
public static bool InternalsVisibleTo(this IProjectContent projectContent, IProjectContent other, ITypeResolveContext context)
{
if (projectContent == other)
return true;
// TODO: implement support for [InternalsVisibleToAttribute]
// Make sure implementation doesn't hurt performance, e.g. don't resolve all assembly attributes whenever
// this method is called - it'll be called once per internal member during lookup operations
return false;
}
#endregion
#region GetAllTypes
/// <summary>
/// Gets all type definitions, including nested types.
/// </summary>
public static IEnumerable<ITypeDefinition> GetAllTypes(this ITypeResolveContext context)
{
return TreeTraversal.PreOrder(context.GetTypes(), t => t.NestedTypes);
}
#endregion
#region GetType/Member
/// <summary>
/// Gets the type (potentially a nested type) defined at the specified location.
/// Returns null if no type is defined at that location.
/// </summary>
public static ITypeDefinition GetInnermostTypeDefinition (this IParsedFile file, int line, int column)
public static IUnresolvedTypeDefinition GetInnermostTypeDefinition (this IParsedFile file, int line, int column)
{
return file.GetInnermostTypeDefinition (new TextLocation (line, column));
}
@ -260,22 +191,39 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Gets the member defined at the specified location.
/// Returns null if no member is defined at that location.
/// </summary>
public static IMember GetMember (this IParsedFile file, int line, int column)
public static IUnresolvedMember GetMember (this IParsedFile file, int line, int column)
{
return file.GetMember (new TextLocation (line, column));
}
#endregion
#region GetSubTypeDefinitions
/// <summary>
/// Gets all sub type definitions defined in a context.
/// </summary>
public static IEnumerable<ITypeDefinition> GetSubTypeDefinitions (this ITypeDefinition baseType, ITypeResolveContext context)
#region Resolve on collections
public static IList<IAttribute> CreateResolvedAttributes(this IList<IUnresolvedAttribute> attributes, ITypeResolveContext context)
{
foreach (var contextType in context.GetAllTypes ()) {
if (contextType.IsDerivedFrom (baseType, context))
yield return contextType;
}
if (attributes == null)
throw new ArgumentNullException("attributes");
if (attributes.Count == 0)
return EmptyList<IAttribute>.Instance;
else
return new ProjectedList<ITypeResolveContext, IUnresolvedAttribute, IAttribute>(context, attributes, (c, a) => a.CreateResolvedAttribute(c));
}
public static IList<IType> Resolve(this IList<ITypeReference> typeReferences, ITypeResolveContext context)
{
if (typeReferences == null)
throw new ArgumentNullException("typeReferences");
if (typeReferences.Count == 0)
return EmptyList<IType>.Instance;
else
return new ProjectedList<ITypeResolveContext, ITypeReference, IType>(context, typeReferences, (c, t) => t.Resolve(c));
}
public static IList<ResolveResult> Resolve(this IList<IConstantValue> constantValues, ITypeResolveContext context)
{
if (constantValues.Count == 0)
return EmptyList<ResolveResult>.Instance;
else
return new ProjectedList<ITypeResolveContext, IConstantValue, ResolveResult>(context, constantValues, (c, t) => t.Resolve(c));
}
#endregion
}

Просмотреть файл

@ -24,7 +24,30 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// <summary>
/// Represents an accessor (property getter/setter; or event add/remove/invoke).
/// </summary>
public interface IAccessor : IFreezable
public interface IUnresolvedAccessor : IHasAccessibility
{
/// <summary>
/// Gets the accessor region.
/// </summary>
DomRegion Region { get; }
/// <summary>
/// Gets the attributes defined on this accessor.
/// </summary>
IList<IUnresolvedAttribute> Attributes { get; }
/// <summary>
/// Gets the attributes defined on the return type of the accessor. (e.g. [return: MarshalAs(...)])
/// </summary>
IList<IUnresolvedAttribute> ReturnTypeAttributes { get; }
//IAccessor CreateResolvedAccessor(ITypeResolveContext context);
}
/// <summary>
/// Represents an accessor (property getter/setter; or event add/remove/invoke).
/// </summary>
public interface IAccessor : IResolved, IHasAccessibility
{
/// <summary>
/// Gets the accessor region.
@ -40,10 +63,5 @@ namespace ICSharpCode.NRefactory.TypeSystem
/// Gets the attributes defined on the return type of the accessor. (e.g. [return: MarshalAs(...)])
/// </summary>
IList<IAttribute> ReturnTypeAttributes { get; }
/// <summary>
/// Gets the accessibility of this accessor.
/// </summary>
Accessibility Accessibility { get; }
}
}

Просмотреть файл

@ -78,15 +78,11 @@ namespace ICSharpCode.NRefactory.TypeSystem
public interface IAmbience
{
ConversionFlags ConversionFlags {
get;
set;
}
ConversionFlags ConversionFlags { get; set; }
string ConvertEntity(IEntity e, ITypeResolveContext context);
string ConvertEntity(IEntity e);
string ConvertType(IType type);
string ConvertType(ITypeReference type, ITypeResolveContext context);
string ConvertVariable(IVariable variable, ITypeResolveContext context);
string ConvertVariable(IVariable variable);
string WrapAttribute(string attribute);
string WrapComment(string comment);

Просмотреть файл

@ -0,0 +1,93 @@
// 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;
namespace ICSharpCode.NRefactory.TypeSystem
{
/// <summary>
/// Represents an unresolved assembly.
/// </summary>
public interface IUnresolvedAssembly : IAssemblyReference
{
/// <summary>
/// Gets the assembly name (short name).
/// </summary>
string AssemblyName { get; }
/// <summary>
/// Gets the list of all assembly attributes in the project.
/// </summary>
IList<IUnresolvedAttribute> AssemblyAttributes { get; }
/// <summary>
/// Gets the list of all module attributes in the project.
/// </summary>
IList<IUnresolvedAttribute> ModuleAttributes { get; }
}
public interface IAssemblyReference
{
/// <summary>
/// Resolves this assembly.
/// </summary>
IAssembly Resolve(ICompilation compilation);
}
/// <summary>
/// Represents an assembly.
/// </summary>
public interface IAssembly : IResolved
{
/// <summary>
/// Gets the original unresolved assembly.
/// </summary>
IUnresolvedAssembly UnresolvedAssembly { get; }
/// <summary>
/// Gets whether this assembly is the main assembly of the compilation.
/// </summary>
bool IsMainAssembly { get; }
/// <summary>
/// Gets the assembly name (short name).
/// </summary>
string AssemblyName { get; }
/// <summary>
/// Gets the list of all assembly attributes in the project.
/// </summary>
IList<IAttribute> AssemblyAttributes { get; }
/// <summary>
/// Gets the list of all module attributes in the project.
/// </summary>
IList<IAttribute> ModuleAttributes { get; }
/// <summary>
/// Gets whether the internals of this assembly are visible in the specified assembly.
/// </summary>
bool InternalsVisibleTo(IAssembly assembly);
/// <summary>
/// Gets the root namespace for this assembly.
/// </summary>
INamespace RootNamespace { get; }
}
}

Просмотреть файл

@ -25,13 +25,13 @@ using ICSharpCode.NRefactory.Semantics;
namespace ICSharpCode.NRefactory.TypeSystem
{
/// <summary>
/// Represents an attribute.
/// Represents an unresolved attribute.
/// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(IAttributeContract))]
[ContractClass(typeof(IUnresolvedAttributeContract))]
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public interface IAttribute : IFreezable
public interface IUnresolvedAttribute
{
/// <summary>
/// Gets the code region of this attribute.
@ -44,20 +44,45 @@ namespace ICSharpCode.NRefactory.TypeSystem
ITypeReference AttributeType { get; }
/// <summary>
/// Gets the positional arguments passed to the attribute.
/// Resolves the attribute.
/// </summary>
IList<ResolveResult> GetPositionalArguments(ITypeResolveContext context);
IAttribute CreateResolvedAttribute(ITypeResolveContext context);
}
/// <summary>
/// Represents an attribute.
/// </summary>
#if WITH_CONTRACTS
[ContractClass(typeof(IAttributeContract))]
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public interface IAttribute
{
/// <summary>
/// Gets the code region of this attribute.
/// </summary>
DomRegion Region { get; }
/// <summary>
/// Gets the type of the attribute.
/// </summary>
IType AttributeType { get; }
/// <summary>
/// Gets the constructor being used.
/// This property may return null if no matching constructor was found.
/// </summary>
IMethod Constructor { get; }
/// <summary>
/// Gets the positional arguments.
/// </summary>
IList<ResolveResult> PositionalArguments { get; }
/// <summary>
/// Gets the named arguments passed to the attribute.
/// </summary>
IList<KeyValuePair<string, ResolveResult>> GetNamedArguments(ITypeResolveContext context);
/// <summary>
/// Resolves the constructor method used for this attribute invocation.
/// Returns null if the constructor cannot be found.
/// </summary>
IMethod ResolveConstructor(ITypeResolveContext context);
IList<KeyValuePair<IMember, ResolveResult>> NamedArguments { get; }
}
#if WITH_CONTRACTS

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше