feat: improve language bindings

Co-authored-by: ObserverOfTime <chronobserver@disroot.org>
This commit is contained in:
Amaan Qureshi 2024-02-21 11:47:59 -05:00
parent d0d349c02b
commit 9e5bf6591f
32 changed files with 1132 additions and 195 deletions

View file

@ -0,0 +1,16 @@
#ifndef TREE_SITTER_UPPER_PARSER_NAME_H_
#define TREE_SITTER_UPPER_PARSER_NAME_H_
typedef struct TSLanguage TSLanguage;
#ifdef __cplusplus
extern "C" {
#endif
extern const TSLanguage *tree_sitter_PARSER_NAME(void);
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_UPPER_PARSER_NAME_H_

View file

@ -0,0 +1,11 @@
prefix=@PREFIX@
libdir=@LIBDIR@
includedir=@INCLUDEDIR@
Name: tree-sitter-PARSER_NAME
Description: PARSER_NAME grammar for tree-sitter
URL: @URL@
Version: @VERSION@
Requires: @REQUIRES@
Libs: -L${libdir} @ADDITIONAL_LIBS@ -ltree-sitter-PARSER_NAME
Cflags: -I${includedir}

View file

@ -0,0 +1,24 @@
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "TreeSitterCAMEL_PARSER_NAME",
platforms: [.macOS(.v10_13), .iOS(.v11)],
products: [
.library(name: "TreeSitterCAMEL_PARSER_NAME", targets: ["TreeSitterCAMEL_PARSER_NAME"]),
],
dependencies: [],
targets: [
.target(name: "TreeSitterCAMEL_PARSER_NAME",
path: ".",
sources: [
"src/parser.c",
// NOTE: if your language has an external scanner, add it here.
],
resources: [
.copy("queries")
],
publicHeadersPath: "bindings/swift",
cSettings: [.headerSearchPath("src")])
]
)

View file

@ -0,0 +1,3 @@
"CAMEL_PARSER_NAME grammar for tree-sitter"
from ._binding import language

View file

@ -0,0 +1 @@
def language() -> int: ...

View file

@ -1,28 +0,0 @@
#include "tree_sitter/parser.h"
#include <node.h>
#include "nan.h"
using namespace v8;
extern "C" TSLanguage * tree_sitter_PARSER_NAME();
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_PARSER_NAME());
Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("PARSER_NAME").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}
NODE_MODULE_CONTEXT_AWARE(tree_sitter_PARSER_NAME_binding, Init)
} // namespace

View file

@ -0,0 +1,13 @@
package tree_sitter_PARSER_NAME
// #cgo CFLAGS: -std=c11 -fPIC
// #include "../../src/parser.c"
// // NOTE: if your language has an external scanner, add it here.
import "C"
import "unsafe"
// Get the tree-sitter Language for this grammar.
func Language() unsafe.Pointer {
return unsafe.Pointer(C.tree_sitter_LOWER_PARSER_NAME())
}

View file

@ -4,15 +4,18 @@
"target_name": "tree_sitter_PARSER_NAME_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
"src",
],
"sources": [
"bindings/node/binding.cc",
"src/parser.c",
# If your language uses an external scanner, add it here.
# NOTE: if your language has an external scanner, add it here.
],
"cflags_c": [
"-std=c99",
"-std=c11",
],
"cflags_cc": [
"-Wno-cast-function-type",
]
}
]

View file

@ -0,0 +1,15 @@
package tree_sitter_PARSER_NAME_test
import (
"testing"
tree_sitter "github.com/smacker/go-tree-sitter"
"github.com/tree-sitter/tree-sitter-PARSER_NAME"
)
func TestCanLoadGrammar(t *testing.T) {
language := tree_sitter.NewLanguage(tree_sitter_PARSER_NAME.Language())
if language == nil {
t.Errorf("Error loading CAMEL_PARSER_NAME grammar")
}
}

View file

@ -2,16 +2,11 @@ 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");
c_config.include(src_dir);
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:
// NOTE: if your language uses an external scanner, uncomment this block:
/*
let scanner_path = src_dir.join("scanner.c");
@ -19,22 +14,6 @@ fn main() {
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
*/
c_config.compile("parser");
c_config.compile("tree-sitter-PARSER_NAME");
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());
*/
}

View file

