internal string GetFullName(NamespaceDefinitionHandle handle) { Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case. NamespaceData data = GetNamespaceData(handle); return(data.FullName); }
/// <summary> /// Extracts the method signature from the metadata by rid /// </summary> public R2RMethod(byte[] image, MetadataReader mdReader, uint rid, int entryPointId, GenericElementTypes[] instanceArgs, uint[] tok) { Token = _mdtMethodDef | rid; EntryPointRuntimeFunctionId = entryPointId; _mdReader = mdReader; RuntimeFunctions = new List <RuntimeFunction>(); // get the method signature from the MethodDefhandle MethodDefinitionHandle methodDefHandle = MetadataTokens.MethodDefinitionHandle((int)rid); _methodDef = mdReader.GetMethodDefinition(methodDefHandle); Name = mdReader.GetString(_methodDef.Name); BlobReader signatureReader = mdReader.GetBlobReader(_methodDef.Signature); TypeDefinitionHandle declaringTypeHandle = _methodDef.GetDeclaringType(); TypeDefinition declaringTypeDef; while (!declaringTypeHandle.IsNil) { declaringTypeDef = mdReader.GetTypeDefinition(declaringTypeHandle); DeclaringType = mdReader.GetString(declaringTypeDef.Name) + "." + DeclaringType; declaringTypeHandle = declaringTypeDef.GetDeclaringType(); } NamespaceDefinitionHandle namespaceHandle = declaringTypeDef.NamespaceDefinition; while (!namespaceHandle.IsNil) { NamespaceDefinition namespaceDef = mdReader.GetNamespaceDefinition(namespaceHandle); DeclaringType = mdReader.GetString(namespaceDef.Name) + "." + DeclaringType; namespaceHandle = namespaceDef.Parent; } SignatureHeader signatureHeader = signatureReader.ReadSignatureHeader(); IsGeneric = signatureHeader.IsGeneric; GenericParameterHandleCollection genericParams = _methodDef.GetGenericParameters(); _genericParamInstanceMap = new Dictionary <string, GenericInstance>(); int argCount = signatureReader.ReadCompressedInteger(); if (IsGeneric) { argCount = signatureReader.ReadCompressedInteger(); } ReturnType = new SignatureType(ref signatureReader, mdReader, genericParams); ArgTypes = new SignatureType[argCount]; for (int i = 0; i < argCount; i++) { ArgTypes[i] = new SignatureType(ref signatureReader, mdReader, genericParams); } if (IsGeneric && instanceArgs != null && tok != null) { InitGenericInstances(genericParams, instanceArgs, tok); } }
private bool TryGetCategoryFlagsForPrimitiveType(out TypeFlags categoryFlags) { categoryFlags = 0; if (_module != _metadataUnit.Context.SystemModule) { // Primitive types reside in the system module return(false); } NamespaceDefinition namespaceDef = MetadataReader.GetNamespaceDefinition(_typeDefinition.NamespaceDefinition); if (namespaceDef.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition) { // Primitive types are in the System namespace the parent of which is the root namespace return(false); } if (!namespaceDef.Name.StringEquals("System", MetadataReader)) { // Namespace name must be 'System' return(false); } NamespaceDefinitionHandle parentNamespaceDefHandle = namespaceDef.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(MetadataReader); NamespaceDefinition parentDef = MetadataReader.GetNamespaceDefinition(parentNamespaceDefHandle); if (parentDef.ParentScopeOrNamespace.HandleType != HandleType.ScopeDefinition) { // The root parent namespace should have scope (assembly) handle as its parent return(false); } return(s_primitiveTypes.TryGetValue(Name, out categoryFlags)); }
public void NamespaceKinds() { var full = NamespaceDefinitionHandle.FromFullNameOffset(123); Assert.False(full.IsVirtual); Assert.Equal(123, full.GetHeapOffset()); Assert.Equal(full, (Handle)full); Assert.Equal(full, (NamespaceDefinitionHandle)(Handle)full); Assert.Equal(0x7C, ((Handle)full).VType); Assert.Equal(123, ((Handle)full).Offset); var virtual1 = NamespaceDefinitionHandle.FromVirtualIndex(123); Assert.True(virtual1.IsVirtual); Assert.Equal(virtual1, (Handle)virtual1); Assert.Equal(virtual1, (NamespaceDefinitionHandle)(Handle)virtual1); Assert.Equal(0xFC, ((Handle)virtual1).VType); Assert.Equal(123, ((Handle)virtual1).Offset); var virtual2 = NamespaceDefinitionHandle.FromVirtualIndex(uint.MaxValue >> 3); Assert.True(virtual2.IsVirtual); Assert.Equal(virtual2, (Handle)virtual2); Assert.Equal(virtual2, (NamespaceDefinitionHandle)(Handle)virtual2); Assert.Equal(0xFC, ((Handle)virtual2).VType); Assert.Equal((int)(uint.MaxValue >> 3), ((Handle)virtual2).Offset); Assert.Throws <BadImageFormatException>(() => NamespaceDefinitionHandle.FromVirtualIndex((uint.MaxValue >> 3) + 1)); }
/// <summary> /// Loops through all type definitions in metadata, adding them to the given table /// </summary> private void PopulateTableWithTypeDefinitions(Dictionary <NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var typeHandle in _metadataReader.TypeDefinitions) { TypeDefinition type = _metadataReader.GetTypeDefinition(typeHandle); if (type.Attributes.IsNested()) { continue; } NamespaceDefinitionHandle namespaceHandle = _metadataReader.TypeDefTable.GetNamespace(typeHandle); NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.TypeDefinitions.Add(typeHandle); } else { StringHandle name = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, name, fullName); newData.TypeDefinitions.Add(typeHandle); table.Add(namespaceHandle, newData); } } }
/// <summary> /// This will return a StringHandle for the simple name of a namespace name at the given segment index. /// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number /// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace /// name between dots. /// /// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle': /// /// reader.GetString(GetSimpleName(handle)) == "Test" /// reader.GetString(GetSimpleName(handle, 0)) == "System" /// reader.GetString(GetSimpleName(handle, 1)) == "Collections" /// reader.GetString(GetSimpleName(handle, 2)) == "Generic" /// reader.GetString(GetSimpleName(handle, 3)) == "Test" /// reader.GetString(GetSimpleName(handle, 1000)) == "Test" /// </summary> private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue) { StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName(); Debug.Assert(!handleContainingSegment.IsVirtual); int lastFoundIndex = fullNamespaceHandle.GetHeapOffset() - 1; int currentSegment = 0; while (currentSegment < segmentIndex) { int currentIndex = _metadataReader.StringStream.IndexOfRaw(lastFoundIndex + 1, '.'); if (currentIndex == -1) { break; } lastFoundIndex = currentIndex; ++currentSegment; } Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0); // + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way, // we want the next char. int resultIndex = lastFoundIndex + 1; return StringHandle.FromOffset(resultIndex).WithDotTermination(); }
/// <summary> /// Loops through all type forwarders in metadata, adding them to the given table /// </summary> private void PopulateTableWithExportedTypes(Dictionary <NamespaceDefinitionHandle, NamespaceDataBuilder> table) { Debug.Assert(table != null); foreach (var exportedTypeHandle in _metadataReader.ExportedTypes) { ExportedType exportedType = _metadataReader.GetExportedType(exportedTypeHandle); if (exportedType.Implementation.Kind == HandleKind.ExportedType) { continue; // skip nested exported types. } NamespaceDefinitionHandle namespaceHandle = exportedType.Namespace; NamespaceDataBuilder builder; if (table.TryGetValue(namespaceHandle, out builder)) { builder.ExportedTypes.Add(exportedTypeHandle); } else { Debug.Assert(namespaceHandle.HasFullName); StringHandle simpleName = GetSimpleName(namespaceHandle); string fullName = _metadataReader.GetString(namespaceHandle); var newData = new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); newData.ExportedTypes.Add(exportedTypeHandle); table.Add(namespaceHandle, newData); } } }
public static String ToNamespaceName(this NamespaceDefinitionHandle namespaceDefinitionHandle, MetadataReader reader) { String ns = ""; for (;;) { NamespaceDefinition currentNamespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(reader); String name = currentNamespaceDefinition.Name.GetStringOrNull(reader); if (name != null) { if (ns.Length != 0) { ns = "." + ns; } ns = name + ns; } Handle nextHandle = currentNamespaceDefinition.ParentScopeOrNamespace; HandleType handleType = nextHandle.HandleType; if (handleType == HandleType.ScopeDefinition) { break; } if (handleType == HandleType.NamespaceDefinition) { namespaceDefinitionHandle = nextHandle.ToNamespaceDefinitionHandle(reader); continue; } throw new BadImageFormatException(SR.Bif_InvalidMetadata); } return(ns); }
/// <summary> /// This will return a StringHandle for the simple name of a namespace name at the given segment index. /// If no segment index is passed explicitly or the "segment" index is greater than or equal to the number /// of segments, then the last segment is used. "Segment" in this context refers to part of a namespace /// name between dots. /// /// Example: Given a NamespaceDefinitionHandle to "System.Collections.Generic.Test" called 'handle': /// /// reader.GetString(GetSimpleName(handle)) == "Test" /// reader.GetString(GetSimpleName(handle, 0)) == "System" /// reader.GetString(GetSimpleName(handle, 1)) == "Collections" /// reader.GetString(GetSimpleName(handle, 2)) == "Generic" /// reader.GetString(GetSimpleName(handle, 3)) == "Test" /// reader.GetString(GetSimpleName(handle, 1000)) == "Test" /// </summary> private StringHandle GetSimpleName(NamespaceDefinitionHandle fullNamespaceHandle, int segmentIndex = Int32.MaxValue) { StringHandle handleContainingSegment = fullNamespaceHandle.GetFullName(); Debug.Assert(!handleContainingSegment.IsVirtual); int lastFoundIndex = fullNamespaceHandle.Index - 1; int currentSegment = 0; while (currentSegment < segmentIndex) { int currentIndex = _metadataReader.StringStream.IndexOfRaw(lastFoundIndex + 1, '.'); if (currentIndex == -1) { break; } lastFoundIndex = currentIndex; ++currentSegment; } Debug.Assert(lastFoundIndex >= 0 || currentSegment == 0); // + 1 because lastFoundIndex will either "point" to a '.', or will be -1. Either way, // we want the next char. uint resultIndex = (uint)(lastFoundIndex + 1); return(StringHandle.FromIndex(resultIndex).WithDotTermination()); }
public void MergeInto(NamespaceDataBuilder other) { Parent = default(NamespaceDefinitionHandle); other.Namespaces.AddRange(this.Namespaces); other.TypeDefinitions.AddRange(this.TypeDefinitions); other.ExportedTypes.AddRange(this.ExportedTypes); }
/// <summary> /// Enumerate all type definitions within a given namespace. /// </summary> /// <param name="metadataUnit">Metadata unit containing the namespace</param> /// <param name="metadataReader">Metadata reader for the scope metadata</param> /// <param name="namespaceDefinitionHandle">Namespace to enumerate</param> private IEnumerable <MetadataType> GetTypesInNamespace( NativeFormatMetadataUnit metadataUnit, MetadataReader metadataReader, NamespaceDefinitionHandle namespaceDefinitionHandle) { NamespaceDefinition namespaceDefinition = metadataReader.GetNamespaceDefinition(namespaceDefinitionHandle); // First, enumerate all types (including nested) in the current namespace foreach (TypeDefinitionHandle namespaceTypeHandle in namespaceDefinition.TypeDefinitions) { yield return((MetadataType)metadataUnit.GetType(namespaceTypeHandle)); foreach (MetadataType nestedType in GetNestedTypes(metadataUnit, metadataReader, namespaceTypeHandle)) { yield return(nestedType); } } // Second, recurse into nested namespaces foreach (NamespaceDefinitionHandle nestedNamespace in namespaceDefinition.NamespaceDefinitions) { foreach (MetadataType type in GetTypesInNamespace(metadataUnit, metadataReader, nestedNamespace)) { yield return(type); } } }
public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName) { Handle = handle; Name = name; FullName = fullName; Namespaces = ImmutableArray.CreateBuilder <NamespaceDefinitionHandle>(); TypeDefinitions = ImmutableArray.CreateBuilder <TypeDefinitionHandle>(); ExportedTypes = ImmutableArray.CreateBuilder <ExportedTypeHandle>(); }
} // Read public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new NamespaceDefinitionHandle((int)value); handle._Validate(); return(offset); } // Read
private LowLevelDictionary <string, QHandle> CreateCaseInsensitiveTypeDictionary() { // // Collect all of the *non-nested* types and type-forwards. // // The keys are full typenames in lower-cased form. // The value is a tuple containing either a TypeDefinitionHandle or TypeForwarderHandle and the associated Reader // for that handle. // // We do not store nested types here. The container type is resolved and chosen first, then the nested type chosen from // that. If we chose the wrong container type and fail the match as a result, that's too bad. (The desktop CLR has the // same issue.) // LowLevelDictionary <string, QHandle> dict = new LowLevelDictionary <string, QHandle>(); foreach (QScopeDefinition scope in AllScopes) { MetadataReader reader = scope.Reader; ScopeDefinition scopeDefinition = scope.ScopeDefinition; IEnumerable <NamespaceDefinitionHandle> topLevelNamespaceHandles = new NamespaceDefinitionHandle[] { scopeDefinition.RootNamespaceDefinition }; IEnumerable <NamespaceDefinitionHandle> allNamespaceHandles = reader.GetTransitiveNamespaces(topLevelNamespaceHandles); foreach (NamespaceDefinitionHandle namespaceHandle in allNamespaceHandles) { string ns = namespaceHandle.ToNamespaceName(reader); if (ns.Length != 0) { ns = ns + "."; } ns = ns.ToLowerInvariant(); NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader); foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions) { string fullName = ns + typeDefinitionHandle.GetTypeDefinition(reader).Name.GetString(reader).ToLowerInvariant(); QHandle existingValue; if (!dict.TryGetValue(fullName, out existingValue)) { dict.Add(fullName, new QHandle(reader, typeDefinitionHandle)); } } foreach (TypeForwarderHandle typeForwarderHandle in namespaceDefinition.TypeForwarders) { string fullName = ns + typeForwarderHandle.GetTypeForwarder(reader).Name.GetString(reader).ToLowerInvariant(); QHandle existingValue; if (!dict.TryGetValue(fullName, out existingValue)) { dict.Add(fullName, new QHandle(reader, typeForwarderHandle)); } } } } return(dict); }
/// <summary> /// Two distinct namespace handles represent the same namespace if their full names are the same. This /// method merges builders corresponding to such namespace handles. /// </summary> private void PopulateNamespaceTable() { lock (_namespaceTableAndListLock) { if (_namespaceTable != null) { return; } var namespaceBuilderTable = new Dictionary <NamespaceDefinitionHandle, NamespaceDataBuilder>(); // Make sure to add entry for root namespace. The root namespace is special in that even // though it might not have types of its own it always has an equivalent representation // as a nil handle and we don't want to handle it below as dot-terminated synthetic namespace. // We use NamespaceDefinitionHandle.FromIndexOfFullName(0) instead of default(NamespaceDefinitionHandle) so // that we never hand back a handle to the user that doesn't have a typeid as that prevents // round-trip conversion to Handle and back. (We may discover other handle aliases for the // root namespace (any nil/empty string will do), but we need this one to always be there. NamespaceDefinitionHandle rootNamespace = NamespaceDefinitionHandle.FromIndexOfFullName(0); namespaceBuilderTable.Add( rootNamespace, new NamespaceDataBuilder( rootNamespace, rootNamespace.GetFullName(), String.Empty)); PopulateTableWithTypeDefinitions(namespaceBuilderTable); PopulateTableWithExportedTypes(namespaceBuilderTable); Dictionary <string, NamespaceDataBuilder> stringTable; MergeDuplicateNamespaces(namespaceBuilderTable, out stringTable); List <NamespaceDataBuilder> syntheticNamespaces; ResolveParentChildRelationships(stringTable, out syntheticNamespaces); var namespaceTable = new Dictionary <NamespaceDefinitionHandle, NamespaceData>(); foreach (var group in namespaceBuilderTable) { // Freeze() caches the result, so any many-to-one relationships // between keys and values will be preserved and efficiently handled. namespaceTable.Add(group.Key, group.Value.Freeze()); } if (syntheticNamespaces != null) { foreach (var syntheticNamespace in syntheticNamespaces) { namespaceTable.Add(syntheticNamespace.Handle, syntheticNamespace.Freeze()); } } _namespaceTable = namespaceTable; _rootNamespace = namespaceTable[rootNamespace]; } }
internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle) { EnsureNamespaceTableIsPopulated(); NamespaceData result; if (!_namespaceTable.TryGetValue(handle, out result)) { ThrowInvalidHandle(); } return result; }
public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return(new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name), @namespace: definition)); }
Namespace CreateNamespace(NamespaceDefinitionHandle handle) { if (handle.IsNil) { return(GlobalNamespace); } NamespaceDefinition nd = mdReader.GetNamespaceDefinition(handle); return(Populate(new Namespace(this, GetString(nd.Name), Create(nd.Parent)))); }
internal NamespaceChain(MetadataReader reader, NamespaceDefinitionHandle innerMostNamespaceHandle) { NamespaceDefinition currentNamespaceDefinition = innerMostNamespaceHandle.GetNamespaceDefinition(reader); ConstantStringValueHandle currentNameHandle = currentNamespaceDefinition.Name; Handle currentNamespaceHandle = innerMostNamespaceHandle.ToHandle(reader); LowLevelList<String> names = new LowLevelList<String>(); for (; ;) { String name = currentNameHandle.GetStringOrNull(reader); names.Add(name); currentNamespaceHandle = currentNamespaceDefinition.ParentScopeOrNamespace; HandleType handleType = currentNamespaceHandle.HandleType; if (handleType == HandleType.ScopeDefinition) break; if (handleType == HandleType.NamespaceDefinition) { NamespaceDefinitionHandle nsHandle = currentNamespaceHandle.ToNamespaceDefinitionHandle(reader); currentNamespaceDefinition = nsHandle.GetNamespaceDefinition(reader); currentNameHandle = currentNamespaceDefinition.Name; continue; } throw new BadImageFormatException(SR.Bif_InvalidMetadata); } DefiningScope = currentNamespaceHandle.ToScopeDefinitionHandle(reader); int count = names.Count; if (count == 0) { // Every namespace chain has to start with the root namespace. throw new BadImageFormatException(); } else if (count == 1) { // The root namespace. For compat with the desktop, TypeInfo.NameSpaces returns null in this case. NameSpace = null; } else { // Namespace has at least one non-root component. StringBuilder sb = new StringBuilder(); int idx = count - 1; while (idx-- != 0) { String name = names[idx]; if (name == null) throw new BadImageFormatException(); // null namespace fragment found in middle. sb.Append(name); if (idx != 0) sb.Append('.'); } NameSpace = sb.ToString(); } }
internal NamespaceData GetNamespaceData(NamespaceDefinitionHandle handle) { EnsureNamespaceTableIsPopulated(); NamespaceData result; if (!_namespaceTable.TryGetValue(handle, out result)) { ThrowInvalidHandle(); } return(result); }
private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List <string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); }
public bool Equals(NamespaceDefinitionHandle handle, string value) { if (value == null) { Throw.ValueArgumentNull(); } if (handle.HasFullName) { return _reader.StringStream.Equals(handle.GetFullName(), value, _reader.utf8Decoder); } return value == _reader.namespaceCache.GetFullName(handle); }
public void NamespaceKinds() { var full = NamespaceDefinitionHandle.FromFullNameOffset(123); Assert.Equal(NamespaceKind.Plain, full.NamespaceKind); Assert.False(full.IsVirtual); Assert.Equal(123, full.GetHeapOffset()); var synthetic = NamespaceDefinitionHandle.FromSimpleNameOffset(123); Assert.Equal(NamespaceKind.Synthetic, synthetic.NamespaceKind); Assert.False(synthetic.IsVirtual); Assert.Equal(123, synthetic.GetHeapOffset()); }
public bool Equals(NamespaceDefinitionHandle handle, string value, bool ignoreCase) { if (value == null) { Throw.ValueArgumentNull(); } if (handle.HasFullName) { return(_reader.StringHeap.Equals(handle.GetFullName(), value, _reader.UTF8Decoder, ignoreCase)); } return(value == _reader.NamespaceCache.GetFullName(handle)); }
public bool Equals(NamespaceDefinitionHandle handle, string value) { if (value == null) { ThrowValueArgumentNull(); } if (handle.HasFullName) { return(reader.StringStream.Equals(handle.GetFullName(), value, reader.utf8Decoder)); } return(value == reader.namespaceCache.GetFullName(handle)); }
public bool Equals(NamespaceDefinitionHandle handle, string value, bool ignoreCase) { if (value == null) { Throw.ValueArgumentNull(); } if (handle.HasFullName) { return _reader.StringHeap.Equals(handle.GetFullName(), value, _reader.Utf8Decoder, ignoreCase); } return value == _reader.NamespaceCache.GetFullName(handle); }
public NamespaceData( StringHandle name, string fullName, NamespaceDefinitionHandle parent, ImmutableArray<NamespaceDefinitionHandle> namespaceDefinitions, ImmutableArray<TypeDefinitionHandle> typeDefinitions, ImmutableArray<ExportedTypeHandle> exportedTypes) { this.Name = name; this.FullName = fullName; this.Parent = parent; this.NamespaceDefinitions = namespaceDefinitions; this.TypeDefinitions = typeDefinitions; this.ExportedTypes = exportedTypes; }
public NamespaceData( StringHandle name, string fullName, NamespaceDefinitionHandle parent, ImmutableArray <NamespaceDefinitionHandle> namespaceDefinitions, ImmutableArray <TypeDefinitionHandle> typeDefinitions, ImmutableArray <ExportedTypeHandle> exportedTypes) { this.Name = name; this.FullName = fullName; this.Parent = parent; this.NamespaceDefinitions = namespaceDefinitions; this.TypeDefinitions = typeDefinitions; this.ExportedTypes = exportedTypes; }
protected override ReferenceKeyValuePair <string, QualifiedNamespaceDefinition[]> CreateValueFromKey(string key) { ArrayBuilder <QualifiedNamespaceDefinition> namespaceDefinitions = new ArrayBuilder <QualifiedNamespaceDefinition>(); foreach (QualifiedScopeDefinition qdefinition in _scopes) { MetadataReader metadataReader = qdefinition.MetadataReader; NamespaceDefinitionHandle rootNamespaceHandle = qdefinition.Definition.RootNamespaceDefinition; NamespaceDefinition currentNamespace = metadataReader.GetNamespaceDefinition(rootNamespaceHandle); if (key == "") { namespaceDefinitions.Add(new QualifiedNamespaceDefinition(qdefinition.MetadataUnit, currentNamespace)); // We're done now. } else { string[] components = key.Split('.'); bool found = false; foreach (string namespaceComponent in components) { found = false; foreach (NamespaceDefinitionHandle childNamespaceHandle in currentNamespace.NamespaceDefinitions) { NamespaceDefinition childNamespace = metadataReader.GetNamespaceDefinition(childNamespaceHandle); if (childNamespace.Name.StringEquals(namespaceComponent, metadataReader)) { found = true; currentNamespace = childNamespace; break; } } if (!found) { break; } } if (found) { namespaceDefinitions.Add(new QualifiedNamespaceDefinition(qdefinition.MetadataUnit, currentNamespace)); } } } return(new ReferenceKeyValuePair <System.String, QualifiedNamespaceDefinition[]>(key, namespaceDefinitions.ToArray())); }
private void EmitNamespaceDefinitionName(NamespaceDefinitionHandle namespaceDefHandle) { NamespaceDefinition namespaceDef = _metadataReader.GetNamespaceDefinition(namespaceDefHandle); if (!namespaceDef.ParentScopeOrNamespace.IsNull(_metadataReader) && namespaceDef.ParentScopeOrNamespace.HandleType == HandleType.NamespaceDefinition) { int charsWritten = _outputBuilder.Length; EmitNamespaceDefinitionName(namespaceDef.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(_metadataReader)); if (_outputBuilder.Length - charsWritten > 0) { _outputBuilder.Append('.'); } } EmitString(namespaceDef.Name); }
public NativeFormatModule GetModuleFromNamespaceDefinition(NamespaceDefinitionHandle handle) { while (true) { NamespaceDefinition namespaceDef = _metadataReader.GetNamespaceDefinition(handle); Handle parentScopeOrDefinitionHandle = namespaceDef.ParentScopeOrNamespace; if (parentScopeOrDefinitionHandle.HandleType == HandleType.ScopeDefinition) { return((NativeFormatModule)GetObject(parentScopeOrDefinitionHandle, null)); } else { handle = parentScopeOrDefinitionHandle.ToNamespaceDefinitionHandle(_metadataReader); } } }
public void NamespaceKinds() { var full = NamespaceDefinitionHandle.FromFullNameOffset(123); Assert.False(full.IsVirtual); Assert.Equal(123, full.GetHeapOffset()); var virtual1 = NamespaceDefinitionHandle.FromVirtualIndex(123); Assert.True(virtual1.IsVirtual); var virtual2 = NamespaceDefinitionHandle.FromVirtualIndex((UInt32.MaxValue >> 3)); Assert.True(virtual2.IsVirtual); Assert.Throws <BadImageFormatException>(() => NamespaceDefinitionHandle.FromVirtualIndex((UInt32.MaxValue >> 3) + 1)); }
/// <summary> /// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle, /// as well as the name provided. /// </summary> private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild) { Debug.Assert(realChild.HasFullName); int numberOfSegments = 0; foreach (char c in fullName) { if (c == '.') { numberOfSegments++; } } StringHandle simpleName = GetSimpleName(realChild, numberOfSegments); var namespaceHandle = NamespaceDefinitionHandle.FromIndexOfSimpleName((uint)simpleName.Index); return(new NamespaceDataBuilder(namespaceHandle, simpleName, fullName)); }
public static string GetFullName(this NamespaceDefinitionHandle namespaceHandle, MetadataReader reader) { var nspace = namespaceHandle.GetNamespaceDefinition(reader); if (nspace.Name.IsNull(reader)) { return(null); } var name = nspace.Name.GetConstantStringValue(reader).Value; var containingNamespace = nspace.ParentScopeOrNamespace.IsNull(reader) ? null : nspace.ParentScopeOrNamespace.GetFullName(reader); if (containingNamespace != null) { return(containingNamespace + "." + name); } return(name); }
private static void AppendNamespaceHashCode(ref HashCodeBuilder builder, NamespaceDefinitionHandle namespaceDefHandle, MetadataReader reader) { NamespaceDefinition namespaceDefinition = reader.GetNamespaceDefinition(namespaceDefHandle); Handle parentHandle = namespaceDefinition.ParentScopeOrNamespace; HandleType parentHandleType = parentHandle.HandleType; if (parentHandleType == HandleType.NamespaceDefinition) { AppendNamespaceHashCode(ref builder, parentHandle.ToNamespaceDefinitionHandle(reader), reader); string namespaceNamePart = reader.GetString(namespaceDefinition.Name); builder.Append(namespaceNamePart); builder.Append("."); } else { Debug.Assert(parentHandleType == HandleType.ScopeDefinition); Debug.Assert(String.IsNullOrEmpty(reader.GetString(namespaceDefinition.Name)), "Root namespace with a name?"); } }
internal static string GetNamespaceName(this MetadataReader metadataReader, NamespaceDefinitionHandle namespaceDefinitionHandle) { if (namespaceDefinitionHandle.IsNull(metadataReader)) { return(null); } else { // TODO! Cache this result, or do something to make it more efficient. NamespaceDefinition namespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(metadataReader); string name = metadataReader.GetString(namespaceDefinition.Name) ?? ""; if (namespaceDefinition.ParentScopeOrNamespace.HandleType == HandleType.NamespaceDefinition) { string parentName = metadataReader.GetNamespaceName(namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(metadataReader)); if (!string.IsNullOrEmpty(parentName)) { name = parentName + "." + name; } } return(name); } }
public static bool CompareNamespaceReferenceToDefinition(NamespaceReferenceHandle nr1, MetadataReader mr1, NamespaceDefinitionHandle nd2, MetadataReader mr2) { NamespaceReference nrData1 = mr1.GetNamespaceReference(nr1); NamespaceDefinition ndData2 = mr2.GetNamespaceDefinition(nd2); if (nrData1.Name.IsNull(mr1) != ndData2.Name.IsNull(mr2)) return false; if (!nrData1.Name.IsNull(mr1)) { if (!nrData1.Name.StringEquals(ndData2.Name.GetConstantStringValue(mr2).Value, mr1)) return false; } switch (nrData1.ParentScopeOrNamespace.HandleType) { case HandleType.NamespaceReference: if (ndData2.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition) return false; return CompareNamespaceReferenceToDefinition(nrData1.ParentScopeOrNamespace.ToNamespaceReferenceHandle(mr1), mr1, ndData2.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(mr2), mr2); case HandleType.ScopeReference: if (ndData2.ParentScopeOrNamespace.HandleType != HandleType.ScopeDefinition) return false; return CompareScopeReferenceToDefinition(nrData1.ParentScopeOrNamespace.ToScopeReferenceHandle(mr1), mr1, ndData2.ParentScopeOrNamespace.ToScopeDefinitionHandle(mr2), mr2); default: Debug.Assert(false); throw new BadImageFormatException(); } }
public string GetString(NamespaceDefinitionHandle handle) { if (handle.HasFullName) { return StringStream.GetString(handle.GetFullName(), utf8Decoder); } return namespaceCache.GetFullName(handle); }
public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle) { NamespaceData data = namespaceCache.GetNamespaceData(handle); return new NamespaceDefinition(data); }
private void AddNamespaceParts( NamespaceDefinitionHandle namespaceHandle, List<string> simpleNames) { if (namespaceHandle.IsNil) { return; } var namespaceDefinition = _metadataReader.GetNamespaceDefinition(namespaceHandle); AddNamespaceParts(namespaceDefinition.Parent, simpleNames); simpleNames.Add(_metadataReader.GetString(namespaceDefinition.Name)); }
/// <summary> /// Creates a NamespaceDataBuilder instance that contains a synthesized NamespaceDefinitionHandle, /// as well as the name provided. /// </summary> private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceDefinitionHandle realChild) { Debug.Assert(realChild.HasFullName); int numberOfSegments = 0; foreach (char c in fullName) { if (c == '.') { numberOfSegments++; } } StringHandle simpleName = GetSimpleName(realChild, numberOfSegments); var namespaceHandle = NamespaceDefinitionHandle.FromSimpleNameOffset(simpleName.GetHeapOffset()); return new NamespaceDataBuilder(namespaceHandle, simpleName, fullName); }
private Mapping<NamespaceDefinitionHandle> MapNamespaceDefinitionImpl(NamespaceDefinitionHandle handle) { throw new NotImplementedException(); }
/// <summary> /// Helper method that will validate that a NamespaceDefinition (and all NamespaceDefinitions considered children /// of it) report correct values for their child namespaces, types, etc. All namespaces in the module are expected /// to be listed in the allNamespaces array. Additionally, the global namespace is expected to have type definitions /// for GlobalClassA, GlobalClassB, and Module. No type forwarder declarations are expected. /// /// All namespaces that aren't the global NS are expected to have type definitions equal to the array /// @namespaceName.Split('.') /// So, ns1.Ns2.NS3 is expected to have type definitions /// {"ns1", "Ns2", "NS3"}. /// /// definitionExceptions and forwarderExceptions may be used to override the default expectations. Pass in /// namespace (key) and what is expected (list of strings) for each exception. /// </summary> private void ValidateNamespaceChildren( MetadataReader reader, NamespaceDefinitionHandle initHandle, string[] allNamespaces, IReadOnlyDictionary<string, IList<string>> definitionExceptions = null, IReadOnlyDictionary<string, IList<string>> forwarderExceptions = null) { // Don't want to have to deal with null. if (definitionExceptions == null) { definitionExceptions = new Dictionary<string, IList<string>>(); } if (forwarderExceptions == null) { forwarderExceptions = new Dictionary<string, IList<string>>(); } var rootNamespaceDefinition = reader.GetNamespaceDefinition(initHandle); string rootNamespaceName = reader.GetString(initHandle); // We need to be in the table of all namespaces... Assert.Contains(rootNamespaceName, allNamespaces); // Cool. Now check to make sure that .Name only returns the last bit of our namespace name. var expNamespaceNameSegment = rootNamespaceName.Split('.').Last(); var rootNamespaceNameSegment = reader.GetString(rootNamespaceDefinition.Name); Assert.Equal(expNamespaceNameSegment, rootNamespaceNameSegment); bool isGlobalNamespace = rootNamespaceName.Length == 0; string[] expTypeDefinitions = null; // Special case: Global NS has GlobalClassA, GlobalClassB. Others just have autogenerated classes. if (definitionExceptions.ContainsKey(rootNamespaceName)) { expTypeDefinitions = definitionExceptions[rootNamespaceName].ToArray(); } else if (isGlobalNamespace) { expTypeDefinitions = new[] { "GlobalClassA", "GlobalClassB", "<Module>" }; } else { expTypeDefinitions = rootNamespaceName.Split('.'); } // Validating type definitions inside the namespace... int numberOfTypeDefinitions = 0; foreach (var definitionHandle in rootNamespaceDefinition.TypeDefinitions) { var definition = reader.GetTypeDefinition(definitionHandle); var definitionName = reader.GetString(definition.Name); var definitionFullNamespaceName = reader.GetString(definition.Namespace); Assert.Equal(rootNamespaceName, definitionFullNamespaceName); Assert.Contains(definitionName, expTypeDefinitions); numberOfTypeDefinitions += 1; } // Guarantee that there are no extra unexpected members... Assert.Equal(numberOfTypeDefinitions, expTypeDefinitions.Length); string[] expTypeForwarders = null; if (forwarderExceptions.ContainsKey(rootNamespaceName)) { expTypeForwarders = forwarderExceptions[rootNamespaceName].ToArray(); } else { expTypeForwarders = new string[] { }; } int numberOfTypeForwarders = 0; foreach (var forwarderHandle in rootNamespaceDefinition.ExportedTypes) { var forwarder = reader.GetExportedType(forwarderHandle); Assert.True(reader.StringComparer.Equals(forwarder.Namespace, rootNamespaceName)); var forwarderName = reader.GetString(forwarder.Name); Assert.Contains(forwarderName, expTypeForwarders); numberOfTypeForwarders += 1; } Assert.Equal(expTypeForwarders.Length, numberOfTypeForwarders); // Validate sub-namespaces // If the last index of '.' in a namespace name is == the current name's length, then // that ns is a direct child of the current one! IList<String> expChildren = null; // Special case: Global NS's children won't have .s in them. if (isGlobalNamespace) { expChildren = allNamespaces.Where(ns => !String.IsNullOrEmpty(ns) && !ns.Contains('.')).ToList(); } else { expChildren = allNamespaces .Where(ns => ns.StartsWith(rootNamespaceName) && ns.LastIndexOf('.') == rootNamespaceName.Length) .ToList(); } int numberOfSubNamespaces = 0; foreach (var subNamespaceHandle in rootNamespaceDefinition.NamespaceDefinitions) { Assert.False(subNamespaceHandle.IsNil); string subNamespaceFullName = reader.GetString(subNamespaceHandle); NamespaceDefinition subNamespace = reader.GetNamespaceDefinition(subNamespaceHandle); string subNamespaceName = subNamespaceFullName.Split('.').Last(); Assert.Equal(subNamespaceName, reader.GetString(subNamespace.Name)); Assert.True(reader.StringComparer.Equals(subNamespace.Name, subNamespaceName)); Assert.True(reader.StringComparer.StartsWith(subNamespace.Name, subNamespaceName)); Assert.True(reader.StringComparer.StartsWith(subNamespace.Name, subNamespaceName.Substring(0, subNamespaceName.Length - 1))); Assert.Equal(subNamespace.Parent, initHandle); Assert.Contains(subNamespaceFullName, expChildren); ValidateNamespaceChildren(reader, subNamespaceHandle, allNamespaces, definitionExceptions, forwarderExceptions); numberOfSubNamespaces += 1; } // Guarantee no extra unexpected namespaces... Assert.Equal(expChildren.Count, numberOfSubNamespaces); }
public NamespaceDataBuilder(NamespaceDefinitionHandle handle, StringHandle name, string fullName) { Handle = handle; Name = name; FullName = fullName; Namespaces = ImmutableArray.CreateBuilder<NamespaceDefinitionHandle>(); TypeDefinitions = ImmutableArray.CreateBuilder<TypeDefinitionHandle>(); ExportedTypes = ImmutableArray.CreateBuilder<ExportedTypeHandle>(); }
public void MergeInto(NamespaceDataBuilder other) { Parent = default(NamespaceDefinitionHandle); other.Namespaces.AddRange(this.Namespaces); other.TypeDefinitions.AddRange(this.TypeDefinitions); other.ExportedTypes.AddRange(this.ExportedTypes); }
private static LowLevelDictionary<String, QHandle> CreateCaseInsensitiveTypeDictionary(RuntimeAssembly assembly) { // // Collect all of the *non-nested* types and type-forwards. // // The keys are full typenames in lower-cased form. // The value is a tuple containing either a TypeDefinitionHandle or TypeForwarderHandle and the associated Reader // for that handle. // // We do not store nested types here. The container type is resolved and chosen first, then the nested type chosen from // that. If we chose the wrong container type and fail the match as a result, that's too bad. (The desktop CLR has the // same issue.) // ReflectionDomain reflectionDomain = assembly.ReflectionDomain; LowLevelDictionary<String, QHandle> dict = new LowLevelDictionary<string, QHandle>(); foreach (QScopeDefinition scope in assembly.AllScopes) { MetadataReader reader = scope.Reader; ScopeDefinition scopeDefinition = scope.ScopeDefinition; IEnumerable<NamespaceDefinitionHandle> topLevelNamespaceHandles = new NamespaceDefinitionHandle[] { scopeDefinition.RootNamespaceDefinition }; IEnumerable<NamespaceDefinitionHandle> allNamespaceHandles = reader.GetTransitiveNamespaces(topLevelNamespaceHandles); foreach (NamespaceDefinitionHandle namespaceHandle in allNamespaceHandles) { String ns = namespaceHandle.ToNamespaceName(reader); if (ns.Length != 0) ns = ns + "."; ns = ns.ToLower(); NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader); foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions) { String fullName = ns + typeDefinitionHandle.GetTypeDefinition(reader).Name.GetString(reader).ToLower(); QHandle existingValue; if (!dict.TryGetValue(fullName, out existingValue)) { dict.Add(fullName, new QHandle(reader, typeDefinitionHandle)); } } foreach (TypeForwarderHandle typeForwarderHandle in namespaceDefinition.TypeForwarders) { String fullName = ns + typeForwarderHandle.GetTypeForwarder(reader).Name.GetString(reader).ToLower(); QHandle existingValue; if (!dict.TryGetValue(fullName, out existingValue)) { dict.Add(fullName, new QHandle(reader, typeForwarderHandle)); } } } } return dict; }
public static MetadataDefinition Create( MetadataReader reader, NamespaceDefinitionHandle namespaceHandle) { var definition = reader.GetNamespaceDefinition(namespaceHandle); return new MetadataDefinition( MetadataDefinitionKind.Namespace, reader.GetString(definition.Name)) { Namespace = definition }; }
public bool Equals(NamespaceDefinitionHandle handle, string value) { return Equals(handle, value, ignoreCase: false); }
internal string GetFullName(NamespaceDefinitionHandle handle) { Debug.Assert(!handle.HasFullName); // we should not hit the cache in this case. NamespaceData data = GetNamespaceData(handle); return data.FullName; }
public Mapping<NamespaceDefinitionHandle> MapNamespaceDefinition(NamespaceDefinitionHandle handle) { return _namespaceDefinitions.GetOrAdd(handle, MapNamespaceDefinitionImpl); }
public string GetString(NamespaceDefinitionHandle handle) { if (handle.HasFullName) { return StringHeap.GetString(handle.GetFullName(), UTF8Decoder); } return NamespaceCache.GetFullName(handle); }