Skip to content

Consider custom iterator for captures #30

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

Open
bennypowers opened this issue May 29, 2025 · 5 comments · May be fixed by #31
Open

Consider custom iterator for captures #30

bennypowers opened this issue May 29, 2025 · 5 comments · May be fixed by #31

Comments

@bennypowers
Copy link

bennypowers commented May 29, 2025

The pattern for iterating captures with go-tree-sitter looks like this

for {
	match, _ := captures.Next()
	if match == nil {
		break
	}
	// 🐒 🌴 🪑 🥥 
}

This is fine, but perhaps we can use go's custom iterators (since 1.23) to nice it up a bit:

for match, idx := range captures.Iter() {
	// 🐒 🌴 🪑 🥥 
}

This wouldn't have to replace the Next() method, it could just be a more ergonomic API for users that want it.

this (basically pseudocode) might do the job:

func (qc *QueryCaptures) Iter() iter.Seq2[*QueryMatch, uint] {
	return func(yield func(c *QueryMatch, i uint) bool) {
		for {
			c, i := qc.Next()
			if c == nil {
				break
			}
			if !yield(c, i) {
				return
			}
		}
	}
}
@topi314
Copy link
Contributor

topi314 commented May 29, 2025

func (qc *QueryCaptures) Iter() iter.Seq2[*QueryMatch, uint] should probably be named func (qc *QueryCaptures) All() iter.Seq2[*QueryMatch, uint]
https://pkg.go.dev/iter#hdr-Naming_Conventions

bennypowers added a commit to bennypowers/go-tree-sitter that referenced this issue May 29, 2025
@bennypowers bennypowers linked a pull request May 29, 2025 that will close this issue
@bennypowers
Copy link
Author

@topi314 ok so in my PR i put the iterator on the query cursor, instead of the matches/captures result

but that introduces a name collision, so I called them IterMatches/Captures

WDYT of that?

@topi314
Copy link
Contributor

topi314 commented May 29, 2025

not ideal, but I'd prob go with AllMatches & AllCaptures

@bennypowers
Copy link
Author

Maybe @amaanq is amenable to a breaking change?

@topi314
Copy link
Contributor

topi314 commented May 29, 2025

I think it's fine.
one thing to note is that you wont be able to use SetByteRange & SetPointRange with the iterator api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants