Skip to content

Commit

Permalink
feat: v0.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
amaanq committed Feb 18, 2023
0 parents commit 12d06b8
Show file tree
Hide file tree
Showing 41 changed files with 93,267 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports = {
'env': {
'commonjs': true,
'es2021': true,
},
'extends': 'google',
'overrides': [
],
'parserOptions': {
'ecmaVersion': 'latest',
'sourceType': 'module',
},
'rules': {
'indent': ['error', 2, {'SwitchCase': 1}],
'max-len': [
'error',
{'code': 120, 'ignoreComments': true, 'ignoreUrls': true, 'ignoreStrings': true},
],
},
};
6 changes: 6 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/src/** linguist-vendored
/examples/* linguist-vendored

src/grammar.json -diff
src/node-types.json -diff
src/parser.c -diff
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI

on:
push:
branches:
- master
pull_request:
branches:
- "**"

jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: true
matrix:
os: [macos-latest, ubuntu-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v2
with:
node-version: 16
- run: npm install
- run: npm test

test_windows:
runs-on: windows-2019
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v2
with:
node-version: 16
- run: npm install
- run: npm run-script test-windows
22 changes: 22 additions & 0 deletions .github/workflows/fuzz.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: Fuzz Parser

on:
push:
paths:
- src/scanner.cc
pull_request:
paths:
- src/scanner.cc

jobs:
test:
name: Parser fuzzing
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: vigoux/tree-sitter-fuzz-action@v1
- run: npm install
with:
language: starlark
external-scanner: src/scanner.cc
time: 60
51 changes: 51 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name: Publish

on:
push:
branches:
- master
tags:
- "v*"
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- run: npm install
- run: npm test

publish-npm:
if: startsWith(github.ref, 'refs/tags/v')
needs: build
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
registry-url: https://registry.npmjs.org/
- run: npm install
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}

publish-crates:
if: startsWith(github.ref, 'refs/tags/v')
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
override: true
- uses: katyo/publish-crates@v2
with:
registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }}
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Cargo.lock
package-lock.json
/build
/node_modules
/examples/*/
/target
22 changes: 22 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "tree-sitter-starlark"
description = "Starlark grammar for tree-sitter"
version = "0.0.1"
authors = ["Amaan Qureshi <amaanq12@gmail.com>"]
keywords = ["incremental", "parsing", "starlark", "bazel", "bzl"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/amaanq/tree-sitter-starlark"
edition = "2021"
license = "MIT"

build = "bindings/rust/build.rs"
include = ["bindings/rust/*", "grammar.js", "queries/*", "src/*"]

[lib]
path = "bindings/rust/lib.rs"

[dependencies]
tree-sitter = "~0.20.3"

[build-dependencies]
cc = "1.0"
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2023 Amaan Qureshi <amaanq12@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# tree-sitter-starlark

[![Build Status](https://github.com/amaanq/tree-sitter-starlark/actions/workflows/ci.yml/badge.svg)](https://github.com/amaanq/tree-sitter-starlark/actions/workflows/ci.yml)
[![Discord](https://img.shields.io/discord/1063097320771698699?logo=discord)](https://discord.gg/w7nTvsVJhm)

Starlark grammar for [tree-sitter](https://github.com/tree-sitter/tree-sitter)

Adapted from the [official spec](https://github.com/bazelbuild/starlark/blob/master/spec.md)
and the [Google spec](https://github.com/google/starlark-go/blob/master/doc/spec.md)
19 changes: 19 additions & 0 deletions binding.gyp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"targets": [
{
"target_name": "tree_sitter_starlark_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
],
"sources": [
"bindings/node/binding.cc",
"src/parser.c",
"src/scanner.cc",
],
"cflags_c": [
"-std=c99",
]
}
]
}
30 changes: 30 additions & 0 deletions bindings/node/binding.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include "nan.h"
#include "tree_sitter/parser.h"
#include <node.h>

using namespace v8;

extern "C" TSLanguage *tree_sitter_starlark();

namespace {

NAN_METHOD(New) {}

void Init(Local<Object> exports, Local<Object> module) {
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Language").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);

Local<Function> constructor = Nan::GetFunction(tpl).ToLocalChecked();
Local<Object> instance =
constructor->NewInstance(Nan::GetCurrentContext()).ToLocalChecked();
Nan::SetInternalFieldPointer(instance, 0, tree_sitter_starlark());

Nan::Set(instance, Nan::New("name").ToLocalChecked(),
Nan::New("starlark").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}

NODE_MODULE(tree_sitter_starlark_binding, Init)

} // namespace
19 changes: 19 additions & 0 deletions bindings/node/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
try {
module.exports = require('../../build/Release/tree_sitter_starlark_binding');
} catch (error1) {
if (error1.code !== 'MODULE_NOT_FOUND') {
throw error1;
}
try {
module.exports = require('../../build/Debug/tree_sitter_starlark_binding');
} catch (error2) {
if (error2.code !== 'MODULE_NOT_FOUND') {
throw error2;
}
throw error1;
}
}

try {
module.exports.nodeTypeInfo = require('../../src/node-types.json');
} catch (_) {}
38 changes: 38 additions & 0 deletions bindings/rust/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
fn main() {
let src_dir = std::path::Path::new("src");

let mut c_config = cc::Build::new();
c_config.include(src_dir);
c_config
.flag_if_supported("-Wno-unused-parameter")
.flag_if_supported("-Wno-unused-but-set-variable")
.flag_if_supported("-Wno-trigraphs");
let parser_path = src_dir.join("parser.c");
c_config.file(&parser_path);

// If your language uses an external scanner written in C,
// then include this block of code:

/*
let scanner_path = src_dir.join("scanner.c");
c_config.file(&scanner_path);
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
*/

c_config.compile("parser");
println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap());

// If your language uses an external scanner written in C++,
// then include this block of code:

let mut cpp_config = cc::Build::new();
cpp_config.cpp(true);
cpp_config.include(src_dir);
cpp_config
.flag_if_supported("-Wno-unused-parameter")
.flag_if_supported("-Wno-unused-but-set-variable");
let scanner_path = src_dir.join("scanner.cc");
cpp_config.file(&scanner_path);
cpp_config.compile("scanner");
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
}
52 changes: 52 additions & 0 deletions bindings/rust/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//! This crate provides starlark language support for the [tree-sitter][] parsing library.
//!
//! Typically, you will use the [language][language func] function to add this language to a
//! tree-sitter [Parser][], and then use the parser to parse some code:
//!
//! ```
//! let code = "";
//! let mut parser = tree_sitter::Parser::new();
//! parser.set_language(tree_sitter_starlark::language()).expect("Error loading starlark grammar");
//! let tree = parser.parse(code, None).unwrap();
//! ```
//!
//! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
//! [language func]: fn.language.html
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/

use tree_sitter::Language;

extern "C" {
fn tree_sitter_starlark() -> Language;
}

/// Get the tree-sitter [Language][] for this grammar.
///
/// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
pub fn language() -> Language {
unsafe { tree_sitter_starlark() }
}

/// The content of the [`node-types.json`][] file for this grammar.
///
/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types
pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");

// Uncomment these to include any queries that this grammar contains

pub const HIGHLIGHTS_QUERY: &str = include_str!("../../queries/highlights.scm");
pub const INJECTIONS_QUERY: &str = include_str!("../../queries/injections.scm");
pub const LOCALS_QUERY: &str = include_str!("../../queries/locals.scm");
// pub const TAGS_QUERY: &'static str = include_str!("../../queries/tags.scm");

#[cfg(test)]
mod tests {
#[test]
fn test_can_load_grammar() {
let mut parser = tree_sitter::Parser::new();
parser
.set_language(super::language())
.expect("Error loading starlark language");
}
}
11 changes: 11 additions & 0 deletions examples/01-syntax.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
def fizz_buzz(n):
"""Print Fizz Buzz numbers from 1 to n."""
for i in range(1, n + 1):
s = ""
if i % 3 == 0:
s += "Fizz"
if i % 5 == 0:
s += "Buzz"
print(s if s else i)

fizz_buzz(20)
7 changes: 7 additions & 0 deletions examples/02-foo.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# `foo.bzl`
var = [] # declare a list

def fct(): # declare a function
var.append(5) # append a value to the list

fct() # execute the fct function
6 changes: 6 additions & 0 deletions examples/03-bar.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# `bar.bzl`
load(":foo.bzl", "var", "fct") # loads `var`, and `fct` from `./foo.bzl`

var.append(6) # runtime error, the list stored in var is frozen

fct() # runtime error, fct() attempts to modify a frozen list
Loading

0 comments on commit 12d06b8

Please sign in to comment.