/// <summary> /// Creates a new unknown type. /// </summary> /// <param name="namespaceName">Namespace name, if known. Can be null if unknown.</param> /// <param name="name">Name of the type, must not be null.</param> /// <param name="typeParameterCount">Type parameter count, zero if unknown.</param> public UnknownType(string namespaceName, string name, int typeParameterCount = 0) { if (name == null) throw new ArgumentNullException("name"); this.namespaceKnown = namespaceName != null; this.fullTypeName = new TopLevelTypeName(namespaceName ?? string.Empty, name, typeParameterCount); }
public NUnitTestMethod(ITestProject parentProject, IUnresolvedMethod method, FullTypeName derivedFixture = default(FullTypeName)) { if (parentProject == null) throw new ArgumentNullException("parentProject"); this.parentProject = parentProject; UpdateTestMethod(method, derivedFixture); }
public NUnitTestClass(NUnitTestProject parentProject, FullTypeName fullTypeName) { if (parentProject == null) throw new ArgumentNullException("parentProject"); this.parentProject = parentProject; this.fullTypeName = fullTypeName; BindResultToCompositeResultOfNestedTests(); // No need to call UpdateTestClass() here as NestedTestsInitialized still is false }
IType GetMethodReturnType(string typeName) { var fullTypeName = new FullTypeName(typeName); IType type = typeDefinition.Compilation.FindType(fullTypeName); if (type != null) { return type; } return new UnknownType(fullTypeName); }
IType GetFieldType(string type) { var fieldTypeName = new FullTypeName(type); IType fieldType = typeDefinition.Compilation.FindType(fieldTypeName); if (fieldType != null) { return fieldType; } return new UnknownType(fieldTypeName); }
/// <summary> /// Retrieves the specified type in this compilation. /// Returns an <see cref="UnknownType"/> if the type cannot be found in this compilation. /// </summary> /// <remarks> /// There can be multiple types with the same full name in a compilation, as a /// full type name is only unique per assembly. /// If there are multiple possible matches, this method will return just one of them. /// When possible, use <see cref="IAssembly.GetTypeDefinition"/> instead to /// retrieve a type from a specific assembly. /// </remarks> public static IType FindType(this ICompilation compilation, FullTypeName fullTypeName) { if (compilation == null) throw new ArgumentNullException("compilation"); foreach (IAssembly asm in compilation.Assemblies) { ITypeDefinition def = asm.GetTypeDefinition(fullTypeName); if (def != null) return def; } return new UnknownType(fullTypeName); }
/// <summary> /// Creates a new unknown type. /// </summary> /// <param name="fullTypeName">Full name of the unknown type.</param> public UnknownType(FullTypeName fullTypeName) { if (fullTypeName.Name == null) { Debug.Assert(fullTypeName == default(FullTypeName)); this.namespaceKnown = false; this.fullTypeName = new TopLevelTypeName(string.Empty, "?", 0); } else { this.namespaceKnown = true; this.fullTypeName = fullTypeName; } }
public virtual global::EnvDTE.CodeVariable AddVariable(string name, object type, object Position = null, global::EnvDTE.vsCMAccess Access = global::EnvDTE.vsCMAccess.vsCMAccessPublic, object Location = null) { var fieldTypeName = new FullTypeName((string)type); var td = typeModel.Resolve(); if (td == null) return null; IType fieldType = td.Compilation.FindType(fieldTypeName); context.CodeGenerator.AddField(td, Access.ToAccessibility(), fieldType, name); var fieldModel = typeModel.Members.OfType<IFieldModel>().FirstOrDefault(f => f.Name == name); if (fieldModel != null) { return new CodeVariable(context, fieldModel); } return null; }
public void UpdateTestMethod(IUnresolvedMethod method, FullTypeName derivedFixture = default(FullTypeName)) { if (method == null) throw new ArgumentNullException("method"); string oldDisplayName = this.displayName; this.derivedFixture = derivedFixture; this.method = method; if (this.IsInherited) displayName = method.DeclaringTypeDefinition.Name + "." + method.Name; else displayName = method.Name; if (displayName != oldDisplayName && DisplayNameChanged != null) DisplayNameChanged(this, EventArgs.Empty); }
public MSTestClass(MSTestProject parentProject, FullTypeName fullTypeName) { this.parentProject = parentProject; this.fullTypeName = fullTypeName; BindResultToCompositeResultOfNestedTests(); }
/// <summary> /// Creates a new GetClassTypeReference that searches a top-level type in the specified assembly. /// </summary> /// <param name="assembly">A reference to the assembly containing this type. /// If this parameter is null, the GetClassTypeReference will search in all assemblies belonging to the ICompilation.</param> /// <param name="namespaceName">The namespace name containing the type, e.g. "System.Collections.Generic".</param> /// <param name="name">The name of the type, e.g. "List".</param> /// <param name="typeParameterCount">The number of type parameters, (e.g. 1 for List<T>).</param> public GetClassTypeReference(IAssemblyReference assembly, string namespaceName, string name, int typeParameterCount = 0) { this.assembly = assembly; this.fullTypeName = new TopLevelTypeName(namespaceName, name, typeParameterCount); }
/// <summary> /// Creates a new GetClassTypeReference that searches a top-level type in the specified assembly. /// </summary> /// <param name="module">A reference to the assembly containing this type. /// If this parameter is null, the GetClassTypeReference will search in all assemblies belonging to the ICompilation.</param> /// <param name="namespaceName">The namespace name containing the type, e.g. "System.Collections.Generic".</param> /// <param name="name">The name of the type, e.g. "List".</param> /// <param name="typeParameterCount">The number of type parameters, (e.g. 1 for List<T>).</param> public GetClassTypeReference(IModuleReference module, string namespaceName, string name, int typeParameterCount = 0, bool?isReferenceType = null) { this.module = module; this.fullTypeName = new TopLevelTypeName(namespaceName, name, typeParameterCount); this.isReferenceType = isReferenceType; }
/// <summary> /// Gets the type definition for the specified unresolved type. /// Returns null if the unresolved type does not belong to this assembly. /// </summary> public static ITypeDefinition GetTypeDefinition(this IAssembly assembly, FullTypeName fullTypeName) { if (assembly == null) throw new ArgumentNullException("assembly"); TopLevelTypeName topLevelTypeName = fullTypeName.TopLevelTypeName; ITypeDefinition typeDef = assembly.GetTypeDefinition(topLevelTypeName); if (typeDef == null) return null; int typeParameterCount = topLevelTypeName.TypeParameterCount; for (int i = 0; i < fullTypeName.NestingLevel; i++) { string name = fullTypeName.GetNestedTypeName(i); typeParameterCount += fullTypeName.GetNestedTypeAdditionalTypeParameterCount(i); typeDef = FindNestedType(typeDef, name, typeParameterCount); if (typeDef == null) break; } return typeDef; }
/// <summary> /// Gets the attribute of the specified attribute type (or derived attribute types). /// </summary> /// <param name="entity">The entity on which the attributes are declared.</param> /// <param name="attributeType">The attribute type to look for.</param> /// <param name="inherit"> /// Specifies whether attributes inherited from base classes and base members (if the given <paramref name="entity"/> in an <c>override</c>) /// should be returned. The default is <c>true</c>. /// </param> /// <returns> /// Returns the attribute that was found; or <c>null</c> if none was found. /// If inherit is true, an from the entity itself will be returned if possible; /// and the base entity will only be searched if none exists. /// </returns> public static IAttribute GetAttribute(this IEntity entity, FullTypeName attributeType, bool inherit = true) { return GetAttributes(entity, attributeType, inherit).FirstOrDefault(); }
public void RegisterInheritedClass(FullTypeName baseClassName, NUnitTestClass inheritedClass) { inheritedTestClasses.Add(baseClassName.TopLevelTypeName, inheritedClass); }
internal MetadataTypeDefinition(MetadataModule module, TypeDefinitionHandle handle) { Debug.Assert(module != null); Debug.Assert(!handle.IsNil); this.module = module; this.handle = handle; var metadata = module.metadata; var td = metadata.GetTypeDefinition(handle); this.attributes = td.Attributes; this.fullTypeName = td.GetFullTypeName(metadata); // Find DeclaringType + KnownTypeCode: if (fullTypeName.IsNested) { this.DeclaringTypeDefinition = module.GetDefinition(td.GetDeclaringType()); // Create type parameters: this.TypeParameters = MetadataTypeParameter.Create(module, this.DeclaringTypeDefinition, this, td.GetGenericParameters()); } else { // Create type parameters: this.TypeParameters = MetadataTypeParameter.Create(module, this, td.GetGenericParameters()); var topLevelTypeName = fullTypeName.TopLevelTypeName; for (int i = 0; i < KnownTypeReference.KnownTypeCodeCount; i++) { var ktr = KnownTypeReference.Get((KnownTypeCode)i); if (ktr != null && ktr.TypeName == topLevelTypeName) { this.KnownTypeCode = (KnownTypeCode)i; break; } } } // Find type kind: if ((attributes & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) { this.Kind = TypeKind.Interface; } else if (td.IsEnum(metadata, out var underlyingType)) { this.Kind = TypeKind.Enum; this.EnumUnderlyingType = module.Compilation.FindType(underlyingType.ToKnownTypeCode()); } else if (td.IsValueType(metadata)) { if (KnownTypeCode == KnownTypeCode.Void) { this.Kind = TypeKind.Void; } else { this.Kind = TypeKind.Struct; this.IsByRefLike = td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.IsByRefLike); } } else if (td.IsDelegate(metadata)) { this.Kind = TypeKind.Delegate; } else { this.Kind = TypeKind.Class; this.HasExtensionMethods = this.IsStatic && td.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.Extension); } }
public MSpecTestClass(MSpecTestProject parentProject, FullTypeName fullTypeName) { this.parentProject = parentProject; this.fullTypeName = fullTypeName; BindResultToCompositeResultOfNestedTests(); }
public void UpdateTestClass(ITypeDefinition typeDefinition) { fullTypeName = typeDefinition.FullTypeName; if (this.NestedTestsInitialized) { int baseClassIndex = 0; foreach (IType baseType in typeDefinition.GetNonInterfaceBaseTypes()) { ITypeDefinition baseTypeDef = baseType.GetDefinition(); // Check that the base type isn't equal to System.Object or the current class itself if (baseTypeDef == null || baseTypeDef == typeDefinition || baseTypeDef.KnownTypeCode == KnownTypeCode.Object) { continue; } if (baseTypeDef.DeclaringTypeDefinition != null) { continue; // we only support inheriting from top-level classes } var baseClassName = baseTypeDef.FullTypeName; if (baseClassIndex < baseClassNames.Count && baseClassName == baseClassNames[baseClassIndex]) { // base class is already in the list, just keep it baseClassIndex++; } else { // base class is not in the list, or the remaining portion of the list differs // remove remaining portion of the list: RemoveBaseClasses(baseClassIndex); // Add new base class: parentProject.RegisterInheritedClass(baseClassName, this); baseClassNames.Add(baseClassName); baseClassIndex++; } } HashSet <ITest> newOrUpdatedNestedTests = new HashSet <ITest>(); // Update nested test classes: foreach (ITypeDefinition nestedClass in typeDefinition.NestedTypes) { if (!NUnitTestFramework.IsTestClass(nestedClass)) { continue; } NUnitTestClass nestedTestClass = FindNestedTestClass(nestedClass.Name, nestedClass.TypeParameterCount); if (nestedTestClass != null) { nestedTestClass.UpdateTestClass(nestedClass); } else { nestedTestClass = new NUnitTestClass(parentProject, nestedClass.FullTypeName); this.NestedTestCollection.Add(nestedTestClass); } newOrUpdatedNestedTests.Add(nestedTestClass); } // Get methods (not operators etc.) foreach (IMethod method in typeDefinition.GetMethods(m => m.SymbolKind == SymbolKind.Method)) { if (!NUnitTestFramework.IsTestMethod(method)) { continue; } IUnresolvedMethod unresolvedMethod = (IUnresolvedMethod)method.UnresolvedMember; string methodNameWithDeclaringType; FullTypeName derivedFixture; if (method.DeclaringTypeDefinition == typeDefinition) { derivedFixture = default(FullTypeName); // method is not inherited methodNameWithDeclaringType = method.Name; } else { if (method.DeclaringTypeDefinition == null) { continue; } derivedFixture = fullTypeName; // method is inherited methodNameWithDeclaringType = method.DeclaringTypeDefinition.Name + "." + method.Name; } NUnitTestMethod testMethod; if (method.IsOverride) { testMethod = FindTestMethodWithShortName(method.Name); } else { testMethod = FindTestMethod(methodNameWithDeclaringType); } if (testMethod != null) { testMethod.UpdateTestMethod(unresolvedMethod, derivedFixture); } else { testMethod = new NUnitTestMethod(parentProject, unresolvedMethod, derivedFixture); this.NestedTestCollection.Add(testMethod); } newOrUpdatedNestedTests.Add(testMethod); } // Remove all tests that weren't contained in the new type definition anymore: this.NestedTestCollection.RemoveAll(t => !newOrUpdatedNestedTests.Contains(t)); } }
void CopyGen(TypeDefinition type) { bool isNested = type.IsNested; HashSet <string> IgnoreNestType = new HashSet <string>(); if (!(isNested && IsCopyOrign(genType.DeclaringType))) { var tName = type.FullName.Replace("/", "+"); var name = new FullTypeName(tName); SyntaxTree syntaxTree; if (isNested) { ITypeDefinition typeInfo = Binder.Decompiler.TypeSystem.MainModule.Compilation.FindType(name).GetDefinition(); var tokenOfFirstMethod = typeInfo.MetadataToken; syntaxTree = Binder.Decompiler.Decompile(tokenOfFirstMethod); } else { syntaxTree = Binder.Decompiler.DecompileType(name); } StringWriter w = new StringWriter(); CustomOutputVisitor outVisitor; outVisitor = new BlittableOutputVisitor(isNested, w, Binder.DecompilerSetting.CSharpFormattingOptions); syntaxTree.AcceptVisitor(outVisitor); if (!isNested) { RefNameSpace.UnionWith(outVisitor.nestedUsing); foreach (var ns in RefNameSpace) { if (!string.IsNullOrEmpty(ns)) { CS.Writer.WriteHead($"using {ns}"); } } } var txt = w.ToString(); CS.Writer.WriteLine(txt, false); } if (genType.IsStruct()) { foreach (var f in genType.Fields) { var fType = f.FieldType.Resolve(); if (fType != null && !fType.IsPublic && !fType.IsNested) { Binder.AddType(fType); } } if (!string.IsNullOrEmpty(genType.Namespace)) { CS.Writer.Start($"namespace {genType.Namespace}"); } var classDefine = $"public partial struct {genType.Name}"; CS.Writer.Start(classDefine); GenNested(); foreach (var p in properties) { p.Gen(); } foreach (var m in methods) { m.Gen(); } } }
public void UpdateTestClass(ITypeDefinition typeDefinition) { fullTypeName = typeDefinition.FullTypeName; if (this.NestedTestsInitialized) { int baseClassIndex = 0; foreach (IType baseType in typeDefinition.GetNonInterfaceBaseTypes()) { ITypeDefinition baseTypeDef = baseType.GetDefinition(); // Check that the base type isn't equal to System.Object or the current class itself if (baseTypeDef == null || baseTypeDef == typeDefinition || baseTypeDef.KnownTypeCode == KnownTypeCode.Object) continue; if (baseTypeDef.DeclaringTypeDefinition != null) continue; // we only support inheriting from top-level classes var baseClassName = baseTypeDef.FullTypeName; if (baseClassIndex < baseClassNames.Count && baseClassName == baseClassNames[baseClassIndex]) { // base class is already in the list, just keep it baseClassIndex++; } else { // base class is not in the list, or the remaining portion of the list differs // remove remaining portion of the list: RemoveBaseClasses(baseClassIndex); // Add new base class: parentProject.RegisterInheritedClass(baseClassName, this); baseClassNames.Add(baseClassName); baseClassIndex++; } } HashSet<ITest> newOrUpdatedNestedTests = new HashSet<ITest>(); // Update nested test classes: foreach (ITypeDefinition nestedClass in typeDefinition.NestedTypes) { if (!NUnitTestFramework.IsTestClass(nestedClass)) continue; NUnitTestClass nestedTestClass = FindNestedTestClass(nestedClass.Name, nestedClass.TypeParameterCount); if (nestedTestClass != null) { nestedTestClass.UpdateTestClass(nestedClass); } else { nestedTestClass = new NUnitTestClass(parentProject, nestedClass.FullTypeName); this.NestedTestCollection.Add(nestedTestClass); } newOrUpdatedNestedTests.Add(nestedTestClass); } // Get methods (not operators etc.) foreach (IMethod method in typeDefinition.GetMethods(m => m.SymbolKind == SymbolKind.Method)) { if (!NUnitTestFramework.IsTestMethod(method)) continue; IUnresolvedMethod unresolvedMethod = (IUnresolvedMethod)method.UnresolvedMember; string methodNameWithDeclaringType; FullTypeName derivedFixture; if (method.DeclaringTypeDefinition == typeDefinition) { derivedFixture = default(FullTypeName); // method is not inherited methodNameWithDeclaringType = method.Name; } else { if (method.DeclaringTypeDefinition == null) continue; derivedFixture = fullTypeName; // method is inherited methodNameWithDeclaringType = method.DeclaringTypeDefinition.Name + "." + method.Name; } NUnitTestMethod testMethod; if (method.IsOverride) { testMethod = FindTestMethodWithShortName(method.Name); } else { testMethod = FindTestMethod(methodNameWithDeclaringType); } if (testMethod != null) { testMethod.UpdateTestMethod(unresolvedMethod, derivedFixture); } else { testMethod = new NUnitTestMethod(parentProject, unresolvedMethod, derivedFixture); this.NestedTestCollection.Add(testMethod); } newOrUpdatedNestedTests.Add(testMethod); } // Remove all tests that weren't contained in the new type definition anymore: this.NestedTestCollection.RemoveAll(t => !newOrUpdatedNestedTests.Contains(t)); } }
/// <summary> /// Creates a new GetClassTypeReference that searches a top-level type in the specified assembly. /// </summary> /// <param name="assembly">A reference to the assembly containing this type. /// If this parameter is null, the GetClassTypeReference will search in all assemblies belonging to the ICompilation.</param> /// <param name="namespaceName">The namespace name containing the type, e.g. "System.Collections.Generic".</param> /// <param name="name">The name of the type, e.g. "List".</param> /// <param name="typeParameterCount">The number of type parameters, (e.g. 1 for List<T>).</param> public GetClassTypeReference(IAssemblyReference assembly, string namespaceName, string name, int typeParameterCount = 0) { this.assembly = assembly; this.fullTypeName = new TopLevelTypeName(namespaceName, name, typeParameterCount); }
/// <summary> /// Creates a new GetClassTypeReference that searches a type definition. /// </summary> /// <param name="fullTypeName">The full name of the type.</param> /// <param name="assembly">A reference to the assembly containing this type. /// If this parameter is null, the GetClassTypeReference will search in all /// assemblies belonging to the compilation. /// </param> public GetClassTypeReference(FullTypeName fullTypeName, IAssemblyReference assembly = null) { this.fullTypeName = fullTypeName; this.assembly = assembly; }
/// <summary> /// Looks for the specified type in all the projects in the open solution /// excluding the current project. /// </summary> static IProject FindProjectContainingType(FullTypeName type) { IProject currentProject = SD.ProjectService.CurrentProject; if (currentProject == null) return null; foreach (IProject project in SD.ProjectService.CurrentSolution.Projects.Where(p => p != currentProject)) { if (project.ProjectContent.TopLevelTypeDefinitions.Any(t => t.FullTypeName == type)) { SD.Log.Debug("Found project containing type: " + project.FileName); return project; } } return null; }
public AstType ConvertType(FullTypeName fullTypeName) { if (resolver != null) { foreach (var asm in resolver.Compilation.Assemblies) { var def = asm.GetTypeDefinition(fullTypeName); if (def != null) { return ConvertType(def); } } } TopLevelTypeName top = fullTypeName.TopLevelTypeName; AstType type; if (string.IsNullOrEmpty(top.Namespace)) { type = new SimpleType(top.Name); } else { type = new SimpleType(top.Namespace).MemberType(top.Name); } for (int i = 0; i < fullTypeName.NestingLevel; i++) { type = type.MemberType(fullTypeName.GetNestedTypeName(i)); } return type; }
MSpecTestClass GetMSpecTestClass(FullTypeName fullTypeName) { return(GetTestClass(fullTypeName.TopLevelTypeName) as MSpecTestClass); }
static void SelectedToolUsedHandler(object sender, EventArgs e) { SD.Log.Debug("SelectedToolUsedHandler"); SideTab tab = sideBar.ActiveTab; // try to add project reference if (sender is ICSharpCode.FormsDesigner.Services.ToolboxService) { ToolboxItem selectedItem = ((IToolboxService)sender).GetSelectedToolboxItem(); if (tab is CustomComponentsSideTab) { if (selectedItem != null && selectedItem.TypeName != null) { SD.Log.Debug("Checking for reference to CustomComponent: " + selectedItem.TypeName); // Check current project has the custom component first. ICompilation currentCompilation = GetCompilationForCurrentProject(); var typeName = new FullTypeName(selectedItem.TypeName); if (currentCompilation != null && currentCompilation.FindType(typeName).Kind == TypeKind.Unknown) { // Check other projects in the solution. SD.Log.Debug("Checking other projects in the solution."); IProject projectContainingType = FindProjectContainingType(typeName); if (projectContainingType != null) { AddProjectReferenceToProject(SD.ProjectService.CurrentProject, projectContainingType); } } } } else { if (selectedItem != null && selectedItem.AssemblyName != null) { IProject currentProject = ProjectService.CurrentProject; if (currentProject != null) { if (!ProjectContainsReference(currentProject, selectedItem.AssemblyName)) { AddReferenceToProject(currentProject, selectedItem.AssemblyName); } } } } } if (tab.Items.Count > 0) { tab.ChosenItem = tab.Items[0]; } sideBar.Refresh(); }
protected IType FindType(string type) { var fieldTypeName = new FullTypeName(type); return typeDefinition.Compilation.FindType(fieldTypeName); }
public NUnitTestClass GetTestClass(FullTypeName fullTypeName) { var testClass = (NUnitTestClass)base.GetTestClass(fullTypeName.TopLevelTypeName); int tpc = fullTypeName.TopLevelTypeName.TypeParameterCount; for (int i = 0; i < fullTypeName.NestingLevel; i++) { if (testClass == null) break; tpc += fullTypeName.GetNestedTypeAdditionalTypeParameterCount(i); testClass = testClass.FindNestedTestClass(fullTypeName.GetNestedTypeName(i), tpc); } return testClass; }
public override object Visit (TypeExpression typeExpression) { var result = new FullTypeName (); if (typeExpression.Type != null) { result.AddChild (new Identifier (typeExpression.Type.Name, Convert (typeExpression.Location))); } // if (!string.IsNullOrEmpty (typeExpression.)) { // result.AddChild (new Identifier (typeExpression.Namespace + "." + typeExpression.Name, Convert (typeExpression.Location))); // } else { // result.AddChild (new Identifier (typeExpression.Name, Convert (typeExpression.Location))); // } return result; }
public void RemoveInheritedClass(FullTypeName baseClassName, NUnitTestClass inheritedClass) { inheritedTestClasses.Remove(baseClassName.TopLevelTypeName, inheritedClass); }
private async Task <Document> DecompileSymbolAsync(Document temporaryDocument, ISymbol symbol, CancellationToken cancellationToken) { // Get the name of the type the symbol is in var containingOrThis = symbol.GetContainingTypeOrThis(); var fullName = GetFullReflectionName(containingOrThis); var compilation = await temporaryDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); string assemblyLocation = null; var isReferenceAssembly = symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass.Name == nameof(ReferenceAssemblyAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName); if (isReferenceAssembly) { try { var fullAssemblyName = symbol.ContainingAssembly.Identity.GetDisplayName(); GlobalAssemblyCache.Instance.ResolvePartialName(fullAssemblyName, out assemblyLocation, preferredCulture: CultureInfo.CurrentCulture); } catch (Exception e) when(FatalError.ReportWithoutCrash(e)) { } } if (assemblyLocation == null) { var reference = compilation.GetMetadataReference(symbol.ContainingAssembly); assemblyLocation = (reference as PortableExecutableReference)?.FilePath; if (assemblyLocation == null) { throw new NotSupportedException(EditorFeaturesResources.Cannot_navigate_to_the_symbol_under_the_caret); } } // Load the assembly. var assemblyDefinition = AssemblyDefinition.ReadAssembly(assemblyLocation, new ReaderParameters() { AssemblyResolver = new RoslynAssemblyResolver(compilation) }); // Initialize a decompiler with default settings. var decompiler = new CSharpDecompiler(assemblyDefinition.MainModule, new DecompilerSettings()); // Escape invalid identifiers to prevent Roslyn from failing to parse the generated code. // (This happens for example, when there is compiler-generated code that is not yet recognized/transformed by the decompiler.) decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers()); var fullTypeName = new FullTypeName(fullName); var decompilerVersion = FileVersionInfo.GetVersionInfo(typeof(CSharpDecompiler).Assembly.Location); // Add header to match output of metadata-only view. // (This also makes debugging easier, because you can see which assembly was decompiled inside VS.) var header = $"#region {FeaturesResources.Assembly} {assemblyDefinition.FullName}" + Environment.NewLine + $"// {assemblyDefinition.MainModule.FileName}" + Environment.NewLine + $"// Decompiled with ICSharpCode.Decompiler {decompilerVersion.FileVersion}" + Environment.NewLine + "#endregion" + Environment.NewLine; // Try to decompile; if an exception is thrown the caller will handle it var text = decompiler.DecompileTypeAsString(fullTypeName); return(temporaryDocument.WithText(SourceText.From(header + text))); }
/// <summary> /// Gets the attributes of the specified attribute type (or derived attribute types). /// </summary> /// <param name="entity">The entity on which the attributes are declared.</param> /// <param name="attributeType">The attribute type to look for.</param> /// <param name="inherit"> /// Specifies whether attributes inherited from base classes and base members (if the given <paramref name="entity"/> in an <c>override</c>) /// should be returned. The default is <c>true</c>. /// </param> /// <returns> /// Returns the list of attributes that were found. /// If inherit is true, attributes from the entity itself are returned first; followed by attributes inherited from the base entity. /// </returns> public static IEnumerable<IAttribute> GetAttributes(this IEntity entity, FullTypeName attributeType, bool inherit = true) { if (entity == null) throw new ArgumentNullException("entity"); return GetAttributes(entity, attrType => { ITypeDefinition typeDef = attrType.GetDefinition(); return typeDef != null && typeDef.FullTypeName == attributeType; }, inherit); }
/// <summary> /// Creates a new GetClassTypeReference that searches a type definition. /// </summary> /// <param name="fullTypeName">The full name of the type.</param> /// <param name="assembly">A reference to the assembly containing this type. /// If this parameter is null, the GetClassTypeReference will search in all /// assemblies belonging to the compilation. /// </param> public GetClassTypeReference(FullTypeName fullTypeName, IAssemblyReference assembly = null) { this.fullTypeName = fullTypeName; this.assembly = assembly; }
MSTestClass GetMSTestClass(FullTypeName fullTypeName) { return GetTestClass(fullTypeName.TopLevelTypeName) as MSTestClass; }
/// <summary> /// Creates a new GetClassTypeReference that searches a type definition. /// </summary> /// <param name="fullTypeName">The full name of the type.</param> /// <param name="module">A reference to the module containing this type. /// If this parameter is null, the GetClassTypeReference will search in all /// assemblies belonging to the compilation. /// </param> public GetClassTypeReference(FullTypeName fullTypeName, IModuleReference module = null, bool?isReferenceType = null) { this.fullTypeName = fullTypeName; this.module = module; this.isReferenceType = isReferenceType; }
public override object Visit (SimpleName simpleName) { var result = new FullTypeName (); result.AddChild (new Identifier (simpleName.Name, Convert (simpleName.Location)), FullTypeName.Roles.Identifier); if (simpleName.TypeArguments != null) { var location = LocationsBag.GetLocations (simpleName); if (location != null) result.AddChild (new CSharpTokenNode (Convert (location[0]), 1), FullTypeName.Roles.LChevron); // AddTypeArguments (result, location, simpleName.TypeArguments); if (location != null && location.Count > 1) result.AddChild (new CSharpTokenNode (Convert (location[1]), 1), FullTypeName.Roles.RChevron); } return result; }
/// <summary> /// Updates the parse information. /// </summary> public void Update(IList <IUnresolvedTypeDefinition> oldFile, IList <IUnresolvedTypeDefinition> newFile) { List <ITypeDefinitionModel> oldModels = null; List <ITypeDefinitionModel> newModels = null; bool[] oldTypeDefHandled = null; if (oldFile.Count > 0) { oldTypeDefHandled = new bool[oldFile.Count]; } foreach (var newPart in newFile) { FullTypeName newFullTypeName = newPart.FullTypeName; TypeDefinitionModel model; if (dict.TryGetValue(newFullTypeName.TopLevelTypeName, out model)) { // Existing type changed // Find a matching old part: IUnresolvedTypeDefinition oldPart = null; if (oldTypeDefHandled != null) { for (int i = 0; i < oldTypeDefHandled.Length; i++) { if (oldTypeDefHandled[i]) { continue; } if (oldFile[i].FullTypeName == newFullTypeName) { oldTypeDefHandled[i] = true; oldPart = oldFile[i]; break; } } } model.Update(oldPart, newPart); } else { // New type added model = new TypeDefinitionModel(context, newPart); dict.Add(newFullTypeName.TopLevelTypeName, model); if (newModels == null) { newModels = new List <ITypeDefinitionModel>(); } newModels.Add(model); } } // Remove all old parts that weren't updated: if (oldTypeDefHandled != null) { for (int i = 0; i < oldTypeDefHandled.Length; i++) { if (!oldTypeDefHandled[i]) { IUnresolvedTypeDefinition oldPart = oldFile[i]; TopLevelTypeName topLevelTypeName = oldPart.FullTypeName.TopLevelTypeName; TypeDefinitionModel model; if (dict.TryGetValue(topLevelTypeName, out model)) { // Remove the part from the model if (model.Parts.Count > 1) { model.Update(oldPart, null); } else { dict.Remove(topLevelTypeName); if (oldModels == null) { oldModels = new List <ITypeDefinitionModel>(); } oldModels.Add(model); } } } } } // Raise the event if necessary: if (collectionChangedEvent.ContainsHandlers && (oldModels != null || newModels != null)) { IReadOnlyCollection <ITypeDefinitionModel> emptyList = EmptyList <ITypeDefinitionModel> .Instance; collectionChangedEvent.Fire(oldModels ?? emptyList, newModels ?? emptyList); } }