@ -1,26 +1,23 @@
[package]
name = "tree-sitter-PARSER_NAME"
description = "PARSER_NAME grammar for the tree-sitter parsing library"
description = "PARSER_NAME grammar for tree-sitter"
version = "0.0.1"
license = "MIT"
readme = "bindings/rust/README.md"
keywords = ["incremental", "parsing", "PARSER_NAME"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/tree-sitter/tree-sitter-PARSER_NAME"
edition = "2018"
license = "MIT"
edition = "2021"
autoexamples = false
build = "bindings/rust/build.rs"
include = [
"bindings/rust/*",
"grammar.js",
"queries/*",
"src/*",
]
include = ["bindings/rust/*", "grammar.js", "queries/*", "src/*"]
[lib]
path = "bindings/rust/lib.rs"
[dependencies]
tree-sitter = "~RUST_BINDING_VERSION"
tree-sitter = ">=RUST_BINDING_VERSION"
[build-dependencies]
cc = "1.0"
cc = "1.0.87"

View file

@ -0,0 +1,41 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{json,toml,yml}]
indent_style = space
indent_size = 2
[*.js]
quote_type = double
indent_style = space
indent_size = 2
[*.rs]
indent_style = space
indent_size = 4
[*.{c,cc,h}]
indent_style = space
indent_size = 4
[*.{py,pyi}]
quote_type = double
indent_style = space
indent_size = 4
[*.swift]
indent_style = space
indent_size = 4
[*.go]
indent_style = tab
indent_size = 8
[Makefile]
indent_style = tab
indent_size = 8

View file

@ -0,0 +1,10 @@
* text eol=lf
src/*.json linguist-generated
src/parser.c linguist-generated
src/tree_sitter/* linguist-generated
bindings/** linguist-generated
binding.gyp linguist-generated
setup.py linguist-generated
Makefile linguist-generated

View file

@ -0,0 +1,36 @@
# Rust artifacts
/Cargo.lock
/target/
# Node artifacts
/build/
/node_modules/
# Swift artifacts
/.build/
# Python artifacts
/dist/
*.egg-info
*.whl
# Zig artifacts
/zig-cache/
/zig-out/
# C artifacts
*.a
*.so
*.so.*
*.dylib
*.dll
*.pc
# Example dirs
/examples/*/
# Grammar volatiles
dsl.d.ts
*.wasm
*.obj
*.o

View file

@ -0,0 +1,5 @@
module github.com/tree-sitter/tree-sitter-PARSER_NAME
go 1.22
require github.com/smacker/go-tree-sitter v0.0.0-20230720070738-0d0a9f78d8f8

View file

@ -0,0 +1,11 @@
/// <reference types="./types/dsl" />
// @ts-check
module.exports = grammar({
name: "LOWER_PARSER_NAME",
rules: {
// TODO: add the actual grammar rules
source_file: $ => "hello"
}
});

View file

