Skip to content

Allow more control on custom type formatting #15100

Closed

Description

@GeeLaw

Summary of the new feature/enhancement

A developer might have created some custom type that aims to behave like a primitive or built-in type, but PowerShell does not provide a way to let the developer precisely control formatting of custom types. In particular, the handling of string is very special --- it implements IEnumerable<char>, but will not be enumerated (into a stream of chars) when formatted. There is no way for a custom type to be handled like a string.

Another example. Currently, System.Text.Rune does not have special handling, and the default formatting is Format-List instead of ToString(). Arguably, ToString() is more appropriate. For a custom type, the only way to force ToString() formatting is to apply System.Management.Automation.HiddenAttribute to all instance fields and properties. However, this comes with the downside of referencing PowerShell in the assembly containing the type, but the assembly should be usable even in an environment without PowerShell (and you don't want to load PowerShell assemblies if you aren't using it anyway).

The closest we can get for Rune (or any other custom type not implementing IEnumerable nor IEnumerator) is to give it a Custom view, but it will add blank lines when outputting. Not ideal...

image

This issue aims to generate discussion on creating mechanisms to have fine-grained control over (default) formatting of a type. Related #9538.

Proposed technical implementation details (optional)

Here is a simple proposal.

  • Decouple Out-Default into Format-Default and Out-Host. Today's PowerShell handles Out-Default monolithically. It chooses Format-Table or Format-List or ToString()-formatting, depending on the number of non-hidden public fields and properties, and then applies Out-Host.
  • In Format.ps1xml, allow a new type of NativeControl. It specifies a type name, which, if found in loaded assemblies, is used to format the object.
  • Format-Default chooses the format as follows:
    1. If there is a view defined for this type, use the first available view (which does not have to be NativeControl view). However, if NativeControl formatter was used to produce the object being formatted (formatting is recursive for NativeControl views), then NativeControl is skipped.
    2. Otherwise, use today's default formatting choice. (Special handling for string; use ToString() if there is no non-hidden public fields or properties; use Format-Table if there are only a few; use Format-List if there are many.)

Make the types in Microsoft.PowerShell.Commands.Internal.Format public, so people can create custom format objects. Provide a new abstract class:

// or another namespace?
namespace System.Management.Automation
{
  // The derived class must be stateless, so that
  // only one instance is created per PowerShell runspace.
  public abstract class NativeFormatter
  {
    // The returned object is recursively formatted,
    // but cannot be sent to the same formatter again.
    public abstract object FormatObject(object obj);
  }
}

For example, suppose we have a custom string class AsciiString, then we can create

public sealed class AsciiStringFormatter : NativeFormatter
{
  public override object FormatObject(object obj) { return ((AsciiString)obj).ToString(); }
}

This will format an AsciiString into a string, which will then be handled by PowerShell natively.

It's also possible to return IEnumerable from FormatObject, which will be expanded by PowerShell, and each resulting object is formatted by their own formatter. Those expanded object could be what is Microsoft.PowerShell.Commands.Internal.Format.GroupEntryData today.

