tree-sitter / tree-sitter-cli

CLI tool for creating and testing tree-sitter parsers
MIT License
45 stars 15 forks source link
cli parser-generator tree-sitter

tree-sitter-cli

Incremental parsers for node

Build Status Build status


:warning: This repository is deprecated. :warning:

The source code for the Tree-sitter CLI is now part of the main Tree-sitter repository.


Installation

npm install tree-sitter-cli

Creating a language

Create a grammar.js in the root directory of your module. This file should create and export a grammar object using tree-sitter's helper functions:

module.exports = grammar({
  name: "arithmetic",

  extras: $ => [$.comment, /\s/],

  rules: {
    program: $ => repeat(choice(
      $.assignment_statement,
      $.expression_statement
    )),

    assignment_statement: $ => seq(
      $.variable, "=", $.expression, ";"
    ),

    expression_statement: $ => seq(
      $.expression, ";"
    ),

    expression: $ => choice(
      $.variable,
      $.number,
      prec.left(1, seq($.expression, "+", $.expression)),
      prec.left(1, seq($.expression, "-", $.expression)),
      prec.left(2, seq($.expression, "*", $.expression)),
      prec.left(2, seq($.expression, "/", $.expression)),
      prec.left(3, seq($.expression, "^", $.expression))
    ),

    variable: $ => /\a\w*/,

    number: $ => /\d+/,

    comment: $ => /#.*/
  }
});

Run tree-sitter generate. This will generate a C function for parsing your language, a C++ function that exposes the parser to javascript, and a binding.gyp file for compiling these sources into a native node module.

Grammar syntax

The grammar function takes an object with the following keys:

Rules