diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..d3a8b5b6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,39 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{json,toml,yml,gyp}] +indent_style = space +indent_size = 2 + +[*.js] +indent_style = space +indent_size = 2 + +[*.rs] +indent_style = space +indent_size = 4 + +[*.{c,cc,h}] +indent_style = space +indent_size = 4 + +[*.{py,pyi}] +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 diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..832fa5df --- /dev/null +++ b/Makefile @@ -0,0 +1,110 @@ +VERSION := 0.0.1 + +LANGUAGE_NAME := tree-sitter-javascript + +# 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 + +TS ?= tree-sitter + +# 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 -fPIC + +# OS-specific bits +ifeq ($(OS),Windows_NT) + $(error "Windows is not supported") +else 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 + 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) +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 + +lib$(LANGUAGE_NAME).a: $(OBJS) + $(AR) $(ARFLAGS) $@ $^ + +lib$(LANGUAGE_NAME).$(SOEXT): $(OBJS) + $(CC) $(LDFLAGS) $(LINKSHARED) $^ $(LDLIBS) -o $@ +ifneq ($(STRIP),) + $(STRIP) $@ +endif + +$(LANGUAGE_NAME).pc: bindings/c/$(LANGUAGE_NAME).pc.in + sed -e 's|@URL@|$(PARSER_URL)|' \ + -e 's|@VERSION@|$(VERSION)|' \ + -e 's|@LIBDIR@|$(LIBDIR)|' \ + -e 's|@INCLUDEDIR@|$(INCLUDEDIR)|' \ + -e 's|@REQUIRES@|$(REQUIRES)|' \ + -e 's|@ADDITIONAL_LIBS@|$(ADDITIONAL_LIBS)|' \ + -e 's|=$(PREFIX)|=$${prefix}|' \ + -e 's|@PREFIX@|$(PREFIX)|' $< > $@ + +$(SRC_DIR)/parser.c: grammar.js + $(TS) generate --no-bindings + +install: all + install -d '$(DESTDIR)$(INCLUDEDIR)'/tree_sitter '$(DESTDIR)$(PCLIBDIR)' '$(DESTDIR)$(LIBDIR)' + install -m644 bindings/c/$(LANGUAGE_NAME).h '$(DESTDIR)$(INCLUDEDIR)'/tree_sitter/$(LANGUAGE_NAME).h + install -m644 $(LANGUAGE_NAME).pc '$(DESTDIR)$(PCLIBDIR)'/$(LANGUAGE_NAME).pc + install -m644 lib$(LANGUAGE_NAME).a '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).a + install -m755 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) + +uninstall: + $(RM) '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).a \ + '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER) \ + '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXTVER_MAJOR) \ + '$(DESTDIR)$(LIBDIR)'/lib$(LANGUAGE_NAME).$(SOEXT) \ + '$(DESTDIR)$(INCLUDEDIR)'/tree_sitter/$(LANGUAGE_NAME).h \ + '$(DESTDIR)$(PCLIBDIR)'/$(LANGUAGE_NAME).pc + +clean: + $(RM) $(OBJS) $(LANGUAGE_NAME).pc lib$(LANGUAGE_NAME).a lib$(LANGUAGE_NAME).$(SOEXT) + +test: + $(TS) test + +.PHONY: all install uninstall clean test diff --git a/Package.swift b/Package.swift index feb7ed8b..5efbffaa 100644 --- a/Package.swift +++ b/Package.swift @@ -2,13 +2,13 @@ import PackageDescription let package = Package( - name: "TreeSitterJS", + name: "TreeSitterJavascript", products: [ - .library(name: "TreeSitterJS", targets: ["TreeSitterJS"]), + .library(name: "TreeSitterJavascript", targets: ["TreeSitterJavascript"]), ], dependencies: [], targets: [ - .target(name: "TreeSitterJS", + .target(name: "TreeSitterJavascript", path: ".", exclude: [ "binding.gyp", @@ -35,4 +35,4 @@ let package = Package( publicHeadersPath: "bindings/swift", cSettings: [.headerSearchPath("src")]) ] -) \ No newline at end of file +) diff --git a/binding.gyp b/binding.gyp index c60dff7a..3df7b625 100644 --- a/binding.gyp +++ b/binding.gyp @@ -2,18 +2,20 @@ "targets": [ { "target_name": "tree_sitter_javascript_binding", + "dependencies": [ + " -#include "nan.h" +#include -using namespace v8; +typedef struct TSLanguage TSLanguage; -extern "C" TSLanguage * tree_sitter_javascript(); +extern "C" TSLanguage *tree_sitter_javascript(); -namespace { +// "tree-sitter", "language" hashed with BLAKE2 +const napi_type_tag LANGUAGE_TYPE_TAG = { + 0x8AF2E5212AD58ABF, 0xD5006CAD83ABBA16 +}; -NAN_METHOD(New) {} - -void Init(Local exports, Local module) { - Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("Language").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - Local constructor = Nan::GetFunction(tpl).ToLocalChecked(); - Local instance = constructor->NewInstance(Nan::GetCurrentContext()).ToLocalChecked(); - Nan::SetInternalFieldPointer(instance, 0, tree_sitter_javascript()); - - Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("javascript").ToLocalChecked()); - Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance); +Napi::Object Init(Napi::Env env, Napi::Object exports) { + exports["name"] = Napi::String::New(env, "javascript"); + auto language = Napi::External::New(env, tree_sitter_javascript()); + language.TypeTag(&LANGUAGE_TYPE_TAG); + exports["language"] = language; + return exports; } -NODE_MODULE(tree_sitter_javascript_binding, Init) - -} // namespace +NODE_API_MODULE(tree_sitter_javascript_binding, Init) diff --git a/bindings/node/index.d.ts b/bindings/node/index.d.ts new file mode 100644 index 00000000..efe259ee --- /dev/null +++ b/bindings/node/index.d.ts @@ -0,0 +1,28 @@ +type BaseNode = { + type: string; + named: boolean; +}; + +type ChildNode = { + multiple: boolean; + required: boolean; + types: BaseNode[]; +}; + +type NodeInfo = + | (BaseNode & { + subtypes: BaseNode[]; + }) + | (BaseNode & { + fields: { [name: string]: ChildNode }; + children: ChildNode[]; + }); + +type Language = { + name: string; + language: unknown; + nodeTypeInfo: NodeInfo[]; +}; + +declare const language: Language; +export = language; diff --git a/bindings/node/index.js b/bindings/node/index.js index 18707655..6657bcf4 100644 --- a/bindings/node/index.js +++ b/bindings/node/index.js @@ -1,18 +1,6 @@ -try { - module.exports = require("../../build/Release/tree_sitter_javascript_binding"); -} catch (error1) { - if (error1.code !== 'MODULE_NOT_FOUND') { - throw error1; - } - try { - module.exports = require("../../build/Debug/tree_sitter_javascript_binding"); - } catch (error2) { - if (error2.code !== 'MODULE_NOT_FOUND') { - throw error2; - } - throw error1 - } -} +const root = require("path").join(__dirname, "..", ".."); + +module.exports = require("node-gyp-build")(root); try { module.exports.nodeTypeInfo = require("../../src/node-types.json"); diff --git a/bindings/python/tree_sitter_javascript/__init__.py b/bindings/python/tree_sitter_javascript/__init__.py new file mode 100644 index 00000000..21235548 --- /dev/null +++ b/bindings/python/tree_sitter_javascript/__init__.py @@ -0,0 +1,5 @@ +"Javascript grammar for tree-sitter" + +from ._binding import language + +__all__ = ["language"] diff --git a/bindings/python/tree_sitter_javascript/__init__.pyi b/bindings/python/tree_sitter_javascript/__init__.pyi new file mode 100644 index 00000000..5416666f --- /dev/null +++ b/bindings/python/tree_sitter_javascript/__init__.pyi @@ -0,0 +1 @@ +def language() -> int: ... diff --git a/bindings/python/tree_sitter_javascript/binding.c b/bindings/python/tree_sitter_javascript/binding.c new file mode 100644 index 00000000..d255b6af --- /dev/null +++ b/bindings/python/tree_sitter_javascript/binding.c @@ -0,0 +1,27 @@ +#include + +typedef struct TSLanguage TSLanguage; + +TSLanguage *tree_sitter_javascript(void); + +static PyObject* _binding_language(PyObject *self, PyObject *args) { + return PyLong_FromVoidPtr(tree_sitter_javascript()); +} + +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); +} diff --git a/bindings/python/tree_sitter_javascript/py.typed b/bindings/python/tree_sitter_javascript/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/bindings/swift/TreeSitterJS/javascript.h b/bindings/swift/TreeSitterJavascript/javascript.h similarity index 67% rename from bindings/swift/TreeSitterJS/javascript.h rename to bindings/swift/TreeSitterJavascript/javascript.h index 29cc18db..c3fffbac 100644 --- a/bindings/swift/TreeSitterJS/javascript.h +++ b/bindings/swift/TreeSitterJavascript/javascript.h @@ -7,10 +7,10 @@ typedef struct TSLanguage TSLanguage; extern "C" { #endif -extern TSLanguage *tree_sitter_javascript(); +const TSLanguage *tree_sitter_javascript(void); #ifdef __cplusplus } #endif -#endif // TREE_SITTER_JAVASCRIPT_H_ \ No newline at end of file +#endif // TREE_SITTER_JAVASCRIPT_H_ diff --git a/package.json b/package.json index 7fcfc947..1a8d6ffe 100644 --- a/package.json +++ b/package.json @@ -3,11 +3,20 @@ "version": "0.20.4", "description": "JavaScript grammar for tree-sitter", "main": "bindings/node", + "types": "bindings/node", "keywords": [ "parser", "lexer", "javascript" ], + "files": [ + "grammar.js", + "binding.gyp", + "prebuilds/**", + "bindings/node/*", + "queries/*", + "src/**" + ], "repository": { "type": "git", "url": "https://github.com/tree-sitter/tree-sitter-javascript.git" @@ -15,19 +24,31 @@ "author": "Max Brunsfeld", "license": "MIT", "dependencies": { - "nan": "^2.18.0" + "node-addon-api": "^7.1.0", + "node-gyp-build": "^4.8.0" + }, + "peerDependencies": { + "tree-sitter": "^0.21.0" + }, + "peerDependenciesMeta": { + "tree_sitter": { + "optional": true + } }, "devDependencies": { "eslint": "^8.57.0", "eslint-config-google": "^0.14.0", - "tree-sitter-cli": "^0.21.0" + "tree-sitter-cli": "^0.21.0", + "prebuildify": "^6.0.0" }, "scripts": { "build": "tree-sitter generate && node-gyp build", "lint": "eslint grammar.js", "parse": "tree-sitter parse", "test": "tree-sitter test && script/parse-examples", - "test-windows": "tree-sitter test" + "test-windows": "tree-sitter test", + "install": "node-gyp-build", + "prebuildify": "prebuildify --napi --strip" }, "tree-sitter": [ { diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..4b3eb1bd --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,29 @@ +[build-system] +requires = ["setuptools>=42", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "tree-sitter-javascript" +description = "Javascript grammar for tree-sitter" +version = "0.0.1" +keywords = ["incremental", "parsing", "tree-sitter", "javascript"] +classifiers = [ + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Topic :: Software Development :: Compilers", + "Topic :: Text Processing :: Linguistic", + "Typing :: Typed" +] +requires-python = ">=3.8" +license.text = "MIT" +readme = "README.md" + +[project.urls] +Homepage = "https://github.com/tree-sitter/tree-sitter-javascript" + +[project.optional-dependencies] +core = ["tree-sitter~=0.21"] + +[tool.cibuildwheel] +build = "cp38-*" +build-frontend = "build" diff --git a/setup.py b/setup.py new file mode 100644 index 00000000..b4e5683c --- /dev/null +++ b/setup.py @@ -0,0 +1,57 @@ +from os.path import isdir, join +from platform import system + +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): + if isdir("queries"): + dest = join(self.build_lib, "tree_sitter_javascript", "queries") + self.copy_tree("queries", dest) + 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_javascript": ["*.pyi", "py.typed"], + "tree_sitter_javascript.queries": ["*.scm"], + }, + ext_package="tree_sitter_javascript", + ext_modules=[ + Extension( + name="_binding", + sources=[ + "bindings/python/tree_sitter_javascript/binding.c", + "src/parser.c", + # NOTE: if your language uses an external scanner, add it here. + ], + extra_compile_args=( + ["-std=c11"] if system() != 'Windows' else [] + ), + 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 +) diff --git a/src/parser.c b/src/parser.c index 30068d29..e03c5f5e 100644 --- a/src/parser.c +++ b/src/parser.c @@ -149918,7 +149918,9 @@ bool tree_sitter_javascript_external_scanner_scan(void *, TSLexer *, const bool unsigned tree_sitter_javascript_external_scanner_serialize(void *, char *); void tree_sitter_javascript_external_scanner_deserialize(void *, const char *, unsigned); -#ifdef _WIN32 +#ifdef TREE_SITTER_HIDE_SYMBOLS +#define TS_PUBLIC +#elif defined(_WIN32) #define TS_PUBLIC __declspec(dllexport) #else #define TS_PUBLIC __attribute__((visibility("default"))) diff --git a/src/tree_sitter/alloc.h b/src/tree_sitter/alloc.h index 1f7610a3..1f4466d7 100644 --- a/src/tree_sitter/alloc.h +++ b/src/tree_sitter/alloc.h @@ -9,19 +9,13 @@ extern "C" { #include #include -#ifdef _WIN32 -#define TS_PUBLIC __declspec(dllexport) -#else -#define TS_PUBLIC __attribute__((visibility("default"))) -#endif - -TS_PUBLIC extern void *(*ts_current_malloc)(size_t); -TS_PUBLIC extern void *(*ts_current_calloc)(size_t, size_t); -TS_PUBLIC extern void *(*ts_current_realloc)(void *, size_t); -TS_PUBLIC extern void (*ts_current_free)(void *); - // Allow clients to override allocation functions -#ifdef TS_REUSE_ALLOCATOR +#ifdef TREE_SITTER_REUSE_ALLOCATOR + +extern void *(*ts_current_malloc)(size_t); +extern void *(*ts_current_calloc)(size_t, size_t); +extern void *(*ts_current_realloc)(void *, size_t); +extern void (*ts_current_free)(void *); #ifndef ts_malloc #define ts_malloc ts_current_malloc diff --git a/src/tree_sitter/array.h b/src/tree_sitter/array.h index 45969242..15a3b233 100644 --- a/src/tree_sitter/array.h +++ b/src/tree_sitter/array.h @@ -15,10 +15,7 @@ extern "C" { #ifdef _MSC_VER #pragma warning(disable : 4101) -#elif defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-variable" -#elif defined(__GNUC__) +#elif defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" #endif @@ -69,9 +66,12 @@ extern "C" { /// Increase the array's size by `count` elements. /// New elements are zero-initialized. #define array_grow_by(self, count) \ - (_array__grow((Array *)(self), count, array_elem_size(self)), \ - memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)), \ - (self)->size += (count)) + do { \ + if ((count) == 0) break; \ + _array__grow((Array *)(self), count, array_elem_size(self)); \ + memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \ + (self)->size += (count); \ + } while (0) /// Append all elements from one array to the end of another. #define array_push_all(self, other) \ @@ -109,9 +109,13 @@ extern "C" { #define array_assign(self, other) \ _array__assign((Array *)(self), (const Array *)(other), array_elem_size(self)) +/// Swap one array with another #define array_swap(self, other) \ _array__swap((Array *)(self), (Array *)(other)) +/// Get the size of the array contents +#define array_elem_size(self) (sizeof *(self)->contents) + /// Search a sorted array for a given `needle` value, using the given `compare` /// callback to determine the order. /// @@ -128,7 +132,7 @@ extern "C" { /// /// See also `array_search_sorted_with`. #define array_search_sorted_by(self, field, needle, _index, _exists) \ - _array__search_sorted(self, 0, compare_int, field, needle, _index, _exists) + _array__search_sorted(self, 0, _compare_int, field, needle, _index, _exists) /// Insert a given `value` into a sorted array, using the given `compare` /// callback to determine the order. @@ -154,8 +158,6 @@ extern "C" { typedef Array(void) Array; -#define array_elem_size(self) sizeof(*(self)->contents) - /// This is not what you're looking for, see `array_delete`. static inline void _array__delete(Array *self) { if (self->contents) { @@ -273,13 +275,11 @@ static inline void _array__splice(Array *self, size_t element_size, /// Helper macro for the `_sorted_by` routines below. This takes the left (existing) /// parameter by reference in order to work with the generic sorting function above. -#define compare_int(a, b) ((int)*(a) - (int)(b)) +#define _compare_int(a, b) ((int)*(a) - (int)(b)) #ifdef _MSC_VER #pragma warning(default : 4101) -#elif defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) +#elif defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif