Repository navigation
Description
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, _ -> 0This 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
dotnet-policy-service commentedon Jul 11, 2026
Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.
tannergooding commentedon Jul 11, 2026
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
tannergooding commentedon Jul 11, 2026
CC. @T-Gro as well for any additional input on the F# side of things
tannergooding commentedon Jul 11, 2026
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.JakeYallop commentedon Jul 11, 2026
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).
tannergooding commentedon Jul 11, 2026
Going to close the other as a dupe against this one (at the very least the parameter ordering is wrong)
bartonjs commentedon Jul 14, 2026
Video
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); } }epeshk commentedon Jul 15, 2026
@tannergooding Happy to see this feature moving forward!
Scanning methods often operate on stream data that is fetched partially. With the current
boolreturn type,TryParsePartialcan'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
TryParsePartialmethod, it will stop parsing at the whitespace character and produce the correct result.2. The stream is fetched partially as
s = "-1".This will return$-1e9$ , but the caller has to rely on
true, withresult = -1andcharsConsumed = 2. The real value in the stream ischarsConsumed == s.Lengthto guess if parsing should be retried with more data.3. The stream is fetched partially as
s = "-".This will return
false, with probably no meaningful value incharsConsumed.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".Based on implementation it may return
truefor "-1" withcharsConsumed = 2orfalse. If it resulted intrue, caller can't use heuristic aboutcharsConsumed = s.LengthPartial 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
out bool reachedEndparameter 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 availableOperationStatusenum as a result. Already done inUtf8Parser, but contains onlyDone/DestinationTooSmall/NeedMoreData/InvalidData, and can't differ betweenDone but may result in other value with more dataandNot Done but may succeed with more dataOperationStatusenum as a result + add isFinalBlock parameter to the API. When isFinalBlock set to false, success with ambiguous finality will result inNeedMoreDataProposed update
bartonjs commentedon Jul 15, 2026
Numeric parsing is ambiguous without an End-of-Data or other delimiter. These methods assume end-of-buffer is end-of-data.
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
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()))
tannergooding commentedon Jul 15, 2026
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.
Rename INumberBase partial-parse overloads to TryParsePartial (#130789)
epeshk commentedon Jul 15, 2026
@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
OperationStatusis an awful API design because it doesn't follow the established pattern forTryXXX(...)methods and makes the API much more difficult to use - it becomes impossible to writeif (TryXXX(...)). This API should remainbool-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
charsConsumedparameter as the bitwise complement or negated numberTryParsePartial("-1", ..., out double result, out int charsConsumed)would returntruewithcharsConsumed = 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 returnfalsewithcharsConsumed = ~1 (−2), or possiblycharsConsumed = -1. This may seem confusing, but the same encoding is already used byArray.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
tannergooding commentedon Jul 16, 2026
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
falsefor it was completely invalid from the start (or partial is unsupported because generic context + DIM, which should be the rare case), ortruebecause 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 returnedfalse, 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.
jeffhandley commentedon Aug 15, 2026
The .NET 11 portion of this shipped via #130789, with the
INumberBase<TSelf>.TryParsePartialDIMs appearing in the Preview 7 API diff.That PR implemented the API shape approved in
#130537 (comment), scoped
to
INumberBase<TSelf>:TryParsePartialoverloads toINumberBase<TSelf>asstatic virtualDIMs that fall back toTryParse.TryParse(..., out TSelf result, out int charsConsumed)overloads(
string,ReadOnlySpan<char>,ReadOnlySpan<byte>) toTryParsePartialandre-exposed them as public rather than explicitly implemented.
NumberStyles.AllowTrailingInvalidCharactersflag in favor of aninternal-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
TryParsePartialpattern toIParsableand friends via DIMs toTryParse— was not included. Quoting #130789:Confirmed against the ref assemblies on
main:IParsable<TSelf>,ISpanParsable<TSelf>, andIUtf8SpanParsable<TSelf>still expose onlyParseand
TryParse.Moving to the 12.0.0 milestone to track extending
TryParsePartialto theIParsablefamily.