1

One very common parsing scenario in programming languages is an arbitrary-length nonempty list of elements with a separator, for example:

[1, 2, 3, 4, 5]
f(a, b, c)

I've been parsing this in treesitter as follows:

list: $ => seq(
  repeat(seq($.element, ',')),
  $.element
)

This works, but it's common enough that I wonder whether treesitter has a built-in construct for it. Does it?

ahelwer
  • 1,441
  • 13
  • 29

1 Answers1

2

In several grammars, (e.g. Rust, Go), we define helper functions for this.

function commaSep1(rule) {
  return seq(rule, repeat(seq(',', rule)))
}

function commaSep(rule) {
  return optional(commaSep1(rule))
}

We could include these functions as part of the Tree-sitter DSL, but since it's so easy to define your own helper functions like this, I think it's best to keep the DSL small.

maxbrunsfeld
  • 341
  • 2
  • 2