-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: regexp: add iterator forms of matching methods #61902
Comments
@rsc under "The full list is" the actual function signatures need to be fixed to match the correct names in the doc comments. |
It seems like you are trying to establish a general pattern in the stdlib that the word Which is to say, I think these names would be a lot clearer:
|
@magical I think |
This proposal has been added to the active column of the proposals project |
I have found it quite confusing in the past to figure out which of the 16 |
In addition to the correction @cespare proposes, I believe your func (re *Regexp) AllString(s string) iter.Seq[string] |
I believe it would be beneficial to document in the relevant methods that any yielded slices ( I suspect most use-cases will be unaffected by this restriction, other than to benefit from reduced allocations (which could potentially further benefit from internal use of
|
Emm, that is, we will have nearly 60 methods to do matching? 😂 How about add a new type |
I agree with @leaxoy. Irrespective of my above comments, I believe we'll be better served with an approach closer to |
I don't believe a separate type is a good idea. The It's unfortunate that the |
Regarding the |
With separate methods, particularly the Index variants, I am concerned that we'd be adding the methods for completeness without gaining much value. FindReaderIndex is of questionable utility, given that when you have a reader that you know nothing about (or know that you can't or don't want to reread, such as io.Stdin), it's rare that you can make meaningful use of the indices alone. There are other cases where having a separate Match type is simply more efficient: the consumer may want a string representation of some submatches while having a byte slice representation of others. With a Match type, the consumer does not need to care what the underlying input was. If a string for a particular submatch is requested, it'll slice or copy a portion the underlying input data depending on whether or not it was a string, but will be no worse in allocation efficiency compared to what the caller needs to do today. |
@Merovius regarding deviating from the current convention being confusing, I think that's entirely manageable if all of the iter methods are internally self-consistent. Per your point, if we implement the methods as Russ initially proposed and then introduce a separate type, that certainly will be confusing. So this is really the only good time we'll get to make a clean decision. |
@extemporalgenome We seem to be talking past each other. Putting the method on a new type is the deviation. Obviously that can't be addressed by making them "internally self-consistent". And it's also not about timing - it's a deviation if we do it from the beginning just as much. If we never had the |
Is there really a need for these? do the regexp find methods return enough elements to justify returning an iterator or is this just to avoid that one slice allocation? |
@Merovius a crazy idea, how about introduce regexp v2 like the math v2 to simplify API. |
@leaxoy It doesn't seem that wild to me. I think there is an argument to be made that a) we might want to wait a release or so to see how the But yeah, it's not really up to me. Personally, I think this proposal is fine as it is, but maybe the Go team can be persuaded to do a v2 for @doggedOwl I thought the same thing, TBH. Especially as the matching groups can be sliced out of the input, so just the actual result slice has to be allocated. There are still two ways in which an iterator form arguably might improve performance: 1. it might enable you to prematurely stop some matching work - though this seems to be possible in a corner case at best. And 2. it might enable you to do subgroup matching entirely without allocations. But I'm not totally sold on needing an iterator form of these either. It would be possible to feed the iterator into other iterator transformation functions, but then again, that would be just as possible by using |
Unfortunately the proposal doesn't say, what the benefit of the proposal is or what problem it is trying to address. It looks more like a demo for iterator functions. The proposal will further inflate the number of methods for the Regexp type. Already now I have to consult the documentation every time I use the package. I would welcome a regexp2 package that simplifies the interface. Maybe by using byte slices and string as type arguments and supporting only the iterator methods, since the first match functions wouldn't be required anymore. Using a match type could also reduce the provided variants. |
It says
The benefit is that it doesn't build the slice. If you are searching large texts, you almost always want to consider the matches one at a time, and building the slice of all results is wasted memory, potentially larger than the text. |
Finishing this proposal discussion is blocked on #61405. |
This should be unblocked right? Or is it waiting on the iterators addition to roll out? |
This is a lot of new methods, but it's also very regular and consistent with the existing API. Is there anything still blocking this proposal? |
Every time I use the regexp API I find it hard to remember what all the different unnamed numbers signify. Has anyone prototyped a version of a Match method that returns an iter.Seq of some abstract match data type that provides methods (with informative names!) that can return any information you need about a given match: its indices, its byte or string value (allocating if different from the input string type), its submatch index, and so on? (speaking for proposal committee) |
https://go.dev/cl/643896 provides a sketch of the idea above: package regexp
// All returns the sequence of matches of the regular expression on
// the input text, which may be a string or a []byte slice.
//
// TODO(adonovan): API:
// - Should we define two variants All([]byte), AllString(string)?
// This is consistent with the String flavors of the existing API.
// - Or use generics: func All[S string|[]byte](S)?
// This means we must forego methods.
func (re *Regexp) All(text any) iter.Seq[Substring]
// A Substring represents a subsequence of an input string or []byte
// slice that matches a regular expression.
type Substring struct { ... }
// String returns the matched substring.
func (s Substring) String() string
// AppendTo appends the matched substring to the provided slice.
func (s Substring) AppendTo(slice []byte) []byte
// Start returns the matched substring's start index,
// relative to the input of [Regexp.All].
func (s Substring) Start() int
// End returns the matched substring's end index,
// relative to the input of [Regexp.All].
func (s Substring) End() int
// NumSubmatch returns the number of submatches.
func (s Substring) NumSubmatch() int
// Submatch returns the ith submatch of the current match.
func (s Substring) Submatch(i int) Substring Feedback welcome. |
Change https://go.dev/cl/643896 mentions this issue: |
@adonovan One note is, that this API doesn't allow to inspect a match without allocation ( In regards to your question, I would add |
Incorporating @Merovius's suggestions, we have: // All returns the sequence of matches of the regular expression on
// the input text.
func (re *Regexp) All(text []byte) iter.Seq[Substring]
// AllString returns the sequence of matches of the regular expression
// on the input text.
func (re *Regexp) AllString(text string) iter.Seq[Substring]
// A Substring represents a subsequence of an input string or []byte
// slice that matches a regular expression.
//
// Call the [Substring.Bytes] or [Substring.String] method to access
// the text of the substring. (For efficiency, use the method that
// corresponds to the function--[Regexp.All] or
// [Regexp.AllString]--that created this Substring.)
//
// A Substring is valid only for the duration of the iteration that
// produced it.
type Substring struct {}
// String returns the matched substring.
//
// If this Substring was created by [Regexp.All], String must allocate
// a copy; it may be more efficient to use [Substring.Bytes].
func (s Substring) String() string
// Bytes returns the matched substring.
//
// If this Substring was created by [Regexp.All], Bytes returns a
// clipped slice of the original array; if created by
// [Regexp.AllString], it allocates a copy of part of the
// original string.
func (s Substring) Bytes() []byte
// AppendTo appends the matched substring to the provided slice.
func (s Substring) AppendTo(slice []byte) []byte
// Start returns the matched substring's start index,
// relative to the input of [Regexp.All].
func (s Substring) Start() int
// End returns the matched substring's end index,
// relative to the input of [Regexp.All].
func (s Substring) End() int
// NumSubmatch returns the number of submatches.
func (s Substring) NumSubmatch() int
// Submatch returns the ith submatch of the current match.
// The boolean indicates whether it exists.
func (s Substring) Submatch(i int) (Substring, bool) [Update: changed Substring to be valid only for the duration of its iteration. The CL implements a defensive check.] |
I have some code that makes use of named capture groups but hadn't looked at it for a while and was initially worried that the above API would be hard to use in that case. However, I'm pleased to report that it actually wasn't a problem after all! This new proposed API is also, in my opinion at least, considerably more ergonomic than working with Two potential additions that would make my use-case more convenient:
In case anyone finds it interesting, some specific places where I'd like to use this new API:
In this particular usage, earlier code has checked to make sure that the given pattern consistently uses either all named or all unnamed capture groups -- an additional constraint imposed by me for simplicity's sake -- so these are handled entirely separately.
|
Thanks for the feedback. Re: Submatches and iterators: the usual case is that Submatch is called with a specific constant index to extract a particular portion, rather than that all submatches are iterated over. (The submatches are more like a struct than a slice, i.e., heterogenous.) The proposed Submatch(int) also dovetails nicely with named groups: re.Submatch(re.SubexpIndex("foo")). Re: FindSubstring (which I think must have a []byte parameter?): I don't think the gain from FindSubstring is very much: one source line, and no difference in efficiency:
(A better name might be Regexp.First.) |
Is Should
|
Not sure; perhaps not since it can be derived from the other two for any given situation.
Substring should have a String method so that you can log.Print them. If it has that method, it doesn't need a Text method.
regexp.Match would be ideal but is taken. regexp.RegexpMatch is unfortunately stuttery (though, as you point out, rarely needs to be written). |
I wouldn't want to print one and get the current value. I'd only be printing it to log or print-debug so I'd either want just the type name so I realize I did something silly or something more informative to help me. |
If we're bikeshedding about the type name 😀 then I will offer
It is admittedly unconventional to use a past tense verb to name a type. In this particular case I'm treating it as an adjective (participle) modifying an implied noun, which is also unconventional but perhaps not so weird? 🤷 Agreed that (FWIW I was also just fine with |
This feels like a false symmetry. What happens if I ask for a submatch of a submatch? There are really two levels here: matches and submatches (aka capture groups). I'm not positive, but I think you flattened them into one concept because a match is also a match of the whole regexp. But I think its better to separate these concepts. Here's what that would look like as a minimal change from @adonovan 's API, where "matches" are represented as a // All returns the sequence of matches of the regular expression on
// the input text.
//
// Submatch 0 is the match of the entire expression,
// submatch 1 is the match of the first parenthesized subexpression,
// and so on.
func (re *Regexp) All(text []byte) iter.Seq[[]Submatch]
// AllString returns the sequence of matches of the regular expression
// on the input text.
func (re *Regexp) AllString(text string) iter.Seq[[]Submatch]
type Submatch struct { ... }
// String returns the matched substring.
//
// If this Submatch was created by [Regexp.All], String must allocate
// a copy; it may be more efficient to use [Substring.Bytes].
func (s Submatch) String() string
// Bytes returns the matched substring.
//
// If this Submatch was created by [Regexp.All], Bytes returns a
// clipped slice of the original array; if created by
// [Regexp.AllString], it allocates a copy of part of the
// original string.
func (s Submatch) Bytes() []byte
// AppendTo appends the matched substring to the provided slice.
func (s Submatch) AppendTo(slice []byte) []byte
// Start returns the matched substring's start index,
// relative to the input of [Regexp.All].
func (s Submatch) Start() int
// End returns the matched substring's end index,
// relative to the input of [Regexp.All].
func (s Submatch) End() int Using a A few smaller things: I'd propose replacing Start and End with a single method: // Indexes returns the location of this submatch.
// The match itself is at b[start:end], where b is the original input.
// If this submatch is empty, it returns 0, 0, false.
func (s Submatch) Indexes() (start, end int, ok bool) This whole approach is dipping our toes in a bit of a v2 API, albeit in a backwards compatible way, and it feels odd to only do the iterator part. That suggests we should also support single matches: func (re *Regexp) First(b []byte) []Submatch
func (re *Regexp) FirstString(s string) []Submatch This also raises the question of whether we should use generics, which shrinks // All returns the sequence of matches of the regular expression on
// the input text.
//
// Submatch 0 is the match of the entire expression,
// submatch 1 is the match of the first parenthesized subexpression,
// and so on.
func (re *Regexp) All(text []byte) iter.Seq[[]Submatch[[]byte]]
// AllString returns the sequence of matches of the regular expression
// on the input text.
func (re *Regexp) AllString(text string) iter.Seq[[]Submatch[string]]
type Submatch[T []byte | string] struct { ... }
// String returns the matched substring.
//
// If this match came from a []byte, this may allocate.
func (s Submatch[T]) String() string
// Match returns the matched substring as its original type.
func (s Submatch[T]) Match() T
// Indexes returns the location of this submatch.
// The match itself is at b[start:end], where b is the original input.
// If this submatch is empty, it returns 0, 0, false.
func (s Submatch[T]) Indexes() (start, end int, ok bool) |
There's a tension between allocation and aliasing here that worries me. This also appears in @rsc's proposal at the top and in whether iteration reuses the @rsc's proposal doesn't say anything about whether slices are reused between iterations and, by omission, that tells me that they are not. That's certainly the safer choice. The compiler is at least sometimes able to eliminate this allocation, and I'm sure could do a better job than it does today: https://go.dev/play/p/MJTonvzkfkM?v=gotip |
True, my proposed API raises the question of sub-sub-matches, and the answer is simply "there are none". You could define a different type for capturing group, but it would be identical to Substring but lacking the {Num,}Submatch methods. I suppose a it could also provide a I'm not sure it's necessary to distinguish the parent and child types, but I don't feel strongly. If we were to do it, I would suggest keeping the abstract Substring data type, and adding a second type for the child:
I think we have often over-revealed the representation of core data types, either because of the lack of abstract iteration, or motivated by efficiency (especially in the pre-inlining days) but ultimately foreclosing desirable optimizations or reorganizations of the implementation.
The need to know that "zero means the whole thing" is IMHO an unfortunate flaw in the original API. Now that we have iterators and method inlining, we can do better. Regexps without submatches are I think the common case, yet this API would make them harder to use.
We should not expose the complete slice of submatches, as it either forces an allocation for each match (which, as Russ points out, can easily add up to more than the input text), or demands that the loop body only "borrow" the slice, which is more prone to error. The {Num,}Submatch API is efficient and safe. (One could also provide an iterator, but, as mentioned above, efficient random access is much more important and common than looping over submatches.)
I had that initially, and decided against it just because it forces the need for a statement. But one never asks for one without the other. I don't feel strongly either way.
This approach creates Submatch values even when there was no submatch, requiring all methods (e.g. String) to quietly return zero on a non-matching Submatch. The approach I proposed doesn't even create the Submatch unless it is valid.
These seem fine to me, but we could also add them later. |
Note that the regexp package does not use the term "group". It calls these "submatches" (and it calls the syntactic part of the regular expression itself a "subexpression"). That's why I called my type
Yes, but it's also standard across a huge range of languages and regexp packages that subexpressions are numbered starting at "1" and that "0" refers to the whole thing. This convention also permeates substitutions, for example Regexp.Expand starts submatches at
I may be missing something, but I don't see how to implement
I'm not sure I quite agree. In your approach, |
Fair enough; I picked that name casually, figuring we'll always haggle over the names as the last step. ;-)
I'll take your word for it; that's unfortunate.
The sketch implementation in the attached CL allocates a single []int array for the entire scan over the input, and it is shared by all Substrings, which is why they each become invalid after the end of the iteration that produced them. I haven't measured it but I suspect this could be a major reduction in allocation, given how careful the package is about allocations otherwise. The key is that the array doesn't escape the loop.
Good point. |
We propose to add methods to regexp that allow iterating over matches instead of having to accumulate all the matches into a slice.
This is one of a collection of proposals updating the standard library for the new 'range over function' feature (#61405). It would only be accepted if that proposal is accepted. See #61897 for a list of related proposals.
Regexp has a lot of methods that return slices of all matches (the “FindAll*” methods). Each should have an iterator equivalent that doesn’t build the slice. They can be named by removing the “Find” prefix. The docs would change as follows. (Plain text is unchanged; strikethrough is removed, bold is added):
Instead of enumerating all eight methods here, let’s just show one example.
FindAllString currently reads:
This would change to become a pair of methods:
The full list is:
There would also be a new SplitSeq method alongside regexp.Regexp.Split, completing the analogy with strings.Split and strings.SplitSeq.
The text was updated successfully, but these errors were encountered: