Skip to content

Consider custom iterator for captures #30

@bennypowers

Description

@bennypowers

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
			}
		}
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions