private IEnumerable CalculateInternalTypesToPreserve()

in src/Refasmer/Importer/ImportLogic.cs [657:716]


    private IEnumerable<TypeDefinitionHandle> CalculateInternalTypesToPreserve(
        IReadOnlyCollection<TypeDefinitionHandle> importedTypeHandles)
    {
        var preservedTypes = new HashSet<TypeDefinitionHandle>(importedTypeHandles);
        var result = new List<TypeDefinitionHandle>();
        foreach (var importedTypeHandle in importedTypeHandles)
        {
            var candidateTypes = new List<TypeDefinitionHandle>();
            var type = _reader.GetTypeDefinition(importedTypeHandle);
            var collector = new UsedTypeCollector(candidateTypes);

            var parentTypes = new List<EntityHandle>();
            if (!type.BaseType.IsNil) parentTypes.Add(type.BaseType);
            foreach (var interfaceImplHandle in type.GetInterfaceImplementations())
            {
                var interfaceImpl = _reader.GetInterfaceImplementation(interfaceImplHandle);
                parentTypes.Add(interfaceImpl.Interface);
            }

            foreach (var parentTypeHandle in parentTypes)
            {
                switch (parentTypeHandle.Kind)
                {
                    case HandleKind.TypeDefinition:
                        candidateTypes.Add((TypeDefinitionHandle)parentTypeHandle);
                        break;
                    case HandleKind.TypeSpecification:
                        var specification = _reader.GetTypeSpecification((TypeSpecificationHandle)parentTypeHandle);
                        AcceptTypeSignature(specification.Signature, collector);
                        break;
                }
            }

            foreach (var fieldHandle in type.GetFields())
            {
                var field = _reader.GetFieldDefinition(fieldHandle);
                if (Filter == null || Filter.AllowImport(field, _reader))
                    AcceptFieldSignature(field, collector);
            }

            var methodImplementations = GetAllowlistedInterfaceMethodImplementations(type);
            foreach (var methodHandle in type.GetMethods())
            {
                var method = _reader.GetMethodDefinition(methodHandle);
                if (AllowImportMethod(methodImplementations, methodHandle, method))
                    AcceptMethodSignature(method, collector);
            }

            foreach (var typeHandle in candidateTypes)
            {
                if (preservedTypes.Add(typeHandle))
                {
                    result.Add(typeHandle);
                    Debug?.Invoke($"Exposing internal type {_reader.GetFullname(typeHandle)}.");
                }
            }
        }

        return result;
    }