Skip to content

Adjust API surface for stopping parsing after the first invalid character #130537

Open

Description

@tannergooding

Issue

#87171 was approved to be a general purpose way to extend a previously Utf8Parser unique feature to support UTF-16 and all number styles rather than the limited subset that Utf8Parser covered. In particular this was the ability to parse up until the first invalid character and then succeed rather than fail, allowing for incremental parsing to occur which can be particularly useful for things like CSV, tokenizers, serialization formats (e.g. JSON, YAML, XML, ...), etc.

However, it turns out that doing it this way is a breaking change to F# namely because they allow the following which binds against the existing single out overload and produces a tuple (bool, int) containing the result type and out parameters:

match Int32.TryParse(rightMost, NumberStyles.Integer, CultureInfo.InvariantCulture) with 
| true, n -> n
| false, _ -> 0

This F# feature actually works for any shape of T Method(out U result) including multiple out parameters. However, it only works if you only have a single overload with out parameters and errors with an ambiguity if you have multiple, such as the approved API surface is introducing.

Due to the way the F# type inferrence works (largely linear), this is not something that's readily feasible for them to fix. We might be able to use ORPA, but F# would first have to add support for ORPA and that may have unintended future impact, particularly since we're not really deprecating or preferring one API over the other.

Proposal

Given the above and that there was also the discussion of extending this support to other non-numeric types in the future (like Guid or DateTime which does not take a NumberStyles), it is proposed we change the approved API surface to avoid this ambiguity and land on a unified design.

The main proposal is to split this apart into two distinct interfaces that expose the "incremental parsing" nature. The natural term for this in computer science tends to be a "scanner" in contrast to a "parser" so that is the proposed name below. I expect this name may be slightly contentious and we'll need to discuss other names as well. Some other words that may fit are Consume, ParsePrefix, ParseLeading, ParsePartial, Read, Take, or Tokenize; but I feel like most of these aren't as "clear".

We could notably get away with only providing the span versions, we don't strictly need the string one (only differing in behavior for null as its slightly different from empty in exception for parse).

We could also notably get away with only providing the Try* APIs or only providing Scan either in the form of int Scan(..., out T result) or T Scan(..., out int elementsConsumed) where a consumption amount of 0 or -1 indicates "failure". But those feel slightly less consistent with normal .NET conventions.

This new shape would solve the question of how it works for non-numeric types as well; provided we're okay with whatever name we land on.

namespace System
{
    public interface IScannable<TSelf>
        where TSelf : IScannable<TSelf>
    {
        public static abstract TSelf Scan(string s, IFormatProvider? provider, out int charsConsumed);
        public static abstract bool TryScan(string? s, IFormatProvider? provider, out TSelf result, out int charsConsumed);
    }

    public interface ISpanScannable<TSelf>
        where TSelf : ISpanScannable<TSelf>
    {
        public static abstract TSelf Scan(ReadOnlySpan<char> s, IFormatProvider? provider, out int charsConsumed);
        public static abstract bool TryScan(ReadOnlySpan<char> s, IFormatProvider? provider, out TSelf result, out int charsConsumed);
    }

    public interface IUtf8SpanScannable<TSelf>
        where TSelf : IUtf8SpanScannable<TSelf>
    {
        public static abstract TSelf Scan(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out int bytesConsumed);
        public static abstract bool TryScan(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out TSelf result, out int bytesConsumed);
    }
}

namespace System.Numerics
{
     public partial interface INumberBase<TSelf>
        : IScannable<TSelf>,
          ISpanScannable<TSelf>,
          IUtf8SpanScannable<TSelf>
    {
        public static abstract TSelf Scan(string s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int charsConsumed);
        public static abstract TSelf Scan(ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out int charsConsumed);
        public static virtual TSelf Scan(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out int bytesConsumed);

        public static abstract bool TryScan(string? s, System.Globalization.NumberStyles style, IFormatProvider? provider, out TSelf result, out int charsConsumed);
        public static abstract bool TryScan(ReadOnlySpan<char> s, System.Globalization.NumberStyles style, IFormatProvider? provider, out TSelf result, out int charsConsumed);
        public static virtual bool TryScan(ReadOnlySpan<byte> utf8Text, System.Globalization.NumberStyles style, IFormatProvider? provider, out TSelf result, out int bytesConsumed);
    }
}

