Skip to content

Improve mutable struct detection #12430

Closed

Description

Summary of the new feature/enhancement

When assigning a struct to a variable, some checks are done to determine if the struct is mutable. The current code path checks if there are:

  1. Any public instance fields
  2. Any public instance properties with a set accessor
  3. Any public instance methods

This can be simplified by checking if the struct is decorated with the IsReadOnlyAttribute. This would allow PS to assume any struct that wasn't declared explicitly as read only with the C# readonly modifier (SharpLab example) to be mutable. This would also probably result in less false positives because most structs have a public field (even if initonly) or a public method, even these explicitly readonly structs.

Proposed technical implementation details (optional)

This method:

internal static bool IsValueTypeMutable(Type type)
{
if (type.IsPrimitive || type.IsEnum)
{
return false;
}
// If there are any fields, the type is mutable.
if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Any())
{
return true;
}
// If there are any properties with setters, the type is mutable.
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
for (int index = 0; index < properties.Length; index++)
{
var property = properties[index];
if (property.CanWrite)
{
return true;
}
}
// If there are any methods other than the property getters, the type might
// be mutable, so assume the type is mutable.
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
if (methods.Length != properties.Length)
{
return true;
}
return false;
}

Should be changed like this:

diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs
index b54fbdfd5..7a0254ccb 100644
--- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs
+++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs
@@ -2034,32 +2034,7 @@ namespace System.Management.Automation.Language
                 return false;
             }
 
-            // If there are any fields, the type is mutable.
-            if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Any())
-            {
-                return true;
-            }
-
-            // If there are any properties with setters, the type is mutable.
-            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
-            for (int index = 0; index < properties.Length; index++)
-            {
-                var property = properties[index];
-                if (property.CanWrite)
-                {
-                    return true;
-                }
-            }
-
-            // If there are any methods other than the property getters, the type might
-            // be mutable, so assume the type is mutable.
-            var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
-            if (methods.Length != properties.Length)
-            {
-                return true;
-            }
-
-            return false;
+            return !type.IsDefined<System.Runtime.CompilerServices.IsReadOnlyAttribute>();
         }
 
         private static readonly ConcurrentDictionary<Type, bool> s_mutableValueTypesWithInstanceMembers =

Related issue #12411

/cc Michael Klement (@mklement0)

Activity

  1. added
    Issue-Enhancement
    on Apr 22, 2020
  2. added
    WG-Engine
    on Apr 23, 2020
  3. iSazonov commented on Apr 23, 2020

    @iSazonov
    Collaborator

    We need to compare performance - IsDefined() method may be too costly.

  4. SeeminglyScience commented on Apr 23, 2020

    @SeeminglyScience
    ContributorAuthor

    True, though I would be very surprised if it was slower than all of the other reflection calls it would replace.

  5. iSazonov commented on Apr 23, 2020

    @iSazonov
    Collaborator

    I don't see using IsReadOnlyAttribute in .Net Runtime repo https://github.com/dotnet/runtime/search?l=C%23&q=IsReadOnlyAttribute

  6. SeeminglyScience commented on Apr 23, 2020

    @SeeminglyScience
    ContributorAuthor

    Check out the right hand side of this SharpLab example. When a struct has the readonly modifier applied to it, it is decorated with that attribute.

  7. SeeminglyScience commented on Apr 23, 2020

    @SeeminglyScience
    ContributorAuthor

    Eh complicating it a bit is that the attribute isn't in netstandard2.0. Libraries that target netstandard2.0 will turn this:

    public readonly struct MyStruct { }

    into

    namespace System.Runtime.CompilerServices
    {
        [EditorBrowsable(EditorBrowsableState.Never)]
        [AttributeUsage(AttributeTargets.All, Inherited = false)]
        internal sealed class IsReadOnlyAttribute : Attribute
        {
        }
    }
    
    [IsReadOnly]
    public struct MyStruct { }

    That makes it a little bit more tricky, and may need to match based on type full name:

    foreach (Attribute attribute in type.GetCustomAttributes(inherit: false))
    {
        if (attribute.GetType().FullName.Equals("System.Runtime.CompilerServices.IsReadOnlyAttribute", StringComparison.Ordinal))
        {
            return true;
        }
    }

    That makes performance more of a concern, but it still replaces a lot of reflection calls so hopefully performance is very similar if not better. Either way, it's cached statically per type so I believe it's worth it.

  8. iSazonov commented on Apr 23, 2020

    @iSazonov
    Collaborator

    the attribute isn't in netstandard2.0

    .Net runtime does not address the issue in IsDefine()?

  9. SeeminglyScience commented on Apr 23, 2020

    @SeeminglyScience
    ContributorAuthor

    So because the attribute isn't in netstandard2.0, roslyn adds the code to define it as an internal type within the library declaring a readonly struct.

    So if my module declares a readonly struct while targeting netstandard2.0, it'll be decorated with System.Runtime.CompilerServices.IsReadOnlyAttribute, MyModuleAssembly not System.Runtime.CompilerServices.IsReadOnlyAttribute, System.Private.CoreLib

  10. iSazonov commented on Apr 23, 2020

    @iSazonov
    Collaborator

    I guess IsDefine() knows about this?

  11. SeeminglyScience commented on Apr 23, 2020

    @SeeminglyScience
    ContributorAuthor

    Hmm not sure what you mean. Can't use that method because it only takes a Type object, which has assembly identity built into it.

  12. iSazonov commented on Apr 23, 2020

    @iSazonov
    Collaborator

    I guess IsDefined() understand custom IsReadOnlyAttribute() and I hope we have no need a workaround.

  13. iSazonov commented on Apr 23, 2020

    @iSazonov
  14. SeeminglyScience commented on Apr 23, 2020

    @SeeminglyScience
    ContributorAuthor

    That's a different attribute from IsReadOnlyAttribute.

    If IsDefined accounted for this scenario it would be lying, and would lose a ton of performance for the typical case. If I pass it a typeref of System.Runtime.CompilerServices.IsReadOnlyAttribute, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e and it returns true for System.Runtime.CompilerServices.IsReadOnlyAttribute, MyRandomAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken= then that would be pretty confusing for any attribute outside of these edge cases. Plus, it would have to just do a full name compare like we're doing here.

  15. iSazonov commented on Apr 23, 2020

    @iSazonov
    Collaborator

    In the case I wonder why the attribute is automatically defined for <netstandard2.0.

  16. 4 remaining items

  17. SeeminglyScience commented on Apr 24, 2020

    @SeeminglyScience
    ContributorAuthor

    Nah you can mark it up for grabs.

  18. added
    Up-for-Grabs
    on Apr 24, 2020
  19. added a commit that references this issue on Aug 10, 2020
    ec25fd6
  20. added a commit that references this issue on Dec 10, 2020
  21. added a commit that references this issue on Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementUp-for-GrabsWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions