Skip to content

Add alternative syntax in queries - #630

Merged
maxbrunsfeld merged 2 commits into
masterfrom
query-alternatives
Jun 1, 2020
Merged

maxbrunsfeld merged 2 commits into
masterfrom
query-alternatives

Conversation

@maxbrunsfeld

@maxbrunsfeld maxbrunsfeld commented May 30, 2020 •

Copy link
Copy Markdown
Contributor

Summary

This PR deals with tree queries, introduced in #444

Currently, there is a fair amount of duplication in some of our highlighting and tagging queries. Some of this could be avoided if Tree queries had a notion of alternation - writing a sub-pattern that matches any one of a list of possible patterns. This PR adds a general alternation syntax to Tree queries.

Syntax

An alternation is written as a pair of square brackets containing a list of alternative patterns. Using square brackets seems practical because:

  • It fits neatly into the existing S-expression syntax, which is based on the ( ) delimiters
  • It is reminiscent of the regular expression character class syntax [abc], which matches either a, b, or c.

Alternations are (I believe) fully composable with the other syntax constructs in queries (captures, +, *, and ?, etc).

Examples

All of these examples are for the JavaScript language:

  1. Match a function or an arrow function being assigned to a variable or an object property. If the left hand side is a variable, capture it as @function. If it is a property, capture it as @method.
(assignment_expression
  left: [
    (identifier) @function
    (member_expression
      property: (property_identifier) @method)
  ]
  right: [(function) (arrow_function)]
)
  1. Match a call to either a variable or an object property. In the case of a variable, capture it as @function. In the case of a property, capture it as @method.
(call_expression
  function: [
    (identifier) @function
    (member_expression
      property: (property_identifier) @method)
  ])
  1. Match a set of possible keyword tokens, capturing them as @keyword.
[
  "break"
  "catch"
  "delete"
  "do"
  "else"
  "finally"
  "for"
  "function"
  "if"
  "new"
  "return"
  "throw"
  "try"
  "var"
  "while"
] @keyword

@maxbrunsfeld
maxbrunsfeld merged commit 47d607d into master Jun 1, 2020
@maxbrunsfeld
maxbrunsfeld deleted the query-alternatives branch June 1, 2020 20:23
@maxbrunsfeld

Copy link
Copy Markdown
Contributor Author

Still need to write docs for this feature.

stsewd added a commit to stsewd/tree-sitter that referenced this pull request Aug 15, 2020
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 this pull request may close these issues.

1 participant