@ -1,13 +1,13 @@
try {
module.exports = require("../../build/Release/tree_sitter_PARSER_NAME_binding");
} catch (error1) {
if (error1.code !== 'MODULE_NOT_FOUND') {
if (error1.code !== "MODULE_NOT_FOUND") {
throw error1;
}
try {
module.exports = require("../../build/Debug/tree_sitter_PARSER_NAME_binding");
} catch (error2) {
if (error2.code !== 'MODULE_NOT_FOUND') {
if (error2.code !== "MODULE_NOT_FOUND") {
throw error2;
}
throw error1

View file

@ -0,0 +1,29 @@
#include "nan.h"
#include <node.h>
using namespace v8;
typedef struct TSLanguage TSLanguage;
extern "C" const TSLanguage *tree_sitter_PARSER_NAME(void);
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, (void *)tree_sitter_PARSER_NAME());
Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("PARSER_NAME").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}
NODE_MODULE_CONTEXT_AWARE(tree_sitter_PARSER_NAME_binding, Init)
} // namespace

View file

@ -1,13 +1,15 @@
//! This crate provides PARSER_NAME language support for the [tree-sitter][] parsing library.
//! This crate provides CAMEL_PARSER_NAME 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 code = r#"
//! "#;
//! let mut parser = tree_sitter::Parser::new();
//! parser.set_language(tree_sitter_PARSER_NAME::language()).expect("Error loading PARSER_NAME grammar");
//! parser.set_language(&tree_sitter_PARSER_NAME::language()).expect("Error loading CAMEL_PARSER_NAME grammar");
//! let tree = parser.parse(code, None).unwrap();
//! assert!(!tree.root_node().has_error());
//! ```
//!
//! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
@ -31,14 +33,14 @@ pub fn language() -> Language {
/// 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: &'static str = include_str!("../../src/node-types.json");
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: &'static str = include_str!("../../queries/highlights.scm");
// pub const INJECTIONS_QUERY: &'static str = include_str!("../../queries/injections.scm");
// pub const LOCALS_QUERY: &'static str = include_str!("../../queries/locals.scm");
// pub const TAGS_QUERY: &'static str = include_str!("../../queries/tags.scm");
// 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: &str = include_str!("../../queries/tags.scm");
#[cfg(test)]
mod tests {
@ -46,7 +48,7 @@ mod tests {
fn test_can_load_grammar() {
let mut parser = tree_sitter::Parser::new();
parser
.set_language(super::language())
.expect("Error loading PARSER_NAME language");
.set_language(&super::language())
.expect("Error loading CAMEL_PARSER_NAME language");
}
}

View file

@ -0,0 +1,94 @@
VERSION := 0.0.1
LANGUAGE_NAME := tree-sitter-PARSER_NAME
# repository
SRC_DIR := src
PARSER_REPO_URL := $(shell git -C $(SRC_DIR) remote get-url origin 2>/dev/null)
ifeq ($(PARSER_URL),)
PARSER_URL := $(subst .git,,$(PARSER_REPO_URL))
ifeq ($(shell echo $(PARSER_URL) | grep '^[a-z][-+.0-9a-z]*://'),)
PARSER_URL := $(subst :,/,$(PARSER_URL))
PARSER_URL := $(subst git@,https://,$(PARSER_URL))
endif
endif
# ABI versioning
SONAME_MAJOR := $(word 1,$(subst ., ,$(VERSION)))
SONAME_MINOR := $(word 2,$(subst ., ,$(VERSION)))
# install directory layout
PREFIX ?= /usr/local
INCLUDEDIR ?= $(PREFIX)/include
LIBDIR ?= $(PREFIX)/lib
PCLIBDIR ?= $(LIBDIR)/pkgconfig
# object files
OBJS := $(patsubst %.c,%.o,$(wildcard $(SRC_DIR)/*.c))
# flags
ARFLAGS := rcs
override CFLAGS += -I$(SRC_DIR) -std=c11
# OS-specific bits
ifeq ($(shell uname),Darwin)
SOEXT = dylib
SOEXTVER_MAJOR = $(SONAME_MAJOR).dylib
SOEXTVER = $(SONAME_MAJOR).$(SONAME_MINOR).dylib
LINKSHARED := $(LINKSHARED)-dynamiclib -Wl,
ifneq ($(ADDITIONAL_LIBS),)
LINKSHARED := $(LINKSHARED)$(ADDITIONAL_LIBS),
endif
LINKSHARED := $(LINKSHARED)-install_name,$(LIBDIR)/lib$(LANGUAGE_NAME).$(SONAME_MAJOR).dylib,-rpath,@executable_path/../Frameworks
else ifneq ($(filter $(shell uname),Linux FreeBSD NetBSD DragonFly),)
SOEXT = so
SOEXTVER_MAJOR = so.$(SONAME_MAJOR)
SOEXTVER = so.$(SONAME_MAJOR).$(SONAME_MINOR)
LINKSHARED := $(LINKSHARED)-shared -Wl,
ifneq ($(ADDITIONAL_LIBS),)
LINKSHARED := $(LINKSHARED)$(ADDITIONAL_LIBS)
endif
LINKSHARED := $(LINKSHARED)-soname,lib$(LANGUAGE_NAME).so.$(SONAME_MAJOR)
else ifeq ($(OS),Windows_NT)
$(error "Windows is not supported")
endif
ifneq ($(filter $(shell uname),FreeBSD NetBSD DragonFly),)
PCLIBDIR := $(PREFIX)/libdata/pkgconfig
endif
all: lib$(LANGUAGE_NAME).a lib$(LANGUAGE_NAME).$(SOEXT) $(LANGUAGE_NAME).pc
$(SRC_DIR)/%.o: $(SRC_DIR)/%.c
$(CC) -c $^ -o $@
lib$(LANGUAGE_NAME).a: $(OBJS)
$(AR) $(ARFLAGS) $@ $^
lib$(LANGUAGE_NAME).$(SOEXT): $(OBJS)
$(CC) -fPIC $(LDFLAGS) $(LINKSHARED) $^ $(LDLIBS) -o $@
$(LANGUAGE_NAME).pc:
sed > $@ bindings/c/$(LANGUAGE_NAME).pc.in \
-e 's|@URL@|$(PARSER_URL)|' \
-e 's|@VERSION@|$(VERSION)|' \
-e 's|@LIBDIR@|$(LIBDIR)|;' \
-e 's|@INCLUDEDIR@|$(INCLUDEDIR)|;' \
-e 's|=$(PREFIX)|=$${prefix}|' \
-e 's|@PREFIX@|$(PREFIX)|' \
-e 's|@REQUIRES@|$(REQUIRES)|' \
-e 's|@ADDITIONAL_LIBS@|$(ADDITIONAL_LIBS)|'
install: all
install -Dm644 bindings/c/$(LANGUAGE_NAME).h '$(DESTDIR)$(INCLUDEDIR)'/tree_sitter/$(LANGUAGE_NAME).h
install -Dm644 $(LANGUAGE_NAME).pc '$(DESTDIR)$(PCLIBDIR)'/$(LANGUAGE_NAME).pc
install -Dm755 lib$(LANGUAGE_NAME).a '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).a
install -Dm755 lib$(LANGUAGE_NAME).$(SOEXT) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER)
ln -sf lib$(LANGUAGE_NAME).$(SOEXTVER) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER_MAJOR)
ln -sf lib$(LANGUAGE_NAME).$(SOEXTVER_MAJOR) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXT)
clean:
$(RM) $(OBJS) $(LANGUAGE_NAME).pc lib$(LANGUAGE_NAME).a lib$(LANGUAGE_NAME).$(SOEXT)
.PHONY: all install clean

View file

@ -1,19 +1,31 @@
{
"name": "tree-sitter-PARSER_NAME",
"version": "0.0.1",
"description": "PARSER_NAME grammar for tree-sitter",
"description": "CAMEL_PARSER_NAME grammar for tree-sitter",
"repository": "github:tree-sitter/tree-sitter-PARSER_NAME",
"license": "MIT",
"main": "bindings/node",
"keywords": [
"parsing",
"incremental"
"incremental",
"LOWER_PARSER_NAME"
],
"dependencies": {
"nan": "^2.12.1"
"nan": "^2.18.0"
},
"devDependencies": {
"tree-sitter-cli": "^CLI_VERSION"
},
"scripts": {
"test": "tree-sitter test"
}
"build": "tree-sitter generate --no-bindings",
"build-wasm": "tree-sitter build-wasm",
"test": "tree-sitter test",
"parse": "tree-sitter parse"
},
"tree-sitter": [
{
"scope": "source.LOWER_PARSER_NAME",
"injection-regex": "LOWER_PARSER_NAME"
}
]
}

View file

@ -0,0 +1,27 @@
#include <Python.h>
typedef struct TSLanguage TSLanguage;
extern const TSLanguage *tree_sitter_LOWER_PARSER_NAME(void);
static PyObject* _binding_language(PyObject *self, PyObject *args) {
return PyLong_FromVoidPtr((void *)tree_sitter_LOWER_PARSER_NAME());
}
static PyMethodDef methods[] = {
{"language", _binding_language, METH_NOARGS,
"Get the tree-sitter language for this grammar."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef module = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "_binding",
.m_doc = NULL,
.m_size = -1,
.m_methods = methods
};
PyMODINIT_FUNC PyInit__binding(void) {
return PyModule_Create(&module);
}

View file

@ -0,0 +1,26 @@
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "tree-sitter-PARSER_NAME"
description = "CAMEL_PARSER_NAME grammar for tree-sitter"
version = "0.0.1"
keywords = ["parsing", "incremental", "PARSER_NAME"]
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Software Development :: Compilers",
"Topic :: Text Processing :: Linguistic",
]
requires-python = ">=3.8"
license.file = "LICENSE"
readme = "README.md"
[project.optional-dependencies]
core = ["tree-sitter~=0.21"]
[tool.cibuildwheel]
build = "cp38-*"
build-frontend = "build"

View file

@ -0,0 +1,49 @@
from os.path import join
from setuptools import Extension, find_packages, setup
from setuptools.command.build import build
from wheel.bdist_wheel import bdist_wheel
class Build(build):
def run(self):
dest = join(self.build_lib, "tree_sitter_PARSER_NAME", "queries")
try:
self.copy_tree("queries", dest)
except:
pass
super().run()
class BdistWheel(bdist_wheel):
def get_tag(self):
python, abi, platform = super().get_tag()
if python.startswith("cp"):
python, abi = "cp38", "abi3"
return python, abi, platform
setup(
packages=find_packages("bindings/python"),
package_dir={"": "bindings/python"},
package_data={
"tree_sitter_LOWER_PARSER_NAME": ["*.pyi", "py.typed"],
"tree_sitter_LOWER_PARSER_NAME.queries": ["*.scm"],
},
ext_package="tree_sitter_LOWER_PARSER_NAME",
ext_modules=[
Extension(
name="_binding",
sources=[
"bindings/python/tree_sitter_LOWER_PARSER_NAME/binding.c",
"src/parser.c",
# NOTE: if your language uses an external scanner, add it here.
],
extra_compile_args=["-std=c11"],
define_macros=[("Py_LIMITED_API", "0x03080000"), ("PY_SSIZE_T_CLEAN", None)],
include_dirs=["src"],
py_limited_api=True,
)
],
cmdclass={"build": Build, "bdist_wheel": BdistWheel},
zip_safe=False,
)