We'd then remove the previously approved API surface, including the AllowTrailingInvalidCharacters number style.

Activity

  1. added this to the 11.0.0 milestone on Jul 11, 2026
  2. added
    blocking
    api-ready-for-review
    on Jul 11, 2026
  3. dotnet-policy-service commented on Jul 11, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime
    See info in area-owners.md if you want to be subscribed.

  4. tannergooding commented on Jul 11, 2026

    @tannergooding
    MemberAuthor

    This is marked blocking due to the breaking change found in F#. It is currently being mitigated by having the APIs explicitly implemented so that it doesn't introduce the source break.

    This is more a placeholder issue for the API review discussion that needs to take place and where we'll either decide one of the obvious suggestions is acceptable or we need to fully back out the change from .NET 11 and take a deeper look in the future after more discussion/consensus can be reached

    The proposed surface is merely the simplest alternative that was recommended by various people talked to and which fits the general industry nomenclature. It is not the definitive solution.

    CC. @dotnet/fxdc, @bartonjs

  5. tannergooding commented on Jul 11, 2026

    @tannergooding
    MemberAuthor

    CC. @T-Gro as well for any additional input on the F# side of things

  6. tannergooding commented on Jul 11, 2026

    @tannergooding
    MemberAuthor

    Deciding to keep the API surface and only have it explicitly implemented (and therefore accessible via where T : INumberBase<TSelf>) is also a viable option.

  7. JakeYallop commented on Jul 11, 2026

    @JakeYallop
    Contributor

    How does this issue relate to #93339 (I assume one should supersede the other)?

    Also, incidentally, I don't love the name (but I also don't have a better suggestion).

  8. tannergooding commented on Jul 11, 2026

    @tannergooding
    MemberAuthor

    Going to close the other as a dupe against this one (at the very least the parameter ordering is wrong)

  9. bartonjs commented on Jul 14, 2026

    @bartonjs
    Member

    Video

    • We don't feel that it's appropriate to take as a general disallowed-breaking rule that we can't introduce new out-arity overloads, but it is important to make TryParse work with match in F#.
    • Rather than an IScannable interface, we went with TryParsePartial.
    • TryParsePartial obviates the need for NumberStyles.AllowTrailingInvalidCharacters
    • Let's go ahead and apply the TryParsePartial pattern to IParsable and friends, via DIMs to TryParse.
    namespace System
    {
        public partial interface IParsable<TSelf>
        {
            // DIM defers to TryParse
            public static virtual bool TryParsePartial(string? s, IFormatProvider? provider, out TSelf result, out int charsConsumed);
        }
    
        public partial interface ISpanParsable<TSelf>
        {
            // DIM defers to TryParse
            public static virtual bool TryParsePartial(ReadOnlySpan<char> s, IFormatProvider? provider, out TSelf result, out int charsConsumed);
        }
    
        public interface IUtf8SpanParsable<TSelf>
        {
            // DIM defers to TryParse
            public static virtual bool TryParsePartial(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out TSelf result, out int bytesConsumed);
        }
    }
    
    namespace System.Numerics
    {
        public interface INumberBase<TSelf>
        {
            public static virtual bool TryParsePartial([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int charsConsumed);
    
            public static virtual bool TryParsePartial(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int charsConsumed);
            
            public static virtual bool TryParsePartial(ReadOnlySpan<byte> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int bytesConsumed);
        }
    }
    namespace System.Globalization
    {
        [Flags]
        public partial enum NumberStyles
        {
    -       AllowTrailingInvalidCharacters = 0x800
        }
    }
    
    namespace System.Numerics
    {
        public interface INumberBase<TSelf>
        {
    -       public static virtual bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int charsConsumed);
    
    -       public static virtual bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int charsConsumed);
            
    -       public static virtual bool TryParse(ReadOnlySpan<byte> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int bytesConsumed);
        }
    }
  10. added
    api-approved
    and removed
    api-ready-for-review
    blocking
    on Jul 14, 2026
  11. epeshk commented on Jul 15, 2026

    @epeshk
    Contributor

    @tannergooding Happy to see this feature moving forward!

    Scanning methods often operate on stream data that is fetched partially. With the current bool return type, TryParsePartial can't tell the caller if they should retry the call with more data.

    What should a caller do in these scenarios?

    1. The stream contains "-1e9".

    If this string is fully given to the TryParsePartial method, it will stop parsing at the whitespace character and produce the correct result.

    2. The stream is fetched partially as s = "-1".

    TryParsePartial("-1", ..., out double result, out int charsConsumed)

    This will return true, with result = -1 and charsConsumed = 2. The real value in the stream is $-1e9$, but the caller has to rely on charsConsumed == s.Length to guess if parsing should be retried with more data.

    3. The stream is fetched partially as s = "-".

    TryParsePartial("-", ..., out double result, out int charsConsumed)

    This will return false, with probably no meaningful value in charsConsumed.

    Now the caller can't understand if the value is entirely invalid as a double (like ",f5"), or if it was rejected just because it is incomplete and needs more data. To work around this, the caller has to rely on things like buffer size to decide (e.g., if the buffer contains 1500 characters, it is probably a truly invalid value, because there are probably no real floats that long).

    4. The stream is fetched partially as s = "-1e".

    TryParsePartial("-1e", ..., out double result, out int charsConsumed)

    Based on implementation it may return true for "-1" with charsConsumed = 2 or false. If it resulted in true, caller can't use heuristic about charsConsumed = s.Length

    Partial fetch from the stream is common situation, because reader may read stream e.g. in 4KB chunks, and problematic value may appears torn at the end of the chunk

    Possible solutions

    • an additional out bool reachedEnd parameter that indicates if retry may be useful, filled independently of parsing result. If end is reached, caller may decide to retry if more data is available
    • using OperationStatus enum as a result. Already done in Utf8Parser, but contains only Done/DestinationTooSmall/NeedMoreData/InvalidData, and can't differ between Done but may result in other value with more data and Not Done but may succeed with more data
    • using OperationStatus enum as a result + add isFinalBlock parameter to the API. When isFinalBlock set to false, success with ambiguous finality will result in NeedMoreData

    Proposed update

    namespace System
    {
        public partial interface IParsable<TSelf>
        {
            // DIM defers to TryParse
            public static virtual bool TryParsePartial(string? s, IFormatProvider? provider, out TSelf result, out int charsConsumed, out bool reachedEnd);
        }
    
        public partial interface ISpanParsable<TSelf>
        {
            // DIM defers to TryParse
            public static virtual bool TryParsePartial(ReadOnlySpan<char> s, IFormatProvider? provider, out TSelf result, out int charsConsumed, out bool reachedEnd);
        }
    
        public interface IUtf8SpanParsable<TSelf>
        {
            // DIM defers to TryParse
            public static virtual bool TryParsePartial(ReadOnlySpan<byte> utf8Text, IFormatProvider? provider, out TSelf result, out int bytesConsumed, out bool reachedEnd);
        }
    }
    
    namespace System.Numerics
    {
        public interface INumberBase<TSelf>
        {
            public static virtual bool TryParsePartial([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int charsConsumed, out bool reachedEnd);
    
            public static virtual bool TryParsePartial(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int charsConsumed, out bool reachedEnd);
            
            public static virtual bool TryParsePartial(ReadOnlySpan<byte> s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out TSelf result, out int bytesConsumed, out bool reachedEnd);
        }
    }
    
  12. bartonjs commented on Jul 15, 2026

    @bartonjs
    Member

    Numeric parsing is ambiguous without an End-of-Data or other delimiter. These methods assume end-of-buffer is end-of-data.

    public OperationStatus Parse(ReadOnlySpan<char> source, out int value, out int charsConsumed);

    shouldn't really return Success and emit 3 for Parse("31".AsSpan(0, 1), out value, out _), it would have to return NeedsMoreData, unless we changed it to

    public OperationStatus Parse(ReadOnlySpan<char> source, out int value, out int charsConsumed, bool finalBlock = SomeDefault);`

    So the caller can indicate "more data is never available", which collapses the previous input to the value 3.

    (edit: I see that one of your variants was an OperationStatus with an isFinalBlock. If streaming-parsing is what you need, then that's the API we'd have to add. TryParsePartial is more for a scenario like reading a comma separated list with a defined ending (e.g. the caller is parsing the response from ReadLine()))

  13. tannergooding commented on Jul 15, 2026

    @tannergooding
    MemberAuthor

    It'd also be very expensive/complex to build a resumable parsing API, especially general-purpose across types. You'd need some form of capturable state holder that understands the accumulated context and how to continue on it. I don't think it's something we'd ever add.

  14. epeshk commented on Jul 15, 2026

    @epeshk
    Contributor

    @tannergooding I never asked about capturable state. I only asked about the caller retrying without preserving state, but with more data.

    @bartonjs What if a comma-separated list is fetched from a file or network and has no line-by-line structure? Having separate methods for partial parsing and streaming seems confusing and redundant.

    I agree that OperationStatus is an awful API design because it doesn't follow the established pattern for TryXXX(...) methods and makes the API much more difficult to use - it becomes impossible to write if (TryXXX(...)). This API should remain bool-returning.

    An alternative that doesn't require an API change is to preserve info of the number of examined characters even when parsing fails. E.g. by encoding it in charsConsumed parameter as the bitwise complement or negated number

    TryParsePartial("-1", ..., out double result, out int charsConsumed) would return true with charsConsumed = 2. Since parsing reached the end of the available input, the caller may defer processing the value and retry if more data becomes available.

    TryParsePartial("-", ..., out double result, out int charsConsumed) would return false with charsConsumed = ~1 (−2), or possibly charsConsumed = -1. This may seem confusing, but the same encoding is already used by Array.BinarySearch.

    This approach enables using these methods for parsing regardless of finality, with some limitations (caller should still make a decision about needing a retry), but without reimplementing parsing in user code, fully relying on well-tested framework code for parsing itself

  15. tannergooding commented on Jul 16, 2026

    @tannergooding
    MemberAuthor

    I never asked about capturable state. I only asked about the caller retrying without preserving state, but with more data.

    You can already achieve that. Just load more data and decide to reparse or not after combining the parts in question.

    If you're doing partial parsing you either get false for it was completely invalid from the start (or partial is unsupported because generic context + DIM, which should be the rare case), or true because it succeeded and it tells you the amount consumed. There's no information missing for you to combine with the next chunk and retry -- noting that if partial was supported and it returned false, it also means that simply combining buffers won't fix anything, the starting characters are still "invalid".

    If you want to parse without manually combining the data, then it needs something which provides access to the tracked parsing state, which is a non-starter. You'd fundamentally need to know what its built so far and how it can meaningfully combine with the next buffer if possible.

  16. jeffhandley commented on Aug 15, 2026

    @jeffhandley
    Member

    The .NET 11 portion of this shipped via #130789, with the
    INumberBase<TSelf>.TryParsePartial DIMs appearing in the Preview 7 API diff.

    That PR implemented the API shape approved in
    #130537 (comment), scoped
    to INumberBase<TSelf>:

    • Added the three TryParsePartial overloads to INumberBase<TSelf> as
      static virtual DIMs that fall back to TryParse.
    • Renamed the TryParse(..., out TSelf result, out int charsConsumed) overloads
      (string, ReadOnlySpan<char>, ReadOnlySpan<byte>) to TryParsePartial and
      re-exposed them as public rather than explicitly implemented.
    • Removed the NumberStyles.AllowTrailingInvalidCharacters flag in favor of an
      internal-only sentinel. Neither that flag nor the old overloads ever shipped in
      a public release or preview, so nothing was broken by this.

    The last item of the approved shape — applying the TryParsePartial pattern to
    IParsable and friends via DIMs to TryParse — was not included. Quoting #130789:

    IParsable, ISpanParsable, and IUtf8SpanParsable are intentionally left out
    of scope for .NET 11.

    Confirmed against the ref assemblies on main: IParsable<TSelf>,
    ISpanParsable<TSelf>, and IUtf8SpanParsable<TSelf> still expose only Parse
    and TryParse.

    Moving to the 12.0.0 milestone to track extending TryParsePartial to the
    IParsable family.

  17. modified the milestones: 11.0.0, 12.0.0 on Aug 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Runtime

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions