tree-sitter / node-tree-sitter

Node.js bindings for tree-sitter
https://www.npmjs.com/package/tree-sitter
MIT License
649 stars 114 forks source link

Auto-generate Node subclasses with getters for node fields #39

Closed maxbrunsfeld closed 5 years ago

maxbrunsfeld commented 5 years ago

This PR exposes the new node fields APIs introduced in https://github.com/tree-sitter/tree-sitter/pull/271.

When using a language that includes fields (like these branches of tree-sitter-javascript, tree-sitter-python and tree-sitter-bash), syntax tree nodes will have different subclasses. Each node will have getters for its different fields.

Example:

const tree = parser.parse(`
  class A {
    @autobind
    @something
    b(c, d) {
      return c + d;
    }
  }
`);

const classNode = tree.rootNode.firstChild;
const methodNode = classNode.bodyNode.firstNamedChild;

// Subclasses named after the node types
assert.equal(classNode.constructor.name, 'ClassDeclarationNode');
assert.equal(methodNode.constructor.name, 'MethodDefinitionNode');

// Plural getters that return arrays
const decoratorNodes = methodNode.decoratorNodes;
assert.deepEqual(decoratorNodes.map(_ => _.text), ['@autobind', '@something'])

// Singular getters that return single nodes
const paramsNode = methodNode.parametersNode;
const bodyNode = methodNode.bodyNode;
assert.equal(paramsNode.constructor.name, 'FormalParametersNode');
assert.equal(bodyNode.constructor.name, 'StatementBlockNode');