Skip to content
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

Add alternative syntax in queries #630

Merged
merged 2 commits into from Jun 1, 2020
Merged

Conversation

maxbrunsfeld
Copy link
Contributor

@maxbrunsfeld maxbrunsfeld commented May 30, 2020

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

None yet

1 participant