Why it is important that we implement formatting in another class.

  • First, we don't want the main assembly (e.g., the assembly containing AsciiString) to be tied to PowerShell. By allowing it to be implemented in another class, the author can implement the formatter in a separate assembly dedicated for scripting (a kind of add-on to the main assembly).
  • Second, users (non-developers of the main assembly) can develop their own native formatter if they so wish.

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Mar 25, 2021
  2. mklement0 commented on Mar 27, 2021

    @mklement0
    Contributor

    I may not have the full picture, but at least the System.Text.Rune example can be implemented by combining a CustomControl entry with the OutOfBand element, as follows:

    @'
    <Configuration>
    <ViewDefinitions>
          <View>
              <Name>RuneFormat</Name>
              <OutOfBand />
              <ViewSelectedBy>
                  <TypeName>System.Text.Rune</TypeName>
              </ViewSelectedBy>
              <CustomControl>
                  <CustomEntries>
                      <CustomEntry>
                         <CustomItem>
                              <ExpressionBinding>
                                  <ScriptBlock>
                                  <![CDATA[
      $_.ToString()
                                  ]]>
                                  </ScriptBlock>
                              </ExpressionBinding>
                          </CustomItem>
                      </CustomEntry>
                  </CustomEntries>
              </CustomControl>
          </View>
    </ViewDefinitions>
    </Configuration>
    '@ > ($tmpFile = [IO.Path]::GetTempPath() + "$PID.ps1xml")
    
    # Load the format data and remove the temp. file.
    Update-FormatData -PrependPath $tmpFile; Remove-Item $tmpFile

    Now you get the desired single-line representation with no surrounding blank lines:

    PS> [System.Text.Rune]::new(123)
    {

    To get a standard view, use -Force:

    PS> [System.Text.Rune]::new(123) | Format-List -Force
    
    IsAscii             : True
    IsBmp               : True
    Plane               : 0
    Utf16SequenceLength : 1
    Utf8SequenceLength  : 1
    Value               : 123
    
  3. GeeLaw commented on Mar 27, 2021

    @GeeLaw
    Author

    Michael Klement (@mklement0) Thanks for the pointer! I didn't know OutOfBand (looks like this feature is little documented). This definitely solves the problem for non-enumerable types. Yet the issue for enumerable types still stand.

    Currently, it's not possible to prevent enumeration unless the type is string or the enumeration depth is exhausted.

    @'
    <Configuration><ViewDefinitions><View>
    <Name>MyHashTableFormat</Name>
    <OutOfBand />
    <ViewSelectedBy><TypeName>System.Collections.Hashtable</TypeName></ViewSelectedBy>
    <CustomControl><CustomEntries><CustomEntry><CustomItem><ExpressionBinding><ScriptBlock>
    ConvertTo-Json -InputObject $_ -Compress
    </ScriptBlock></ExpressionBinding></CustomItem></CustomEntry></CustomEntries></CustomControl>
    </View></ViewDefinitions></Configuration>
    '@ > ($tmpFile = [IO.Path]::GetTempPath() + "$PID.ps1xml");
    Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -Force;
    Update-FormatData -PrependPath $tmpFile;
    Remove-Item $tmpFile;
    
    $ht = @{'a' = 1; 'b' = 'c'};
    $array1 = [object[]]@(0);
    $array2 = [object[]]@(0);
    $array1[0] = $ht;
    $array2[0] = $array1;
    
    $array1; # $ht is enumerated
    $array2; # uses the custom format
  4. mklement0 commented on Mar 27, 2021

    @mklement0
    Contributor

    That's a good point, though I wonder if this should be considered a bug: why should a type's explicitly assigned format not be honored - situationally, no less - just because it implements IEnumerable?

  5. vexx32 commented on Mar 27, 2021

    @vexx32
    Collaborator

    Most likely just because the pipeline enumerates before the formatter ever gets a look at it.

  6. mklement0 commented on Mar 27, 2021

    @mklement0
    Contributor

    Rain Sallow (/u/ta11ow) (@vexx32), that's what seems to be happening de facto, but my point was that if you register formatting data for a type explicitly, it should arguably always be honored, whether the type is enumerable or not. As Ji Luo (@GeeLaw)'s example shows, the fact that it is situationally honored - when no enumeration happens to be in the picture - suggests that this is more of a fallout from the implementation than by intentional design.

  7. GeeLaw commented on Mar 27, 2021

    @GeeLaw
    Author

    After a second thought, it really is about controlling whether a type should be perceived as enumerable, not just for formatting. Suppose someone implements AsciiString, then you want [AsciiString]$myAsciiString | foreach { <# blah #> } to not enumerate $myAsciiString.

    By some reverse-engineering on how PowerShell handles string, I came up with this horrifying hack (not intended for production use): https://gist.github.com/GeeLaw/45d87803847195f9ba0f0155e00493e9

    The snippet makes ArrayList mostly non-enumerable.

    • Inject a rule into PSEnumerableBinder to make the enumerator of ArrayList the dummy NonEnumerableObjectEnumerator.
    • Inject a rule into PSPipeWriterBinder to make ArrayList pass through the pipe without being enumerated.
    • Inject a rule into LanguagePrimitives.GetEnumerable to make it appear non-enumerable.

    I'm not sure how to interpret the result of Write-Host. When passed by pipe, the result is ToString(). When passed via InputObject, the result is joined enumerated items (perhaps due to non-overridden ToString?). And certainly Windows PowerShell 5.1 has some weird behavior...

    I think the issue should be changed to a feature request of controlling enumeration behavior of custom types.

    Gist
    Make ArrayList (mostly) non-enumerable for PowerShell. - Use-NonEnumerableArrayList.ps1
  8. mklement0 commented on Mar 27, 2021

    @mklement0
    Contributor

    I think these are two aspects to consider independently:

    • [This may be what you have in mind] Should there be a way to signal to PowerShell that a given type that implements IEnumerable should not be treated as such in the pipeline?

      • Currently, this decision is hard-coded, comprising exceptions that both exclude (String, IDictionary, XmlNode) and include (DataTable)
    • Should formatting data associated with a given type always be honored, irrespective of whether it is enumerable or not? (I think so)

  9. GeeLaw commented on Mar 28, 2021

    @GeeLaw
    Author

    According to the docs, every line of command is equivalent when appended with | Out-Host, so if an object is enumerable, it will only be treated as the enumerated items, not itself.

    When scripting, there really isn't much difference between List<byte> and byte[] (and even object[] with all items being boxed bytes). I wouldn't expect a cmdlet/function that happens to use List as its intermediate storage and direct return value to be formatted differently. But there is a crucial difference between AsciiString : IEnumerable<byte> and byte[]. I would lean towards implementing the first aspect, and leaving the second as-is (an enumerable type cannot be formatted, unless the enumeration depth is exhausted).

  10. mklement0 commented on Mar 28, 2021

    @mklement0
    Contributor

    leaving the second as-is (an enumerable type cannot be formatted, unless the enumeration depth is exhausted).

    I find this situational inconsistency troubling - if someone wants to use custom-formatting for an enumerable, they should be able to do so, not just when PowerShell happens not to preempt it - but it's probably not much of a real-world concern.

    Either way, to get the behavior you want it sounds like two things are needed:

    • Provide a way to tell PowerShell that a given IEnumerable type is not to be enumerated in the pipeline, as data.

      • Perhaps an attribute to decorate such types is the best solution, say [PSNoDefaultEnumeration] public class AsciiString : IEnumerable<byte> { ... }
    • Make PowerShell's output formatting system respect this attribute too and then always apply any formatting data associated with such a type.

    That the data and the formatting behaviors are already distinct is evidenced by the [hashtable] example: this type is not enumerated in the pipeline, but is enumerated for formatting.

  11. vexx32 commented on Jun 25, 2021

    @vexx32
    Collaborator

    We discussed this today in the Engine Working Group.

    I think we agree with Michael Klement (@mklement0)'s above summary here that there are fundamentally a couple of different issues converging here:

    1. Whether IEnumerable/IEnumerable-implementing types are enumerated by default is currently baked in to the core engine logic and cannot be customized.
    2. The formatting system also typically enumerates records on its own, historically so that it can display the contents of a dictionary (etc).

    For preventing enumeration of additional types, we think allowing some method of annotating a type so that it's not enumerated in the pipeline may be of interest. We all agreed that we'd need to see some more concrete real-world examples of where the current behaviour is insufficient and how adding this kind of feature would improve things. Whether this should take the form of an attribute, or a cached list of types which can be updated via an Add/Remove method, or some other form, we're not entirely sure.

    Rob Holt (@rjmholt) noted that he's raised a similar suggestion in the past, and it was at that point rejected, but we agree that it may still be worth considering. Given that this logic operates in LanguagePrimitives there may be performance concerns associated with modifying the logic, so we'd prefer to see some more real-world examples of how this is impacting users before we commit to adding functionality here.

    For the formatting enumeration issue itself, the performance impact is less stringent, so I think perhaps implementing an attribute to disable enumeration when an object hits the formatter might be considered, but we'd need need to see a prototype or at least a suggested API surface before we can make a clear call on that side of things.

    I think at this point it might make sense to split this issue into two more focused issues?

  12. removed
    Needs-Triage
    on Jun 25, 2021
  13. SeeminglyScience commented on Aug 6, 2021

    @SeeminglyScience
    Contributor

    Apparently the formatting system already supports specifying a type as not enumerable. This doesn't control pipeline enumeration, but still it's one part of the puzzle that already works:

    Set-Content ./DontEnumerateHashtable.format.ps1xml -Value '
    <Configuration>
        <DefaultSettings>
            <EnumerableExpansions>
                <EnumerableExpansion>
                    <EntrySelectedBy>
                        <TypeName>System.Collections.Hashtable</TypeName>
                    </EntrySelectedBy>
                    <Expand>CoreOnly</Expand>
                </EnumerableExpansion>
            </EnumerableExpansions>
        </DefaultSettings>
    </Configuration>'
    
    Update-FormatData -PrependPath ./DontEnumerateHashtable.format.ps1xml
    @{ test = 'test' }
    # Returns:
    # System.Collections.Hashtable
  14. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  15. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  16. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  17. added
    Resolution-No Activity
    on Nov 16, 2023
  18. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

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-EnhancementResolution-No ActivityWG-Engine-Format

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions