Skip to content

Add an API for associating field names with child nodes - #271

Merged
maxbrunsfeld merged 29 commits into
masterfrom
node-fields
Mar 28, 2019
Merged

maxbrunsfeld merged 29 commits into
masterfrom
node-fields

Conversation

@maxbrunsfeld

@maxbrunsfeld maxbrunsfeld commented Feb 7, 2019 •

Copy link
Copy Markdown
Contributor

Problem

Previously, syntax nodes' children were structured as a simple ordered list. This is useful for some kinds of processing (e.g. syntax highlighting), but is different than the way syntax trees are commonly structured, in which there is a label associated with each child node.

Solution

Grammar API

This PR adds a new function called field to the grammar API. You can use it like this:

function: $ => seq(
  optional('async'),
  'function',
  field('name', optional($.identifier)),
  field('parameters', $.formal_parameters),
  field('body', $.statement_block)
),

Node API

Then, when parsing, you can retrieve nodes' children based on their field name:

TSNode params_node = ts_node_child_by_field_name(function_node, "parameters");
TSNode body_node = ts_node_child_by_field_name(function_node, "body");

ts_node_type(function_node); // => "function"
ts_node_type(params_node);   // => "formal_parameters"
ts_node_type(body_node);     // => "statement_block"

Tree Cursor API

You can also retrieve the field name associated with the current node when walking a tree using a tree cursor:

TSTreeCursor cursor = ts_tree_cursor_new(function_node);

ts_tree_cursor_goto_first_child(&cursor);
ts_tree_cursor_current_field_name(&cursor); // => NULL
ts_tree_cursor_goto_next_sibling(&cursor);
ts_tree_cursor_current_field_name(&cursor); // => "name"
ts_tree_cursor_goto_next_sibling(&cursor);
ts_tree_cursor_current_field_name(&cursor); // => "parameters"

Testing API

The tree-sitter test command now allows you to optionally assert about nodes' fields using a notation like this:

=============
Functions
=============

function a(b) {}

---

(program
  (function
    name: (identifier)
    parameters: (formal_parameters)
    body: (statement_block)))

But if you don't want to change your existing tests, you can also omit the field names from the test file. In that case, the fields will be ignored for the purpose of the assertion.

Command Line Output

The field names are also shown when you run the tree-sitter parse command:

(program [0, 0] - [5, 0]
  (function [0, 0] - [4, 1]
    name: (identifier [0, 9] - [0, 12])
    parameters: (formal_parameters [0, 12] - [0, 15]
      (identifier [0, 13] - [0, 14]))
    body: (statement_block [0, 16] - [4, 1]
      (lexical_declaration [1, 2] - [1, 14]
        (variable_declarator [1, 8] - [1, 13]
          name: (identifier [1, 8] - [1, 9])
          value: (identifier [1, 12] - [1, 13])))
      (expression_statement [2, 2] - [3, 5]
        (call_expression [2, 2] - [3, 4]
          function: (identifier [2, 2] - [2, 7])
          arguments: (arguments [2, 7] - [3, 4]
            (function [2, 8] - [3, 3]
              parameters: (formal_parameters [2, 16] - [2, 22]
                (identifier [2, 17] - [2, 18])
                (identifier [2, 20] - [2, 21]))
              body: (statement_block [2, 23] - [3, 3]))))))))

Static Node Types

The tree-sitter generate command now generates a JSON file called src/node-types.json which provides static information about nodes' fields based on the grammar. Here is an example file:

[
  {
    "type": "function",
    "fields": {
      "parameters": {
        "required": true,
        "multiple": false,
        "types": [
          {"type": "formal_parameters", "named": true}
        ]
      },
      "name": {
        "required": false,
        "multiple": false,
        "types": [
          {"type": "identifier", "named": true}
        ]
      },
      "body": {
        "required": true,
        "multiple": false,
        "types": [
          {"type": "statement_block", "named": true}
        ]
      }
    }
  }
]

By reading this JSON, applications can use meta-programming to generate a specific data types for each kind of node. The required, multiple, and types properties in the JSON can be used to determine the appropriate data type for each field.

Property Sheet API

The new Property Sheet feature can also make use of these named fields. You can select nodes based on their field name using CSS class-selector syntax (dot notation).

Example:

function {
  > .name {
    color: blue;
  }

  .parameters > identifier {
    color: red;
  }
}

For any function node, this will associate the property color: blue with the node's name child, and associate the property color: red to any identifier node within the parameters child.

Follow-on Work

We'll need to update Tree-sitter's language binding libraries like node-tree-sitter and haskell-tree-sitter to take advantage of this new feature.

In the JavaScript case, I believe that we can use the new node-interface.json file and the new ts_node_child_by_field_name C API to automatically generate a set of Node subclasses with accessor methods for their children.

Something like this:

const functionNode = rootNode.children[0];

// `FunctionNode` is an auto-generated subclass of `Node` with
// accessor methods for each child field: `name`, `parameters`, and `body`.
functionNode  // => FunctionNode {}
functionNode.getNameNode() // => IdentifierNode {}
functionNode.getParametersNode() // => FormalParametersNode {}
functionNode.getBodyNode() // => StatementBlockNode {}

This allows you to assert about fields in tests. But if your test 
s-expression does *not* include fields, the fields will be stripped from 
the regexp before comparison.
@bilsaboob

Copy link
Copy Markdown

This one would be really nice to get in - would be very useful for several stages after parsing in an IDE pipeline - nice stuff!

@Aerijo

Aerijo commented Mar 3, 2019 •

Copy link
Copy Markdown

Wait, so I won't have to iterate everything just to skip possible comments now?

Also would this provide / have integer values for the fields, like how you can use ts_node_symbol directly instead of going through ts_node_type?

@maxbrunsfeld

Copy link
Copy Markdown
Contributor Author

Yeah the fields have numerical ids that you can use; you don’t have to use the field name strings.

Even though normal aliases don't cause this, simple (single-use) aliases still do cause it.
@maxbrunsfeld
maxbrunsfeld force-pushed the master branch 4 times, most recently from 10d1ff6 to 3340168 Compare March 21, 2019 00:02
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.

3 participants