Showing preview only (289K chars total). Download the full file or copy to clipboard to get everything.
Repository: stsewd/tree-sitter-comment
Branch: master
Commit: 66272d2b6c73
Files: 54
Total size: 273.4 KB
Directory structure:
gitextract_sr4e69ap/
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ ├── ci.yaml
│ └── publish.yml
├── .gitignore
├── CMakeLists.txt
├── Cargo.toml
├── LICENSE
├── Makefile
├── Package.swift
├── README.md
├── binding.gyp
├── bindings/
│ ├── c/
│ │ ├── tree-sitter-comment.pc.in
│ │ └── tree_sitter/
│ │ └── tree-sitter-comment.h
│ ├── go/
│ │ ├── binding.go
│ │ └── binding_test.go
│ ├── node/
│ │ ├── binding.cc
│ │ ├── binding_test.js
│ │ ├── index.d.ts
│ │ └── index.js
│ ├── python/
│ │ ├── tests/
│ │ │ └── test_binding.py
│ │ └── tree_sitter_comment/
│ │ ├── __init__.py
│ │ ├── __init__.pyi
│ │ ├── binding.c
│ │ └── py.typed
│ ├── rust/
│ │ ├── build.rs
│ │ └── lib.rs
│ └── swift/
│ ├── TreeSitterComment/
│ │ └── comment.h
│ └── TreeSitterCommentTests/
│ └── TreeSitterCommentTests.swift
├── compile_flags.txt
├── docs/
│ ├── .nojekyll
│ ├── index.html
│ └── js/
│ ├── playground.js
│ └── tree-sitter.js
├── go.mod
├── grammar.js
├── package.json
├── pyproject.toml
├── setup.py
├── src/
│ ├── grammar.json
│ ├── node-types.json
│ ├── parser.c
│ ├── scanner.c
│ ├── tree_sitter/
│ │ ├── alloc.h
│ │ ├── array.h
│ │ └── parser.h
│ └── tree_sitter_comment/
│ ├── chars.c
│ ├── chars.h
│ ├── parser.c
│ ├── parser.h
│ └── tokens.h
├── test/
│ └── corpus/
│ └── source.txt
└── tree-sitter.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
charset = utf-8
[*.{json,toml,yml,gyp}]
indent_style = space
indent_size = 2
[*.js]
indent_style = space
indent_size = 2
[*.scm]
indent_style = space
indent_size = 2
[*.{c,cc,h}]
indent_style = space
indent_size = 4
[*.rs]
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
[parser.c]
indent_size = 2
[{alloc,array,parser}.h]
indent_size = 2
================================================
FILE: .gitattributes
================================================
* text=auto eol=lf
# Generated source files
src/*.json linguist-generated
src/parser.c linguist-generated
src/tree_sitter/* linguist-generated
# C bindings
bindings/c/** linguist-generated
CMakeLists.txt linguist-generated
Makefile linguist-generated
# Rust bindings
bindings/rust/* linguist-generated
Cargo.toml linguist-generated
Cargo.lock linguist-generated
# Node.js bindings
bindings/node/* linguist-generated
binding.gyp linguist-generated
package.json linguist-generated
package-lock.json linguist-generated
# Python bindings
bindings/python/** linguist-generated
setup.py linguist-generated
pyproject.toml linguist-generated
# Go bindings
bindings/go/* linguist-generated
go.mod linguist-generated
go.sum linguist-generated
# Swift bindings
bindings/swift/** linguist-generated
Package.swift linguist-generated
Package.resolved linguist-generated
# Zig bindings
build.zig linguist-generated
build.zig.zon linguist-generated
================================================
FILE: .github/FUNDING.yml
================================================
github: stsewd
custom:
- https://paypal.me/stsewd
- https://www.buymeacoffee.com/stsewd
================================================
FILE: .github/workflows/ci.yaml
================================================
name: CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up tree-sitter
uses: tree-sitter/setup-action/cli@v2
- name: Run tests
uses: tree-sitter/parser-test-action@v2
with:
test-rust: true
test-node: false
test-python: true
test-go: false
test-swift: false
windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Set up tree-sitter
uses: tree-sitter/setup-action/cli@v2
- name: Run tests
uses: tree-sitter/parser-test-action@v2
with:
test-rust: true
test-node: false
test-python: true
test-go: false
test-swift: false
mac:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: Set up tree-sitter
uses: tree-sitter/setup-action/cli@v2
- name: Run tests
uses: tree-sitter/parser-test-action@v2
with:
test-rust: true
test-node: false
test-python: true
test-go: false
test-swift: false
================================================
FILE: .github/workflows/publish.yml
================================================
name: Publish package
on:
push:
tags: ["*"]
concurrency:
group: ${{github.workflow}}-${{github.ref}}
cancel-in-progress: true
jobs:
npm:
uses: tree-sitter/workflows/.github/workflows/package-npm.yml@main
secrets:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
with:
package-name: "tree-sitter-comment"
crates:
uses: tree-sitter/workflows/.github/workflows/package-crates.yml@main
secrets:
CARGO_REGISTRY_TOKEN: ${{secrets.CARGO_TOKEN}}
with:
package-name: "tree-sitter-comment"
pypi:
uses: tree-sitter/workflows/.github/workflows/package-pypi.yml@main
secrets:
PYPI_API_TOKEN: ${{secrets.PYPI_TOKEN}}
with:
package-name: "tree-sitter-comment"
================================================
FILE: .gitignore
================================================
/log.html
# Rust artifacts
/target
build/
# Node artifacts
build/
prebuilds/
node_modules/
# Swift artifacts
.build/
# Go artifacts
_obj/
# Python artifacts
.venv/
dist/
*.egg-info
*.whl
# C artifacts
*.a
*.so
*.so.*
*.dylib
*.dll
*.pc
*.exp
*.lib
# Zig artifacts
.zig-cache/
zig-cache/
zig-out/
# Example dirs
/examples/*/
# Grammar volatiles
*.wasm
*.obj
*.o
# Archives
*.tar.gz
*.tgz
*.zip
================================================
FILE: CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.13)
project(tree-sitter-comment
VERSION "0.3.0"
DESCRIPTION "Grammar for code tags like TODO:, FIXME(user): for the tree-sitter parsing library"
HOMEPAGE_URL "https://github.com/stsewd/tree-sitter-comment"
LANGUAGES C)
option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
option(TREE_SITTER_REUSE_ALLOCATOR "Reuse the library allocator" OFF)
set(TREE_SITTER_ABI_VERSION 15 CACHE STRING "Tree-sitter ABI version")
if(NOT ${TREE_SITTER_ABI_VERSION} MATCHES "^[0-9]+$")
unset(TREE_SITTER_ABI_VERSION CACHE)
message(FATAL_ERROR "TREE_SITTER_ABI_VERSION must be an integer")
endif()
find_program(TREE_SITTER_CLI tree-sitter DOC "Tree-sitter CLI")
add_custom_command(OUTPUT "${CMAKE_CURRENT_SOURCE_DIR}/src/parser.c"
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/grammar.json"
COMMAND "${TREE_SITTER_CLI}" generate src/grammar.json
--abi=${TREE_SITTER_ABI_VERSION}
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT "Generating parser.c")
add_library(tree-sitter-comment src/parser.c)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/scanner.c)
target_sources(tree-sitter-comment PRIVATE src/scanner.c)
endif()
target_include_directories(tree-sitter-comment
PRIVATE src
INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/bindings/c>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
target_compile_definitions(tree-sitter-comment PRIVATE
$<$<BOOL:${TREE_SITTER_REUSE_ALLOCATOR}>:TREE_SITTER_REUSE_ALLOCATOR>
$<$<CONFIG:Debug>:TREE_SITTER_DEBUG>)
set_target_properties(tree-sitter-comment
PROPERTIES
C_STANDARD 11
POSITION_INDEPENDENT_CODE ON
SOVERSION "${TREE_SITTER_ABI_VERSION}.${PROJECT_VERSION_MAJOR}"
DEFINE_SYMBOL "")
configure_file(bindings/c/tree-sitter-comment.pc.in
"${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-comment.pc" @ONLY)
include(GNUInstallDirs)
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/bindings/c/tree_sitter"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
FILES_MATCHING PATTERN "*.h")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/tree-sitter-comment.pc"
DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig")
install(TARGETS tree-sitter-comment
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}")
file(GLOB QUERIES queries/*.scm)
install(FILES ${QUERIES}
DESTINATION "${CMAKE_INSTALL_DATADIR}/tree-sitter/queries/comment")
add_custom_target(ts-test "${TREE_SITTER_CLI}" test
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
COMMENT "tree-sitter test")
================================================
FILE: Cargo.toml
================================================
[package]
name = "tree-sitter-comment"
description = "Grammar for code tags like TODO:, FIXME(user): for the tree-sitter parsing library"
version = "0.3.0"
authors = ["Santos Gallegos <stsewd@proton.me>"]
license = "MIT"
readme = "README.md"
keywords = ["incremental", "parsing", "tree-sitter", "comment"]
categories = ["parser-implementations", "parsing", "text-editors"]
repository = "https://github.com/stsewd/tree-sitter-comment"
edition = "2021"
autoexamples = false
build = "bindings/rust/build.rs"
include = [
"bindings/rust/*",
"grammar.js",
"queries/*",
"src/*",
"tree-sitter.json",
"LICENSE",
]
[lib]
path = "bindings/rust/lib.rs"
[dependencies]
tree-sitter-language = "0.1"
[build-dependencies]
cc = "1.2"
[dev-dependencies]
tree-sitter = "0.25.3"
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2021 Santos Gallegos
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.
================================================
FILE: Makefile
================================================
ifeq ($(OS),Windows_NT)
$(error Windows is not supported)
endif
LANGUAGE_NAME := tree-sitter-comment
HOMEPAGE_URL := https://github.com/stsewd/tree-sitter-comment
VERSION := 0.3.0
# repository
SRC_DIR := src
TS ?= tree-sitter
# install directory layout
PREFIX ?= /usr/local
DATADIR ?= $(PREFIX)/share
INCLUDEDIR ?= $(PREFIX)/include
LIBDIR ?= $(PREFIX)/lib
PCLIBDIR ?= $(LIBDIR)/pkgconfig
# source/object files
PARSER := $(SRC_DIR)/parser.c
EXTRAS := $(filter-out $(PARSER),$(wildcard $(SRC_DIR)/*.c))
OBJS := $(patsubst %.c,%.o,$(PARSER) $(EXTRAS))
# flags
ARFLAGS ?= rcs
override CFLAGS += -I$(SRC_DIR) -std=c11 -fPIC
# ABI versioning
SONAME_MAJOR = $(shell sed -n 's/\#define LANGUAGE_VERSION //p' $(PARSER))
SONAME_MINOR = $(word 1,$(subst ., ,$(VERSION)))
# OS-specific bits
ifeq ($(shell uname),Darwin)
SOEXT = dylib
SOEXTVER_MAJOR = $(SONAME_MAJOR).$(SOEXT)
SOEXTVER = $(SONAME_MAJOR).$(SONAME_MINOR).$(SOEXT)
LINKSHARED = -dynamiclib -Wl,-install_name,$(LIBDIR)/lib$(LANGUAGE_NAME).$(SOEXTVER),-rpath,@executable_path/../Frameworks
else
SOEXT = so
SOEXTVER_MAJOR = $(SOEXT).$(SONAME_MAJOR)
SOEXTVER = $(SOEXT).$(SONAME_MAJOR).$(SONAME_MINOR)
LINKSHARED = -shared -Wl,-soname,lib$(LANGUAGE_NAME).$(SOEXTVER)
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|@PROJECT_VERSION@|$(VERSION)|' \
-e 's|@CMAKE_INSTALL_LIBDIR@|$(LIBDIR:$(PREFIX)/%=%)|' \
-e 's|@CMAKE_INSTALL_INCLUDEDIR@|$(INCLUDEDIR:$(PREFIX)/%=%)|' \
-e 's|@PROJECT_DESCRIPTION@|$(DESCRIPTION)|' \
-e 's|@PROJECT_HOMEPAGE_URL@|$(HOMEPAGE_URL)|' \
-e 's|@CMAKE_INSTALL_PREFIX@|$(PREFIX)|' $< > $@
$(PARSER): $(SRC_DIR)/grammar.json
$(TS) generate $^
install: all
install -d '$(DESTDIR)$(DATADIR)'/tree-sitter/queries/comment '$(DESTDIR)$(INCLUDEDIR)'/tree_sitter '$(DESTDIR)$(PCLIBDIR)' '$(DESTDIR)$(LIBDIR)'
install -m644 bindings/c/tree_sitter/$(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)
install -m644 queries/*.scm '$(DESTDIR)$(DATADIR)'/tree-sitter/queries/comment
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
$(RM) -r '$(DESTDIR)$(DATADIR)'/tree-sitter/queries/comment
clean:
$(RM) $(OBJS) $(LANGUAGE_NAME).pc lib$(LANGUAGE_NAME).a lib$(LANGUAGE_NAME).$(SOEXT)
test:
$(TS) test
serve: all
npm run build
npm run prestart
npm run start
release: all format
npm run build
npm run prestart
# GitHub pages doesn't like symbolic links
cp tree-sitter-comment.wasm docs/js/tree-sitter-parser.wasm
format:
clang-format -i \
--style="{BasedOnStyle: webkit, IndentWidth: 2}" \
src/scanner.c \
src/tree_sitter_comment/*
.PHONY: all install uninstall clean test serve release format
================================================
FILE: Package.swift
================================================
// swift-tools-version:5.3
import Foundation
import PackageDescription
var sources = ["src/parser.c"]
if FileManager.default.fileExists(atPath: "src/scanner.c") {
sources.append("src/scanner.c")
}
let package = Package(
name: "TreeSitterComment",
products: [
.library(name: "TreeSitterComment", targets: ["TreeSitterComment"]),
],
dependencies: [
.package(url: "https://github.com/tree-sitter/swift-tree-sitter", from: "0.8.0"),
],
targets: [
.target(
name: "TreeSitterComment",
dependencies: [],
path: ".",
sources: sources,
resources: [
.copy("queries")
],
publicHeadersPath: "bindings/swift",
cSettings: [.headerSearchPath("src")]
),
.testTarget(
name: "TreeSitterCommentTests",
dependencies: [
"SwiftTreeSitter",
"TreeSitterComment",
],
path: "bindings/swift/TreeSitterCommentTests"
)
],
cLanguageStandard: .c11
)
================================================
FILE: README.md
================================================
# tree-sitter-comment
[](https://github.com/stsewd/tree-sitter-comment/actions?query=workflow%3ACI+branch%3Amaster)
[Tree-sitter](https://github.com/tree-sitter/tree-sitter) grammar for comment tags like `TODO:`, `FIXME(user):`, etc.
Useful to be embedded inside comments.
Check the playground at <https://stsewd.dev/tree-sitter-comment/>.
## Syntax
Since comment tags aren't a programming language or have a standard,
I have chosen to follow popular conventions for the syntax.
### Comment tags
* Comment tags can contain:
- Upper case ascii letters
- Numbers (can't start with one)
- `-`, `_` (they can't start or end with these characters)
* Optionally can have an user linked to the tag inside parentheses `()`
* The name must be followed by `:` and a whitespace
### URIs
* http and https links are recognized
If you think there are other popular conventions this syntax doesn't cover,
feel free to open a issue.
## Examples
```
TODO: something needs to be done
TODO(stsewd): something needs to be done by @stsewd
XXX: fix something else.
XXX: extra white spaces.
(NOTE: this works too).
NOTE-BUG (stsewd): tags can be separated by `-`
NOTE_BUG: or by `_`.
This will be recognized as a URI
https://github.com/stsewd/
```
## FAQ
### Can I match a tag that doesn't end in `:`, like `TODO`?
This grammar doesn't provide a specific token for it,
but you can match it with this query:
```scm
("text" @todo
(#eq? @todo "TODO"))
```
### Can I highlight references to issues, PRs, MRs, like `#10` or `!10`?
This grammar doesn't provide a specific token for it,
but you can match it with this query:
```scm
("text" @issue
(#match? @issue "^#[0-9]+$"))
;; NOTE: This matches `!10` and `! 10`.
("text" @symbol . "text" @issue
(#eq? @symbol "!")
(#match? @issue "^[0-9]+$"))
```
### I'm using Neovim and don't see all tags highlighted
To avoid false positives, Neovim doesn't highlight all tags,
but a list of specific ones,
see the list at [`queries/comment/highlights.scm`](https://github.com/nvim-treesitter/nvim-treesitter/blob/master/queries/comment/highlights.scm).
If you want your tag highlighted, you can extend the query locally, see `:h treesitter-query`.
Or if you think it's very common, you can suggest it [upstream](https://github.com/nvim-treesitter/nvim-treesitter).
## Why C?
Tree-sitter is a [LR parser](https://en.wikipedia.org/wiki/LR_parser) for context-free grammars,
that means it works great for grammars that don't require backtracking,
or to keep a state for whitespaces (like indentation).
For these reasons, parsing _languages_ that need to keep a state or falling back to a general token,
it requires some manual parsing in C.
## Projects using this grammar
- [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter)
- [helix](https://github.com/helix-editor/helix)
- [zed-comment](https://github.com/thedadams/zed-comment)
- [zed-todo-tree](https://github.com/alexandretrotel/zed-todo-tree)
- Yours?
## Other grammars
- [tree-sitter-rst](https://github.com/stsewd/tree-sitter-rst): reStructuredText grammar.
================================================
FILE: binding.gyp
================================================
{
"targets": [
{
"target_name": "tree_sitter_comment_binding",
"dependencies": [
"<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
],
"include_dirs": [
"src",
],
"sources": [
"bindings/node/binding.cc",
"src/parser.c",
],
"variables": {
"has_scanner": "<!(node -p \"fs.existsSync('src/scanner.c')\")"
},
"conditions": [
["has_scanner=='true'", {
"sources+": ["src/scanner.c"],
}],
["OS!='win'", {
"cflags_c": [
"-std=c11",
],
}, { # OS == "win"
"cflags_c": [
"/std:c11",
"/utf-8",
],
}],
],
}
]
}
================================================
FILE: bindings/c/tree-sitter-comment.pc.in
================================================
prefix=@CMAKE_INSTALL_PREFIX@
libdir=${prefix}/@CMAKE_INSTALL_LIBDIR@
includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
Name: tree-sitter-comment
Description: @PROJECT_DESCRIPTION@
URL: @PROJECT_HOMEPAGE_URL@
Version: @PROJECT_VERSION@
Libs: -L${libdir} -ltree-sitter-comment
Cflags: -I${includedir}
================================================
FILE: bindings/c/tree_sitter/tree-sitter-comment.h
================================================
#ifndef TREE_SITTER_COMMENT_H_
#define TREE_SITTER_COMMENT_H_
typedef struct TSLanguage TSLanguage;
#ifdef __cplusplus
extern "C" {
#endif
const TSLanguage *tree_sitter_comment(void);
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_COMMENT_H_
================================================
FILE: bindings/go/binding.go
================================================
package tree_sitter_comment
// #cgo CFLAGS: -std=c11 -fPIC
// #include "../../src/parser.c"
// #if __has_include("../../src/scanner.c")
// #include "../../src/scanner.c"
// #endif
import "C"
import "unsafe"
// Get the tree-sitter Language for this grammar.
func Language() unsafe.Pointer {
return unsafe.Pointer(C.tree_sitter_comment())
}
================================================
FILE: bindings/go/binding_test.go
================================================
package tree_sitter_comment_test
import (
"testing"
tree_sitter "github.com/tree-sitter/go-tree-sitter"
tree_sitter_comment "github.com/stsewd/tree-sitter-comment/bindings/go"
)
func TestCanLoadGrammar(t *testing.T) {
language := tree_sitter.NewLanguage(tree_sitter_comment.Language())
if language == nil {
t.Errorf("Error loading Comment grammar")
}
}
================================================
FILE: bindings/node/binding.cc
================================================
#include <napi.h>
typedef struct TSLanguage TSLanguage;
extern "C" TSLanguage *tree_sitter_comment();
// "tree-sitter", "language" hashed with BLAKE2
const napi_type_tag LANGUAGE_TYPE_TAG = {
0x8AF2E5212AD58ABF, 0xD5006CAD83ABBA16
};
Napi::Object Init(Napi::Env env, Napi::Object exports) {
auto language = Napi::External<TSLanguage>::New(env, tree_sitter_comment());
language.TypeTag(&LANGUAGE_TYPE_TAG);
exports["language"] = language;
return exports;
}
NODE_API_MODULE(tree_sitter_comment_binding, Init)
================================================
FILE: bindings/node/binding_test.js
================================================
const assert = require("node:assert");
const { test } = require("node:test");
const Parser = require("tree-sitter");
test("can load grammar", () => {
const parser = new Parser();
assert.doesNotThrow(() => parser.setLanguage(require(".")));
});
================================================
FILE: bindings/node/index.d.ts
================================================
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 = {
language: unknown;
nodeTypeInfo: NodeInfo[];
};
declare const language: Language;
export = language;
================================================
FILE: bindings/node/index.js
================================================
const root = require("path").join(__dirname, "..", "..");
module.exports =
typeof process.versions.bun === "string"
// Support `bun build --compile` by being statically analyzable enough to find the .node file at build-time
? require(`../../prebuilds/${process.platform}-${process.arch}/tree-sitter-comment.node`)
: require("node-gyp-build")(root);
try {
module.exports.nodeTypeInfo = require("../../src/node-types.json");
} catch (_) {}
================================================
FILE: bindings/python/tests/test_binding.py
================================================
from unittest import TestCase
import tree_sitter
import tree_sitter_comment
class TestLanguage(TestCase):
def test_can_load_grammar(self):
try:
tree_sitter.Language(tree_sitter_comment.language())
except Exception:
self.fail("Error loading Comment grammar")
================================================
FILE: bindings/python/tree_sitter_comment/__init__.py
================================================
"""Grammar for code tags like TODO:, FIXME(user): for the tree-sitter parsing library"""
from importlib.resources import files as _files
from ._binding import language
def _get_query(name, file):
query = _files(f"{__package__}.queries") / file
globals()[name] = query.read_text()
return globals()[name]
def __getattr__(name):
# NOTE: uncomment these to include any queries that this grammar contains:
# if name == "HIGHLIGHTS_QUERY":
# return _get_query("HIGHLIGHTS_QUERY", "highlights.scm")
# if name == "INJECTIONS_QUERY":
# return _get_query("INJECTIONS_QUERY", "injections.scm")
# if name == "LOCALS_QUERY":
# return _get_query("LOCALS_QUERY", "locals.scm")
# if name == "TAGS_QUERY":
# return _get_query("TAGS_QUERY", "tags.scm")
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
__all__ = [
"language",
# "HIGHLIGHTS_QUERY",
# "INJECTIONS_QUERY",
# "LOCALS_QUERY",
# "TAGS_QUERY",
]
def __dir__():
return sorted(__all__ + [
"__all__", "__builtins__", "__cached__", "__doc__", "__file__",
"__loader__", "__name__", "__package__", "__path__", "__spec__",
])
================================================
FILE: bindings/python/tree_sitter_comment/__init__.pyi
================================================
from typing import Final
# NOTE: uncomment these to include any queries that this grammar contains:
# HIGHLIGHTS_QUERY: Final[str]
# INJECTIONS_QUERY: Final[str]
# LOCALS_QUERY: Final[str]
# TAGS_QUERY: Final[str]
def language() -> object: ...
================================================
FILE: bindings/python/tree_sitter_comment/binding.c
================================================
#include <Python.h>
typedef struct TSLanguage TSLanguage;
TSLanguage *tree_sitter_comment(void);
static PyObject* _binding_language(PyObject *Py_UNUSED(self), PyObject *Py_UNUSED(args)) {
return PyCapsule_New(tree_sitter_comment(), "tree_sitter.Language", NULL);
}
static struct PyModuleDef_Slot slots[] = {
#ifdef Py_GIL_DISABLED
{Py_mod_gil, Py_MOD_GIL_NOT_USED},
#endif
{0, NULL}
};
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 = 0,
.m_methods = methods,
.m_slots = slots,
};
PyMODINIT_FUNC PyInit__binding(void) {
return PyModuleDef_Init(&module);
}
================================================
FILE: bindings/python/tree_sitter_comment/py.typed
================================================
================================================
FILE: bindings/rust/build.rs
================================================
fn main() {
let src_dir = std::path::Path::new("src");
let mut c_config = cc::Build::new();
c_config.std("c11").include(src_dir);
#[cfg(target_env = "msvc")]
c_config.flag("-utf-8");
let parser_path = src_dir.join("parser.c");
c_config.file(&parser_path);
println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap());
let scanner_path = src_dir.join("scanner.c");
if scanner_path.exists() {
c_config.file(&scanner_path);
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
}
c_config.compile("tree-sitter-comment");
}
================================================
FILE: bindings/rust/lib.rs
================================================
//! This crate provides Comment language support for the [tree-sitter][] parsing library.
//!
//! Typically, you will use the [LANGUAGE][] constant to add this language to a
//! tree-sitter [Parser][], and then use the parser to parse some code:
//!
//! ```
//! let code = r#"
//! "#;
//! let mut parser = tree_sitter::Parser::new();
//! let language = tree_sitter_comment::LANGUAGE;
//! parser
//! .set_language(&language.into())
//! .expect("Error loading Comment parser");
//! let tree = parser.parse(code, None).unwrap();
//! assert!(!tree.root_node().has_error());
//! ```
//!
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/
use tree_sitter_language::LanguageFn;
extern "C" {
fn tree_sitter_comment() -> *const ();
}
/// The tree-sitter [`LanguageFn`][LanguageFn] for this grammar.
///
/// [LanguageFn]: https://docs.rs/tree-sitter-language/*/tree_sitter_language/struct.LanguageFn.html
pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitter_comment) };
/// The content of the [`node-types.json`][] file for this grammar.
///
/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types
pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");
// NOTE: 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: &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.into())
.expect("Error loading Comment parser");
}
}
================================================
FILE: bindings/swift/TreeSitterComment/comment.h
================================================
#ifndef TREE_SITTER_COMMENT_H_
#define TREE_SITTER_COMMENT_H_
typedef struct TSLanguage TSLanguage;
#ifdef __cplusplus
extern "C" {
#endif
const TSLanguage *tree_sitter_comment(void);
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_COMMENT_H_
================================================
FILE: bindings/swift/TreeSitterCommentTests/TreeSitterCommentTests.swift
================================================
import XCTest
import SwiftTreeSitter
import TreeSitterComment
final class TreeSitterCommentTests: XCTestCase {
func testCanLoadGrammar() throws {
let parser = Parser()
let language = Language(language: tree_sitter_comment())
XCTAssertNoThrow(try parser.setLanguage(language),
"Error loading Comment grammar")
}
}
================================================
FILE: compile_flags.txt
================================================
-Isrc/
-std=c99
================================================
FILE: docs/.nojekyll
================================================
================================================
FILE: docs/index.html
================================================
<!-- Extracted from the `tree-sitter playground` command. -->
<head>
<meta charset="utf-8">
<title>Tree-sitter grammar for code tags like TODO:, FIXME(user): - tree-sitter-comment</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.19.0/clusterize.min.css">
<link rel="icon" type="image/png" href="https://tree-sitter.github.io/tree-sitter/assets/images/favicon-32x32.png"
sizes="32x32" />
<link rel="icon" type="image/png" href="https://tree-sitter.github.io/tree-sitter/assets/images/favicon-16x16.png"
sizes="16x16" />
</head>
<body>
<div id="playground-container" style="visibility: hidden;">
<header>
<div class="header-item">
<span class="language-name">
<a href="https://github.com/stsewd/tree-sitter-comment" target="_blank">
tree-sitter-comment
</a>
</span>
</div>
<div class="header-item">
<input id="logging-checkbox" type="checkbox">
<label for="logging-checkbox">log</label>
</div>
<div class="header-item">
<input id="anonymous-nodes-checkbox" type="checkbox">
<label for="anonymous-nodes-checkbox">show anonymous nodes</label>
</div>
<div class="header-item">
<input id="query-checkbox" type="checkbox">
<label for="query-checkbox">query</label>
</div>
<div class="header-item">
<input id="accessibility-checkbox" type="checkbox">
<label for="accessibility-checkbox">accessibility</label>
</div>
<div class="header-item">
<label for="update-time">parse time: </label>
<span id="update-time"></span>
</div>
<div class="header-item">
<a href="https://tree-sitter.github.io/tree-sitter/7-playground.html#about">(?)</a>
</div>
<select id="language-select" style="display: none;">
<option value="parser">Parser</option>
</select>
<div class="header-item">
<button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
<svg class="sun-icon" viewBox="0 0 24 24" width="16" height="16">
<path fill="currentColor"
d="M12 17.5a5.5 5.5 0 1 0 0-11 5.5 5.5 0 0 0 0 11zm0 1.5a7 7 0 1 1 0-14 7 7 0 0 1 0 14zm0-16a1 1 0 0 1 1 1v2a1 1 0 1 1-2 0V4a1 1 0 0 1 1-1zm0 15a1 1 0 0 1 1 1v2a1 1 0 1 1-2 0v-2a1 1 0 0 1 1-1zm9-9a1 1 0 0 1-1 1h-2a1 1 0 1 1 0-2h2a1 1 0 0 1 1 1zM4 12a1 1 0 0 1-1 1H1a1 1 0 1 1 0-2h2a1 1 0 0 1 1 1z" />
</svg>
<svg class="moon-icon" viewBox="0 0 24 24" width="16" height="16">
<path fill="currentColor"
d="M12.1 22c-5.5 0-10-4.5-10-10s4.5-10 10-10c.2 0 .3 0 .5.1-1.3 1.4-2 3.2-2 5.2 0 4.1 3.4 7.5 7.5 7.5 2 0 3.8-.7 5.2-2 .1.2.1.3.1.5 0 5.4-4.5 9.7-10 9.7z" />
</svg>
</button>
</div>
</header>
<main>
<div id="input-pane">
<div class="panel-header">Code</div>
<div id="code-container">
<textarea id="code-input"></textarea>
</div>
<div id="query-container" style="visibility: hidden; position: absolute;">
<div class="panel-header">Query</div>
<textarea id="query-input"></textarea>
</div>
</div>
<div id="output-container-scroll">
<div class="panel-header">Tree</div>
<pre id="output-container" class="highlight"></pre>
</div>
</main>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/6.65.7/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.19.0/clusterize.min.js"></script>
<script>LANGUAGE_BASE_URL = "js";</script>
<script type="module" src="js/playground.js"></script>
<script type="module">
import * as TreeSitter from './js/tree-sitter.js';
window.TreeSitter = TreeSitter;
setTimeout(() => window.initializePlayground({local: true}), 1)
</script>
<script>
(codeExample => {
const handle = setInterval(() => {
const $codeEditor = document.querySelector('.CodeMirror');
if ($codeEditor) {
$codeEditor.CodeMirror.setValue(codeExample);
clearInterval(handle);
}
}, 500);
})(`TODO: something needs to be done
TODO(stsewd): something needs to be done by @stsewd
XXX: fix something else.
XXX: extra white spaces.
(NOTE: this works too).
NOTE-BUG (stsewd): tags can be separated by \`-\`
NOTE_BUG: or by \`_\`.
NOTE: check https://github.com/stsewd/tree-sitter-comment`);
</script>
<style>
/* Base Variables */
:root {
--light-bg: #f9f9f9;
--light-border: #e0e0e0;
--light-text: #333;
--light-hover-border: #c1c1c1;
--light-scrollbar-track: #f1f1f1;
--light-scrollbar-thumb: #c1c1c1;
--light-scrollbar-thumb-hover: #a8a8a8;
--dark-bg: #1d1f21;
--dark-border: #2d2d2d;
--dark-text: #c5c8c6;
--dark-panel-bg: #252526;
--dark-code-bg: #1e1e1e;
--dark-scrollbar-track: #25282c;
--dark-scrollbar-thumb: #4a4d51;
--dark-scrollbar-thumb-hover: #5a5d61;
--primary-color: #0550ae;
--primary-color-alpha: rgba(5, 80, 174, 0.1);
--primary-color-alpha-dark: rgba(121, 192, 255, 0.1);
--selection-color: rgba(39, 95, 255, 0.3);
}
/* Theme Colors */
[data-theme="dark"] {
--bg-color: var(--dark-bg);
--border-color: var(--dark-border);
--text-color: var(--dark-text);
--panel-bg: var(--dark-panel-bg);
--code-bg: var(--dark-code-bg);
}
[data-theme="light"] {
--bg-color: var(--light-bg);
--border-color: var(--light-border);
--text-color: var(--light-text);
--panel-bg: white;
--code-bg: white;
}
/* Base Styles */
body {
margin: 0;
padding: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
}
/* Layout */
#playground-container {
width: 100%;
height: 100vh;
display: flex;
flex-direction: column;
background-color: var(--bg-color);
}
header {
padding: 16px 24px;
border-bottom: 1px solid var(--border-color);
display: flex;
align-items: center;
gap: 20px;
background-color: var(--panel-bg);
font-size: 14px;
}
.header-item {
display: flex;
align-items: center;
gap: 8px;
}
.language-name {
font-weight: 600;
}
main {
flex: 1;
display: flex;
overflow: hidden;
}
#input-pane {
width: 50%;
display: flex;
flex-direction: column;
border-right: 1px solid var(--border-color);
background-color: var(--panel-bg);
overflow: hidden;
}
#code-container {
flex: 1;
min-height: 0;
position: relative;
border-bottom: 1px solid var(--border-color);
display: flex;
flex-direction: column;
}
#query-container:not([style*="visibility: hidden"]) {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
#query-container .panel-header {
flex: 0 0 auto;
}
#query-container .CodeMirror {
flex: 1;
position: relative;
min-height: 0;
}
#output-container-scroll {
width: 50%;
overflow: auto;
background-color: var(--panel-bg);
padding: 0;
display: flex;
flex-direction: column;
}
#output-container {
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
line-height: 1.5;
margin: 0;
padding: 16px;
}
.panel-header {
padding: 8px 16px;
font-weight: 600;
font-size: 14px;
border-bottom: 1px solid var(--border-color);
background-color: var(--panel-bg);
}
.CodeMirror {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
height: 100%;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
font-size: 14px;
line-height: 1.6;
background-color: var(--code-bg) !important;
color: var(--text-color) !important;
}
.query-error {
text-decoration: underline red dashed;
-webkit-text-decoration: underline red dashed;
}
/* Scrollbars */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
border-radius: 4px;
background: var(--light-scrollbar-track);
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background: var(--light-scrollbar-thumb);
}
::-webkit-scrollbar-thumb:hover {
background: var(--light-scrollbar-thumb-hover);
}
[data-theme="dark"] {
::-webkit-scrollbar-track {
background: var(--dark-scrollbar-track) !important;
}
::-webkit-scrollbar-thumb {
background: var(--dark-scrollbar-thumb) !important;
}
::-webkit-scrollbar-thumb:hover {
background: var(--dark-scrollbar-thumb-hover) !important;
}
}
/* Theme Toggle */
.theme-toggle {
background: none;
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 6px;
cursor: pointer;
color: var(--text-color);
}
.theme-toggle:hover {
background-color: var(--primary-color-alpha);
}
[data-theme="light"] .moon-icon,
[data-theme="dark"] .sun-icon {
display: none;
}
/* Form Elements */
input[type="checkbox"] {
margin-right: 6px;
vertical-align: middle;
}
label {
font-size: 14px;
margin-right: 16px;
cursor: pointer;
}
#output-container a {
cursor: pointer;
text-decoration: none;
color: #040404;
padding: 2px;
}
#output-container a:hover {
text-decoration: underline;
}
#output-container a.node-link.named {
color: #0550ae;
}
#output-container a.node-link.anonymous {
color: #116329;
}
#output-container a.node-link.anonymous:before {
content: '"';
}
#output-container a.node-link.anonymous:after {
content: '"';
}
#output-container a.node-link.error {
color: #cf222e;
}
#output-container a.highlighted {
background-color: #d9d9d9;
color: red;
border-radius: 3px;
text-decoration: underline;
}
/* Dark Theme Node Colors */
[data-theme="dark"] {
& #output-container a {
color: #d4d4d4;
}
& #output-container a.node-link.named {
color: #79c0ff;
}
& #output-container a.node-link.anonymous {
color: #7ee787;
}
& #output-container a.node-link.error {
color: #ff7b72;
}
& #output-container a.highlighted {
background-color: #373b41;
color: red;
}
& .CodeMirror {
background-color: var(--dark-code-bg) !important;
color: var(--dark-text) !important;
}
& .CodeMirror-gutters {
background-color: var(--dark-panel-bg) !important;
border-color: var(--dark-border) !important;
}
& .CodeMirror-cursor {
border-color: var(--dark-text) !important;
}
& .CodeMirror-selected {
background-color: rgba(255, 255, 255, 0.1) !important;
}
}
</style>
</body>
================================================
FILE: docs/js/playground.js
================================================
function initializeLocalTheme() {
const themeToggle = document.getElementById('theme-toggle');
if (!themeToggle) return;
// Load saved theme or use system preference
const savedTheme = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const initialTheme = savedTheme || (prefersDark ? 'dark' : 'light');
// Set initial theme
document.documentElement.setAttribute('data-theme', initialTheme);
themeToggle.addEventListener('click', () => {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
});
}
function initializeCustomSelect({ initialValue = null, addListeners = false }) {
const button = document.getElementById('language-button');
const select = document.getElementById('language-select');
if (!button || !select) return;
const dropdown = button.nextElementSibling;
const selectedValue = button.querySelector('.selected-value');
if (initialValue) {
select.value = initialValue;
}
if (select.selectedIndex >= 0 && select.options[select.selectedIndex]) {
selectedValue.textContent = select.options[select.selectedIndex].text;
} else {
selectedValue.textContent = 'JavaScript';
}
if (addListeners) {
button.addEventListener('click', (e) => {
e.preventDefault(); // Prevent form submission
dropdown.classList.toggle('show');
});
document.addEventListener('click', (e) => {
if (!button.contains(e.target)) {
dropdown.classList.remove('show');
}
});
dropdown.querySelectorAll('.option').forEach(option => {
option.addEventListener('click', () => {
selectedValue.textContent = option.textContent;
select.value = option.dataset.value;
dropdown.classList.remove('show');
const event = new Event('change');
select.dispatchEvent(event);
});
});
}
}
window.initializePlayground = async (opts) => {
const { Parser, Language } = window.TreeSitter;
const { local } = opts;
if (local) {
initializeLocalTheme();
}
initializeCustomSelect({ addListeners: true });
let tree;
const CAPTURE_REGEX = /@\s*([\w\._-]+)/g;
const LIGHT_COLORS = [
"#0550ae", // blue
"#ab5000", // rust brown
"#116329", // forest green
"#844708", // warm brown
"#6639ba", // purple
"#7d4e00", // orange brown
"#0969da", // bright blue
"#1a7f37", // green
"#cf222e", // red
"#8250df", // violet
"#6e7781", // gray
"#953800", // dark orange
"#1b7c83" // teal
];
const DARK_COLORS = [
"#79c0ff", // light blue
"#ffa657", // orange
"#7ee787", // light green
"#ff7b72", // salmon
"#d2a8ff", // light purple
"#ffa198", // pink
"#a5d6ff", // pale blue
"#56d364", // bright green
"#ff9492", // light red
"#e0b8ff", // pale purple
"#9ca3af", // gray
"#ffb757", // yellow orange
"#80cbc4" // light teal
];
const codeInput = document.getElementById("code-input");
const languageSelect = document.getElementById("language-select");
const loggingCheckbox = document.getElementById("logging-checkbox");
const anonymousNodes = document.getElementById('anonymous-nodes-checkbox');
const outputContainer = document.getElementById("output-container");
const outputContainerScroll = document.getElementById(
"output-container-scroll",
);
const playgroundContainer = document.getElementById("playground-container");
const queryCheckbox = document.getElementById("query-checkbox");
const queryContainer = document.getElementById("query-container");
const queryInput = document.getElementById("query-input");
const accessibilityCheckbox = document.getElementById("accessibility-checkbox");
const updateTimeSpan = document.getElementById("update-time");
const languagesByName = {};
loadState();
await Parser.init();
const parser = new Parser();
console.log(parser, codeInput, queryInput);
const codeEditor = CodeMirror.fromTextArea(codeInput, {
lineNumbers: true,
showCursorWhenSelecting: true
});
codeEditor.on('keydown', (_, event) => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
event.stopPropagation(); // Prevent mdBook from going back/forward
}
});
const queryEditor = CodeMirror.fromTextArea(queryInput, {
lineNumbers: true,
showCursorWhenSelecting: true,
});
queryEditor.on('keydown', (_, event) => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
event.stopPropagation(); // Prevent mdBook from going back/forward
}
});
const cluster = new Clusterize({
rows: [],
noDataText: null,
contentElem: outputContainer,
scrollElem: outputContainerScroll,
});
const renderTreeOnCodeChange = debounce(renderTree, 50);
const saveStateOnChange = debounce(saveState, 2000);
const runTreeQueryOnChange = debounce(runTreeQuery, 50);
let languageName = languageSelect.value;
let treeRows = null;
let treeRowHighlightedIndex = -1;
let parseCount = 0;
let isRendering = 0;
let query;
codeEditor.on("changes", handleCodeChange);
codeEditor.on("viewportChange", runTreeQueryOnChange);
codeEditor.on("cursorActivity", debounce(handleCursorMovement, 150));
queryEditor.on("changes", debounce(handleQueryChange, 150));
loggingCheckbox.addEventListener("change", handleLoggingChange);
anonymousNodes.addEventListener('change', renderTree);
queryCheckbox.addEventListener("change", handleQueryEnableChange);
accessibilityCheckbox.addEventListener("change", handleQueryChange);
languageSelect.addEventListener("change", handleLanguageChange);
outputContainer.addEventListener("click", handleTreeClick);
handleQueryEnableChange();
await handleLanguageChange();
playgroundContainer.style.visibility = "visible";
async function handleLanguageChange() {
const newLanguageName = languageSelect.value;
if (!languagesByName[newLanguageName]) {
const url = `${LANGUAGE_BASE_URL}/tree-sitter-${newLanguageName}.wasm`;
languageSelect.disabled = true;
try {
languagesByName[newLanguageName] = await Language.load(url);
} catch (e) {
console.error(e);
languageSelect.value = languageName;
return;
} finally {
languageSelect.disabled = false;
}
}
tree = null;
languageName = newLanguageName;
parser.setLanguage(languagesByName[newLanguageName]);
handleCodeChange();
handleQueryChange();
}
async function handleCodeChange(editor, changes) {
const newText = codeEditor.getValue() + "\n";
const edits = tree && changes && changes.map(treeEditForEditorChange);
const start = performance.now();
if (edits) {
for (const edit of edits) {
tree.edit(edit);
}
}
const newTree = parser.parse(newText, tree);
const duration = (performance.now() - start).toFixed(1);
updateTimeSpan.innerText = `${duration} ms`;
if (tree) tree.delete();
tree = newTree;
parseCount++;
renderTreeOnCodeChange();
runTreeQueryOnChange();
saveStateOnChange();
}
async function renderTree() {
isRendering++;
const cursor = tree.walk();
let currentRenderCount = parseCount;
let row = "";
let rows = [];
let finishedRow = false;
let visitedChildren = false;
let indentLevel = 0;
for (let i = 0; ; i++) {
if (i > 0 && i % 10000 === 0) {
await new Promise((r) => setTimeout(r, 0));
if (parseCount !== currentRenderCount) {
cursor.delete();
isRendering--;
return;
}
}
let displayName;
if (cursor.nodeIsMissing) {
const nodeTypeText = cursor.nodeIsNamed ? cursor.nodeType : `"${cursor.nodeType}"`;
displayName = `MISSING ${nodeTypeText}`;
} else if (cursor.nodeIsNamed) {
displayName = cursor.nodeType;
} else if (anonymousNodes.checked) {
displayName = cursor.nodeType
}
if (visitedChildren) {
if (displayName) {
finishedRow = true;
}
if (cursor.gotoNextSibling()) {
visitedChildren = false;
} else if (cursor.gotoParent()) {
visitedChildren = true;
indentLevel--;
} else {
break;
}
} else {
if (displayName) {
if (finishedRow) {
row += "</div>";
rows.push(row);
finishedRow = false;
}
const start = cursor.startPosition;
const end = cursor.endPosition;
const id = cursor.nodeId;
let fieldName = cursor.currentFieldName;
if (fieldName) {
fieldName += ": ";
} else {
fieldName = "";
}
const nodeClass =
displayName === 'ERROR' || displayName.startsWith('MISSING')
? 'node-link error'
: cursor.nodeIsNamed
? 'node-link named'
: 'node-link anonymous';
row = `<div class="tree-row">${" ".repeat(indentLevel)}${fieldName}` +
`<a class='${nodeClass}' href="#" data-id=${id} ` +
`data-range="${start.row},${start.column},${end.row},${end.column}">` +
`${displayName}</a> <span class="position-info">` +
`[${start.row}, ${start.column}] - [${end.row}, ${end.column}]</span>`;
finishedRow = true;
}
if (cursor.gotoFirstChild()) {
visitedChildren = false;
indentLevel++;
} else {
visitedChildren = true;
}
}
}
if (finishedRow) {
row += "</div>";
rows.push(row);
}
cursor.delete();
cluster.update(rows);
treeRows = rows;
isRendering--;
handleCursorMovement();
}
function getCaptureCSS(name) {
if (accessibilityCheckbox.checked) {
return `color: white; background-color: ${colorForCaptureName(name)}`;
} else {
return `color: ${colorForCaptureName(name)}`;
}
}
function runTreeQuery(_, startRow, endRow) {
if (endRow == null) {
const viewport = codeEditor.getViewport();
startRow = viewport.from;
endRow = viewport.to;
}
codeEditor.operation(() => {
const marks = codeEditor.getAllMarks();
marks.forEach((m) => m.clear());
if (tree && query) {
const captures = query.captures(
tree.rootNode,
{ row: startRow, column: 0 },
{ row: endRow, column: 0 },
);
let lastNodeId;
for (const { name, node } of captures) {
if (node.id === lastNodeId) continue;
lastNodeId = node.id;
const { startPosition, endPosition } = node;
codeEditor.markText(
{ line: startPosition.row, ch: startPosition.column },
{ line: endPosition.row, ch: endPosition.column },
{
inclusiveLeft: true,
inclusiveRight: true,
css: getCaptureCSS(name),
},
);
}
}
});
}
// When we change from a dark theme to a light theme (and vice versa), the colors of the
// captures need to be updated.
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.attributeName === 'class') {
handleQueryChange();
}
});
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class']
});
function handleQueryChange() {
if (query) {
query.delete();
query.deleted = true;
query = null;
}
queryEditor.operation(() => {
queryEditor.getAllMarks().forEach((m) => m.clear());
if (!queryCheckbox.checked) return;
const queryText = queryEditor.getValue();
try {
query = parser.language.query(queryText);
let match;
let row = 0;
queryEditor.eachLine((line) => {
while ((match = CAPTURE_REGEX.exec(line.text))) {
queryEditor.markText(
{ line: row, ch: match.index },
{ line: row, ch: match.index + match[0].length },
{
inclusiveLeft: true,
inclusiveRight: true,
css: `color: ${colorForCaptureName(match[1])}`,
},
);
}
row++;
});
} catch (error) {
const startPosition = queryEditor.posFromIndex(error.index);
const endPosition = {
line: startPosition.line,
ch: startPosition.ch + (error.length || Infinity),
};
if (error.index === queryText.length) {
if (startPosition.ch > 0) {
startPosition.ch--;
} else if (startPosition.row > 0) {
startPosition.row--;
startPosition.column = Infinity;
}
}
queryEditor.markText(startPosition, endPosition, {
className: "query-error",
inclusiveLeft: true,
inclusiveRight: true,
attributes: { title: error.message },
});
}
});
runTreeQuery();
saveQueryState();
}
function handleCursorMovement() {
if (isRendering) return;
const selection = codeEditor.getDoc().listSelections()[0];
let start = { row: selection.anchor.line, column: selection.anchor.ch };
let end = { row: selection.head.line, column: selection.head.ch };
if (
start.row > end.row ||
(start.row === end.row && start.column > end.column)
) {
let swap = end;
end = start;
start = swap;
}
const node = tree.rootNode.namedDescendantForPosition(start, end);
if (treeRows) {
if (treeRowHighlightedIndex !== -1) {
const row = treeRows[treeRowHighlightedIndex];
if (row)
treeRows[treeRowHighlightedIndex] = row.replace(
"highlighted",
"plain",
);
}
treeRowHighlightedIndex = treeRows.findIndex((row) =>
row.includes(`data-id=${node.id}`),
);
if (treeRowHighlightedIndex !== -1) {
const row = treeRows[treeRowHighlightedIndex];
if (row)
treeRows[treeRowHighlightedIndex] = row.replace(
"plain",
"highlighted",
);
}
cluster.update(treeRows);
const lineHeight = cluster.options.item_height;
const scrollTop = outputContainerScroll.scrollTop;
const containerHeight = outputContainerScroll.clientHeight;
const offset = treeRowHighlightedIndex * lineHeight;
if (scrollTop > offset - 20) {
$(outputContainerScroll).animate({ scrollTop: offset - 20 }, 150);
} else if (scrollTop < offset + lineHeight + 40 - containerHeight) {
$(outputContainerScroll).animate(
{ scrollTop: offset - containerHeight + 40 },
150,
);
}
}
}
function handleTreeClick(event) {
if (event.target.tagName === "A") {
event.preventDefault();
const [startRow, startColumn, endRow, endColumn] =
event.target.dataset.range.split(",").map((n) => parseInt(n));
codeEditor.focus();
codeEditor.setSelection(
{ line: startRow, ch: startColumn },
{ line: endRow, ch: endColumn },
);
}
}
function handleLoggingChange() {
if (loggingCheckbox.checked) {
parser.setLogger((message, lexing) => {
if (lexing) {
console.log(" ", message);
} else {
console.log(message);
}
});
} else {
parser.setLogger(null);
}
}
function handleQueryEnableChange() {
if (queryCheckbox.checked) {
queryContainer.style.visibility = "";
queryContainer.style.position = "";
} else {
queryContainer.style.visibility = "hidden";
queryContainer.style.position = "absolute";
}
handleQueryChange();
}
function treeEditForEditorChange(change) {
const oldLineCount = change.removed.length;
const newLineCount = change.text.length;
const lastLineLength = change.text[newLineCount - 1].length;
const startPosition = { row: change.from.line, column: change.from.ch };
const oldEndPosition = { row: change.to.line, column: change.to.ch };
const newEndPosition = {
row: startPosition.row + newLineCount - 1,
column:
newLineCount === 1
? startPosition.column + lastLineLength
: lastLineLength,
};
const startIndex = codeEditor.indexFromPos(change.from);
let newEndIndex = startIndex + newLineCount - 1;
let oldEndIndex = startIndex + oldLineCount - 1;
for (let i = 0; i < newLineCount; i++) newEndIndex += change.text[i].length;
for (let i = 0; i < oldLineCount; i++)
oldEndIndex += change.removed[i].length;
return {
startIndex,
oldEndIndex,
newEndIndex,
startPosition,
oldEndPosition,
newEndPosition,
};
}
function colorForCaptureName(capture) {
const id = query.captureNames.indexOf(capture);
const isDark = document.querySelector('html').classList.contains('ayu') ||
document.querySelector('html').classList.contains('coal') ||
document.querySelector('html').classList.contains('navy');
const colors = isDark ? DARK_COLORS : LIGHT_COLORS;
return colors[id % colors.length];
}
function loadState() {
const language = localStorage.getItem("language");
const sourceCode = localStorage.getItem("sourceCode");
const anonNodes = localStorage.getItem("anonymousNodes");
const query = localStorage.getItem("query");
const queryEnabled = localStorage.getItem("queryEnabled");
if (language != null && sourceCode != null && query != null) {
queryInput.value = query;
codeInput.value = sourceCode;
languageSelect.value = language;
initializeCustomSelect({ initialValue: language });
anonymousNodes.checked = anonNodes === "true";
queryCheckbox.checked = queryEnabled === "true";
}
}
function saveState() {
localStorage.setItem("language", languageSelect.value);
localStorage.setItem("sourceCode", codeEditor.getValue());
localStorage.setItem("anonymousNodes", anonymousNodes.checked);
saveQueryState();
}
function saveQueryState() {
localStorage.setItem("queryEnabled", queryCheckbox.checked);
localStorage.setItem("query", queryEditor.getValue());
}
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this,
args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
};
================================================
FILE: docs/js/tree-sitter.js
================================================
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
// src/constants.ts
var SIZE_OF_SHORT = 2;
var SIZE_OF_INT = 4;
var SIZE_OF_CURSOR = 4 * SIZE_OF_INT;
var SIZE_OF_NODE = 5 * SIZE_OF_INT;
var SIZE_OF_POINT = 2 * SIZE_OF_INT;
var SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT;
var ZERO_POINT = { row: 0, column: 0 };
var INTERNAL = Symbol("INTERNAL");
function assertInternal(x) {
if (x !== INTERNAL) throw new Error("Illegal constructor");
}
__name(assertInternal, "assertInternal");
function isPoint(point) {
return !!point && typeof point.row === "number" && typeof point.column === "number";
}
__name(isPoint, "isPoint");
function setModule(module2) {
C = module2;
}
__name(setModule, "setModule");
var C;
// src/lookahead_iterator.ts
var LookaheadIterator = class {
static {
__name(this, "LookaheadIterator");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/** @internal */
language;
/** @internal */
constructor(internal, address, language) {
assertInternal(internal);
this[0] = address;
this.language = language;
}
/** Get the current symbol of the lookahead iterator. */
get currentTypeId() {
return C._ts_lookahead_iterator_current_symbol(this[0]);
}
/** Get the current symbol name of the lookahead iterator. */
get currentType() {
return this.language.types[this.currentTypeId] || "ERROR";
}
/** Delete the lookahead iterator, freeing its resources. */
delete() {
C._ts_lookahead_iterator_delete(this[0]);
this[0] = 0;
}
/**
* Reset the lookahead iterator.
*
* This returns `true` if the language was set successfully and `false`
* otherwise.
*/
reset(language, stateId) {
if (C._ts_lookahead_iterator_reset(this[0], language[0], stateId)) {
this.language = language;
return true;
}
return false;
}
/**
* Reset the lookahead iterator to another state.
*
* This returns `true` if the iterator was reset to the given state and
* `false` otherwise.
*/
resetState(stateId) {
return Boolean(C._ts_lookahead_iterator_reset_state(this[0], stateId));
}
/**
* Returns an iterator that iterates over the symbols of the lookahead iterator.
*
* The iterator will yield the current symbol name as a string for each step
* until there are no more symbols to iterate over.
*/
[Symbol.iterator]() {
return {
next: /* @__PURE__ */ __name(() => {
if (C._ts_lookahead_iterator_next(this[0])) {
return { done: false, value: this.currentType };
}
return { done: true, value: "" };
}, "next")
};
}
};
// src/tree.ts
function getText(tree, startIndex, endIndex, startPosition) {
const length = endIndex - startIndex;
let result = tree.textCallback(startIndex, startPosition);
if (result) {
startIndex += result.length;
while (startIndex < endIndex) {
const string = tree.textCallback(startIndex, startPosition);
if (string && string.length > 0) {
startIndex += string.length;
result += string;
} else {
break;
}
}
if (startIndex > endIndex) {
result = result.slice(0, length);
}
}
return result ?? "";
}
__name(getText, "getText");
var Tree = class _Tree {
static {
__name(this, "Tree");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/** @internal */
textCallback;
/** The language that was used to parse the syntax tree. */
language;
/** @internal */
constructor(internal, address, language, textCallback) {
assertInternal(internal);
this[0] = address;
this.language = language;
this.textCallback = textCallback;
}
/** Create a shallow copy of the syntax tree. This is very fast. */
copy() {
const address = C._ts_tree_copy(this[0]);
return new _Tree(INTERNAL, address, this.language, this.textCallback);
}
/** Delete the syntax tree, freeing its resources. */
delete() {
C._ts_tree_delete(this[0]);
this[0] = 0;
}
/** Get the root node of the syntax tree. */
get rootNode() {
C._ts_tree_root_node_wasm(this[0]);
return unmarshalNode(this);
}
/**
* Get the root node of the syntax tree, but with its position shifted
* forward by the given offset.
*/
rootNodeWithOffset(offsetBytes, offsetExtent) {
const address = TRANSFER_BUFFER + SIZE_OF_NODE;
C.setValue(address, offsetBytes, "i32");
marshalPoint(address + SIZE_OF_INT, offsetExtent);
C._ts_tree_root_node_with_offset_wasm(this[0]);
return unmarshalNode(this);
}
/**
* Edit the syntax tree to keep it in sync with source code that has been
* edited.
*
* You must describe the edit both in terms of byte offsets and in terms of
* row/column coordinates.
*/
edit(edit) {
marshalEdit(edit);
C._ts_tree_edit_wasm(this[0]);
}
/** Create a new {@link TreeCursor} starting from the root of the tree. */
walk() {
return this.rootNode.walk();
}
/**
* Compare this old edited syntax tree to a new syntax tree representing
* the same document, returning a sequence of ranges whose syntactic
* structure has changed.
*
* For this to work correctly, this syntax tree must have been edited such
* that its ranges match up to the new tree. Generally, you'll want to
* call this method right after calling one of the [`Parser::parse`]
* functions. Call it on the old tree that was passed to parse, and
* pass the new tree that was returned from `parse`.
*/
getChangedRanges(other) {
if (!(other instanceof _Tree)) {
throw new TypeError("Argument must be a Tree");
}
C._ts_tree_get_changed_ranges_wasm(this[0], other[0]);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
result[i2] = unmarshalRange(address);
address += SIZE_OF_RANGE;
}
C._free(buffer);
}
return result;
}
/** Get the included ranges that were used to parse the syntax tree. */
getIncludedRanges() {
C._ts_tree_included_ranges_wasm(this[0]);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
result[i2] = unmarshalRange(address);
address += SIZE_OF_RANGE;
}
C._free(buffer);
}
return result;
}
};
// src/tree_cursor.ts
var TreeCursor = class _TreeCursor {
static {
__name(this, "TreeCursor");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/** @internal */
[1] = 0;
// Internal handle for WASM
/** @internal */
[2] = 0;
// Internal handle for WASM
/** @internal */
[3] = 0;
// Internal handle for WASM
/** @internal */
tree;
/** @internal */
constructor(internal, tree) {
assertInternal(internal);
this.tree = tree;
unmarshalTreeCursor(this);
}
/** Creates a deep copy of the tree cursor. This allocates new memory. */
copy() {
const copy = new _TreeCursor(INTERNAL, this.tree);
C._ts_tree_cursor_copy_wasm(this.tree[0]);
unmarshalTreeCursor(copy);
return copy;
}
/** Delete the tree cursor, freeing its resources. */
delete() {
marshalTreeCursor(this);
C._ts_tree_cursor_delete_wasm(this.tree[0]);
this[0] = this[1] = this[2] = 0;
}
/** Get the tree cursor's current {@link Node}. */
get currentNode() {
marshalTreeCursor(this);
C._ts_tree_cursor_current_node_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/**
* Get the numerical field id of this tree cursor's current node.
*
* See also {@link TreeCursor#currentFieldName}.
*/
get currentFieldId() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
}
/** Get the field name of this tree cursor's current node. */
get currentFieldName() {
return this.tree.language.fields[this.currentFieldId];
}
/**
* Get the depth of the cursor's current node relative to the original
* node that the cursor was constructed with.
*/
get currentDepth() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_depth_wasm(this.tree[0]);
}
/**
* Get the index of the cursor's current node out of all of the
* descendants of the original node that the cursor was constructed with.
*/
get currentDescendantIndex() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0]);
}
/** Get the type of the cursor's current node. */
get nodeType() {
return this.tree.language.types[this.nodeTypeId] || "ERROR";
}
/** Get the type id of the cursor's current node. */
get nodeTypeId() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
}
/** Get the state id of the cursor's current node. */
get nodeStateId() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0]);
}
/** Get the id of the cursor's current node. */
get nodeId() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
}
/**
* Check if the cursor's current node is *named*.
*
* Named nodes correspond to named rules in the grammar, whereas
* *anonymous* nodes correspond to string literals in the grammar.
*/
get nodeIsNamed() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]) === 1;
}
/**
* Check if the cursor's current node is *missing*.
*
* Missing nodes are inserted by the parser in order to recover from
* certain kinds of syntax errors.
*/
get nodeIsMissing() {
marshalTreeCursor(this);
return C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]) === 1;
}
/** Get the string content of the cursor's current node. */
get nodeText() {
marshalTreeCursor(this);
const startIndex = C._ts_tree_cursor_start_index_wasm(this.tree[0]);
const endIndex = C._ts_tree_cursor_end_index_wasm(this.tree[0]);
C._ts_tree_cursor_start_position_wasm(this.tree[0]);
const startPosition = unmarshalPoint(TRANSFER_BUFFER);
return getText(this.tree, startIndex, endIndex, startPosition);
}
/** Get the start position of the cursor's current node. */
get startPosition() {
marshalTreeCursor(this);
C._ts_tree_cursor_start_position_wasm(this.tree[0]);
return unmarshalPoint(TRANSFER_BUFFER);
}
/** Get the end position of the cursor's current node. */
get endPosition() {
marshalTreeCursor(this);
C._ts_tree_cursor_end_position_wasm(this.tree[0]);
return unmarshalPoint(TRANSFER_BUFFER);
}
/** Get the start index of the cursor's current node. */
get startIndex() {
marshalTreeCursor(this);
return C._ts_tree_cursor_start_index_wasm(this.tree[0]);
}
/** Get the end index of the cursor's current node. */
get endIndex() {
marshalTreeCursor(this);
return C._ts_tree_cursor_end_index_wasm(this.tree[0]);
}
/**
* Move this cursor to the first child of its current node.
*
* This returns `true` if the cursor successfully moved, and returns
* `false` if there were no children.
*/
gotoFirstChild() {
marshalTreeCursor(this);
const result = C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
unmarshalTreeCursor(this);
return result === 1;
}
/**
* Move this cursor to the last child of its current node.
*
* This returns `true` if the cursor successfully moved, and returns
* `false` if there were no children.
*
* Note that this function may be slower than
* {@link TreeCursor#gotoFirstChild} because it needs to
* iterate through all the children to compute the child's position.
*/
gotoLastChild() {
marshalTreeCursor(this);
const result = C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);
unmarshalTreeCursor(this);
return result === 1;
}
/**
* Move this cursor to the parent of its current node.
*
* This returns `true` if the cursor successfully moved, and returns
* `false` if there was no parent node (the cursor was already on the
* root node).
*
* Note that the node the cursor was constructed with is considered the root
* of the cursor, and the cursor cannot walk outside this node.
*/
gotoParent() {
marshalTreeCursor(this);
const result = C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
unmarshalTreeCursor(this);
return result === 1;
}
/**
* Move this cursor to the next sibling of its current node.
*
* This returns `true` if the cursor successfully moved, and returns
* `false` if there was no next sibling node.
*
* Note that the node the cursor was constructed with is considered the root
* of the cursor, and the cursor cannot walk outside this node.
*/
gotoNextSibling() {
marshalTreeCursor(this);
const result = C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
unmarshalTreeCursor(this);
return result === 1;
}
/**
* Move this cursor to the previous sibling of its current node.
*
* This returns `true` if the cursor successfully moved, and returns
* `false` if there was no previous sibling node.
*
* Note that this function may be slower than
* {@link TreeCursor#gotoNextSibling} due to how node
* positions are stored. In the worst case, this will need to iterate
* through all the children up to the previous sibling node to recalculate
* its position. Also note that the node the cursor was constructed with is
* considered the root of the cursor, and the cursor cannot walk outside this node.
*/
gotoPreviousSibling() {
marshalTreeCursor(this);
const result = C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);
unmarshalTreeCursor(this);
return result === 1;
}
/**
* Move the cursor to the node that is the nth descendant of
* the original node that the cursor was constructed with, where
* zero represents the original node itself.
*/
gotoDescendant(goalDescendantIndex) {
marshalTreeCursor(this);
C._ts_tree_cursor_goto_descendant_wasm(this.tree[0], goalDescendantIndex);
unmarshalTreeCursor(this);
}
/**
* Move this cursor to the first child of its current node that contains or
* starts after the given byte offset.
*
* This returns `true` if the cursor successfully moved to a child node, and returns
* `false` if no such child was found.
*/
gotoFirstChildForIndex(goalIndex) {
marshalTreeCursor(this);
C.setValue(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalIndex, "i32");
const result = C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);
unmarshalTreeCursor(this);
return result === 1;
}
/**
* Move this cursor to the first child of its current node that contains or
* starts after the given byte offset.
*
* This returns the index of the child node if one was found, and returns
* `null` if no such child was found.
*/
gotoFirstChildForPosition(goalPosition) {
marshalTreeCursor(this);
marshalPoint(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalPosition);
const result = C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);
unmarshalTreeCursor(this);
return result === 1;
}
/**
* Re-initialize this tree cursor to start at the original node that the
* cursor was constructed with.
*/
reset(node) {
marshalNode(node);
marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
C._ts_tree_cursor_reset_wasm(this.tree[0]);
unmarshalTreeCursor(this);
}
/**
* Re-initialize a tree cursor to the same position as another cursor.
*
* Unlike {@link TreeCursor#reset}, this will not lose parent
* information and allows reusing already created cursors.
*/
resetTo(cursor) {
marshalTreeCursor(this, TRANSFER_BUFFER);
marshalTreeCursor(cursor, TRANSFER_BUFFER + SIZE_OF_CURSOR);
C._ts_tree_cursor_reset_to_wasm(this.tree[0], cursor.tree[0]);
unmarshalTreeCursor(this);
}
};
// src/node.ts
var Node = class {
static {
__name(this, "Node");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/** @internal */
_children;
/** @internal */
_namedChildren;
/** @internal */
constructor(internal, {
id,
tree,
startIndex,
startPosition,
other
}) {
assertInternal(internal);
this[0] = other;
this.id = id;
this.tree = tree;
this.startIndex = startIndex;
this.startPosition = startPosition;
}
/**
* The numeric id for this node that is unique.
*
* Within a given syntax tree, no two nodes have the same id. However:
*
* * If a new tree is created based on an older tree, and a node from the old tree is reused in
* the process, then that node will have the same id in both trees.
*
* * A node not marked as having changes does not guarantee it was reused.
*
* * If a node is marked as having changed in the old tree, it will not be reused.
*/
id;
/** The byte index where this node starts. */
startIndex;
/** The position where this node starts. */
startPosition;
/** The tree that this node belongs to. */
tree;
/** Get this node's type as a numerical id. */
get typeId() {
marshalNode(this);
return C._ts_node_symbol_wasm(this.tree[0]);
}
/**
* Get the node's type as a numerical id as it appears in the grammar,
* ignoring aliases.
*/
get grammarId() {
marshalNode(this);
return C._ts_node_grammar_symbol_wasm(this.tree[0]);
}
/** Get this node's type as a string. */
get type() {
return this.tree.language.types[this.typeId] || "ERROR";
}
/**
* Get this node's symbol name as it appears in the grammar, ignoring
* aliases as a string.
*/
get grammarType() {
return this.tree.language.types[this.grammarId] || "ERROR";
}
/**
* Check if this node is *named*.
*
* Named nodes correspond to named rules in the grammar, whereas
* *anonymous* nodes correspond to string literals in the grammar.
*/
get isNamed() {
marshalNode(this);
return C._ts_node_is_named_wasm(this.tree[0]) === 1;
}
/**
* Check if this node is *extra*.
*
* Extra nodes represent things like comments, which are not required
* by the grammar, but can appear anywhere.
*/
get isExtra() {
marshalNode(this);
return C._ts_node_is_extra_wasm(this.tree[0]) === 1;
}
/**
* Check if this node represents a syntax error.
*
* Syntax errors represent parts of the code that could not be incorporated
* into a valid syntax tree.
*/
get isError() {
marshalNode(this);
return C._ts_node_is_error_wasm(this.tree[0]) === 1;
}
/**
* Check if this node is *missing*.
*
* Missing nodes are inserted by the parser in order to recover from
* certain kinds of syntax errors.
*/
get isMissing() {
marshalNode(this);
return C._ts_node_is_missing_wasm(this.tree[0]) === 1;
}
/** Check if this node has been edited. */
get hasChanges() {
marshalNode(this);
return C._ts_node_has_changes_wasm(this.tree[0]) === 1;
}
/**
* Check if this node represents a syntax error or contains any syntax
* errors anywhere within it.
*/
get hasError() {
marshalNode(this);
return C._ts_node_has_error_wasm(this.tree[0]) === 1;
}
/** Get the byte index where this node ends. */
get endIndex() {
marshalNode(this);
return C._ts_node_end_index_wasm(this.tree[0]);
}
/** Get the position where this node ends. */
get endPosition() {
marshalNode(this);
C._ts_node_end_point_wasm(this.tree[0]);
return unmarshalPoint(TRANSFER_BUFFER);
}
/** Get the string content of this node. */
get text() {
return getText(this.tree, this.startIndex, this.endIndex, this.startPosition);
}
/** Get this node's parse state. */
get parseState() {
marshalNode(this);
return C._ts_node_parse_state_wasm(this.tree[0]);
}
/** Get the parse state after this node. */
get nextParseState() {
marshalNode(this);
return C._ts_node_next_parse_state_wasm(this.tree[0]);
}
/** Check if this node is equal to another node. */
equals(other) {
return this.tree === other.tree && this.id === other.id;
}
/**
* Get the node's child at the given index, where zero represents the first child.
*
* This method is fairly fast, but its cost is technically log(n), so if
* you might be iterating over a long list of children, you should use
* {@link Node#children} instead.
*/
child(index) {
marshalNode(this);
C._ts_node_child_wasm(this.tree[0], index);
return unmarshalNode(this.tree);
}
/**
* Get this node's *named* child at the given index.
*
* See also {@link Node#isNamed}.
* This method is fairly fast, but its cost is technically log(n), so if
* you might be iterating over a long list of children, you should use
* {@link Node#namedChildren} instead.
*/
namedChild(index) {
marshalNode(this);
C._ts_node_named_child_wasm(this.tree[0], index);
return unmarshalNode(this.tree);
}
/**
* Get this node's child with the given numerical field id.
*
* See also {@link Node#childForFieldName}. You can
* convert a field name to an id using {@link Language#fieldIdForName}.
*/
childForFieldId(fieldId) {
marshalNode(this);
C._ts_node_child_by_field_id_wasm(this.tree[0], fieldId);
return unmarshalNode(this.tree);
}
/**
* Get the first child with the given field name.
*
* If multiple children may have the same field name, access them using
* {@link Node#childrenForFieldName}.
*/
childForFieldName(fieldName) {
const fieldId = this.tree.language.fields.indexOf(fieldName);
if (fieldId !== -1) return this.childForFieldId(fieldId);
return null;
}
/** Get the field name of this node's child at the given index. */
fieldNameForChild(index) {
marshalNode(this);
const address = C._ts_node_field_name_for_child_wasm(this.tree[0], index);
if (!address) return null;
return C.AsciiToString(address);
}
/** Get the field name of this node's named child at the given index. */
fieldNameForNamedChild(index) {
marshalNode(this);
const address = C._ts_node_field_name_for_named_child_wasm(this.tree[0], index);
if (!address) return null;
return C.AsciiToString(address);
}
/**
* Get an array of this node's children with a given field name.
*
* See also {@link Node#children}.
*/
childrenForFieldName(fieldName) {
const fieldId = this.tree.language.fields.indexOf(fieldName);
if (fieldId !== -1 && fieldId !== 0) return this.childrenForFieldId(fieldId);
return [];
}
/**
* Get an array of this node's children with a given field id.
*
* See also {@link Node#childrenForFieldName}.
*/
childrenForFieldId(fieldId) {
marshalNode(this);
C._ts_node_children_by_field_id_wasm(this.tree[0], fieldId);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
result[i2] = unmarshalNode(this.tree, address);
address += SIZE_OF_NODE;
}
C._free(buffer);
}
return result;
}
/** Get the node's first child that contains or starts after the given byte offset. */
firstChildForIndex(index) {
marshalNode(this);
const address = TRANSFER_BUFFER + SIZE_OF_NODE;
C.setValue(address, index, "i32");
C._ts_node_first_child_for_byte_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get the node's first named child that contains or starts after the given byte offset. */
firstNamedChildForIndex(index) {
marshalNode(this);
const address = TRANSFER_BUFFER + SIZE_OF_NODE;
C.setValue(address, index, "i32");
C._ts_node_first_named_child_for_byte_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get this node's number of children. */
get childCount() {
marshalNode(this);
return C._ts_node_child_count_wasm(this.tree[0]);
}
/**
* Get this node's number of *named* children.
*
* See also {@link Node#isNamed}.
*/
get namedChildCount() {
marshalNode(this);
return C._ts_node_named_child_count_wasm(this.tree[0]);
}
/** Get this node's first child. */
get firstChild() {
return this.child(0);
}
/**
* Get this node's first named child.
*
* See also {@link Node#isNamed}.
*/
get firstNamedChild() {
return this.namedChild(0);
}
/** Get this node's last child. */
get lastChild() {
return this.child(this.childCount - 1);
}
/**
* Get this node's last named child.
*
* See also {@link Node#isNamed}.
*/
get lastNamedChild() {
return this.namedChild(this.namedChildCount - 1);
}
/**
* Iterate over this node's children.
*
* If you're walking the tree recursively, you may want to use the
* {@link TreeCursor} APIs directly instead.
*/
get children() {
if (!this._children) {
marshalNode(this);
C._ts_node_children_wasm(this.tree[0]);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
this._children = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
this._children[i2] = unmarshalNode(this.tree, address);
address += SIZE_OF_NODE;
}
C._free(buffer);
}
}
return this._children;
}
/**
* Iterate over this node's named children.
*
* See also {@link Node#children}.
*/
get namedChildren() {
if (!this._namedChildren) {
marshalNode(this);
C._ts_node_named_children_wasm(this.tree[0]);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
this._namedChildren = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
this._namedChildren[i2] = unmarshalNode(this.tree, address);
address += SIZE_OF_NODE;
}
C._free(buffer);
}
}
return this._namedChildren;
}
/**
* Get the descendants of this node that are the given type, or in the given types array.
*
* The types array should contain node type strings, which can be retrieved from {@link Language#types}.
*
* Additionally, a `startPosition` and `endPosition` can be passed in to restrict the search to a byte range.
*/
descendantsOfType(types, startPosition = ZERO_POINT, endPosition = ZERO_POINT) {
if (!Array.isArray(types)) types = [types];
const symbols = [];
const typesBySymbol = this.tree.language.types;
for (const node_type of types) {
if (node_type == "ERROR") {
symbols.push(65535);
}
}
for (let i2 = 0, n = typesBySymbol.length; i2 < n; i2++) {
if (types.includes(typesBySymbol[i2])) {
symbols.push(i2);
}
}
const symbolsAddress = C._malloc(SIZE_OF_INT * symbols.length);
for (let i2 = 0, n = symbols.length; i2 < n; i2++) {
C.setValue(symbolsAddress + i2 * SIZE_OF_INT, symbols[i2], "i32");
}
marshalNode(this);
C._ts_node_descendants_of_type_wasm(
this.tree[0],
symbolsAddress,
symbols.length,
startPosition.row,
startPosition.column,
endPosition.row,
endPosition.column
);
const descendantCount = C.getValue(TRANSFER_BUFFER, "i32");
const descendantAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(descendantCount);
if (descendantCount > 0) {
let address = descendantAddress;
for (let i2 = 0; i2 < descendantCount; i2++) {
result[i2] = unmarshalNode(this.tree, address);
address += SIZE_OF_NODE;
}
}
C._free(descendantAddress);
C._free(symbolsAddress);
return result;
}
/** Get this node's next sibling. */
get nextSibling() {
marshalNode(this);
C._ts_node_next_sibling_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get this node's previous sibling. */
get previousSibling() {
marshalNode(this);
C._ts_node_prev_sibling_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/**
* Get this node's next *named* sibling.
*
* See also {@link Node#isNamed}.
*/
get nextNamedSibling() {
marshalNode(this);
C._ts_node_next_named_sibling_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/**
* Get this node's previous *named* sibling.
*
* See also {@link Node#isNamed}.
*/
get previousNamedSibling() {
marshalNode(this);
C._ts_node_prev_named_sibling_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get the node's number of descendants, including one for the node itself. */
get descendantCount() {
marshalNode(this);
return C._ts_node_descendant_count_wasm(this.tree[0]);
}
/**
* Get this node's immediate parent.
* Prefer {@link Node#childWithDescendant} for iterating over this node's ancestors.
*/
get parent() {
marshalNode(this);
C._ts_node_parent_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/**
* Get the node that contains `descendant`.
*
* Note that this can return `descendant` itself.
*/
childWithDescendant(descendant) {
marshalNode(this);
marshalNode(descendant);
C._ts_node_child_with_descendant_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get the smallest node within this node that spans the given byte range. */
descendantForIndex(start2, end = start2) {
if (typeof start2 !== "number" || typeof end !== "number") {
throw new Error("Arguments must be numbers");
}
marshalNode(this);
const address = TRANSFER_BUFFER + SIZE_OF_NODE;
C.setValue(address, start2, "i32");
C.setValue(address + SIZE_OF_INT, end, "i32");
C._ts_node_descendant_for_index_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get the smallest named node within this node that spans the given byte range. */
namedDescendantForIndex(start2, end = start2) {
if (typeof start2 !== "number" || typeof end !== "number") {
throw new Error("Arguments must be numbers");
}
marshalNode(this);
const address = TRANSFER_BUFFER + SIZE_OF_NODE;
C.setValue(address, start2, "i32");
C.setValue(address + SIZE_OF_INT, end, "i32");
C._ts_node_named_descendant_for_index_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get the smallest node within this node that spans the given point range. */
descendantForPosition(start2, end = start2) {
if (!isPoint(start2) || !isPoint(end)) {
throw new Error("Arguments must be {row, column} objects");
}
marshalNode(this);
const address = TRANSFER_BUFFER + SIZE_OF_NODE;
marshalPoint(address, start2);
marshalPoint(address + SIZE_OF_POINT, end);
C._ts_node_descendant_for_position_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/** Get the smallest named node within this node that spans the given point range. */
namedDescendantForPosition(start2, end = start2) {
if (!isPoint(start2) || !isPoint(end)) {
throw new Error("Arguments must be {row, column} objects");
}
marshalNode(this);
const address = TRANSFER_BUFFER + SIZE_OF_NODE;
marshalPoint(address, start2);
marshalPoint(address + SIZE_OF_POINT, end);
C._ts_node_named_descendant_for_position_wasm(this.tree[0]);
return unmarshalNode(this.tree);
}
/**
* Create a new {@link TreeCursor} starting from this node.
*
* Note that the given node is considered the root of the cursor,
* and the cursor cannot walk outside this node.
*/
walk() {
marshalNode(this);
C._ts_tree_cursor_new_wasm(this.tree[0]);
return new TreeCursor(INTERNAL, this.tree);
}
/**
* Edit this node to keep it in-sync with source code that has been edited.
*
* This function is only rarely needed. When you edit a syntax tree with
* the {@link Tree#edit} method, all of the nodes that you retrieve from
* the tree afterward will already reflect the edit. You only need to
* use {@link Node#edit} when you have a specific {@link Node} instance that
* you want to keep and continue to use after an edit.
*/
edit(edit) {
if (this.startIndex >= edit.oldEndIndex) {
this.startIndex = edit.newEndIndex + (this.startIndex - edit.oldEndIndex);
let subbedPointRow;
let subbedPointColumn;
if (this.startPosition.row > edit.oldEndPosition.row) {
subbedPointRow = this.startPosition.row - edit.oldEndPosition.row;
subbedPointColumn = this.startPosition.column;
} else {
subbedPointRow = 0;
subbedPointColumn = this.startPosition.column;
if (this.startPosition.column >= edit.oldEndPosition.column) {
subbedPointColumn = this.startPosition.column - edit.oldEndPosition.column;
}
}
if (subbedPointRow > 0) {
this.startPosition.row += subbedPointRow;
this.startPosition.column = subbedPointColumn;
} else {
this.startPosition.column += subbedPointColumn;
}
} else if (this.startIndex > edit.startIndex) {
this.startIndex = edit.newEndIndex;
this.startPosition.row = edit.newEndPosition.row;
this.startPosition.column = edit.newEndPosition.column;
}
}
/** Get the S-expression representation of this node. */
toString() {
marshalNode(this);
const address = C._ts_node_to_string_wasm(this.tree[0]);
const result = C.AsciiToString(address);
C._free(address);
return result;
}
};
// src/marshal.ts
function unmarshalCaptures(query, tree, address, patternIndex, result) {
for (let i2 = 0, n = result.length; i2 < n; i2++) {
const captureIndex = C.getValue(address, "i32");
address += SIZE_OF_INT;
const node = unmarshalNode(tree, address);
address += SIZE_OF_NODE;
result[i2] = { patternIndex, name: query.captureNames[captureIndex], node };
}
return address;
}
__name(unmarshalCaptures, "unmarshalCaptures");
function marshalNode(node) {
let address = TRANSFER_BUFFER;
C.setValue(address, node.id, "i32");
address += SIZE_OF_INT;
C.setValue(address, node.startIndex, "i32");
address += SIZE_OF_INT;
C.setValue(address, node.startPosition.row, "i32");
address += SIZE_OF_INT;
C.setValue(address, node.startPosition.column, "i32");
address += SIZE_OF_INT;
C.setValue(address, node[0], "i32");
}
__name(marshalNode, "marshalNode");
function unmarshalNode(tree, address = TRANSFER_BUFFER) {
const id = C.getValue(address, "i32");
address += SIZE_OF_INT;
if (id === 0) return null;
const index = C.getValue(address, "i32");
address += SIZE_OF_INT;
const row = C.getValue(address, "i32");
address += SIZE_OF_INT;
const column = C.getValue(address, "i32");
address += SIZE_OF_INT;
const other = C.getValue(address, "i32");
const result = new Node(INTERNAL, {
id,
tree,
startIndex: index,
startPosition: { row, column },
other
});
return result;
}
__name(unmarshalNode, "unmarshalNode");
function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
C.setValue(address + 0 * SIZE_OF_INT, cursor[0], "i32");
C.setValue(address + 1 * SIZE_OF_INT, cursor[1], "i32");
C.setValue(address + 2 * SIZE_OF_INT, cursor[2], "i32");
C.setValue(address + 3 * SIZE_OF_INT, cursor[3], "i32");
}
__name(marshalTreeCursor, "marshalTreeCursor");
function unmarshalTreeCursor(cursor) {
cursor[0] = C.getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32");
cursor[1] = C.getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32");
cursor[2] = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
cursor[3] = C.getValue(TRANSFER_BUFFER + 3 * SIZE_OF_INT, "i32");
}
__name(unmarshalTreeCursor, "unmarshalTreeCursor");
function marshalPoint(address, point) {
C.setValue(address, point.row, "i32");
C.setValue(address + SIZE_OF_INT, point.column, "i32");
}
__name(marshalPoint, "marshalPoint");
function unmarshalPoint(address) {
const result = {
row: C.getValue(address, "i32") >>> 0,
column: C.getValue(address + SIZE_OF_INT, "i32") >>> 0
};
return result;
}
__name(unmarshalPoint, "unmarshalPoint");
function marshalRange(address, range) {
marshalPoint(address, range.startPosition);
address += SIZE_OF_POINT;
marshalPoint(address, range.endPosition);
address += SIZE_OF_POINT;
C.setValue(address, range.startIndex, "i32");
address += SIZE_OF_INT;
C.setValue(address, range.endIndex, "i32");
address += SIZE_OF_INT;
}
__name(marshalRange, "marshalRange");
function unmarshalRange(address) {
const result = {};
result.startPosition = unmarshalPoint(address);
address += SIZE_OF_POINT;
result.endPosition = unmarshalPoint(address);
address += SIZE_OF_POINT;
result.startIndex = C.getValue(address, "i32") >>> 0;
address += SIZE_OF_INT;
result.endIndex = C.getValue(address, "i32") >>> 0;
return result;
}
__name(unmarshalRange, "unmarshalRange");
function marshalEdit(edit, address = TRANSFER_BUFFER) {
marshalPoint(address, edit.startPosition);
address += SIZE_OF_POINT;
marshalPoint(address, edit.oldEndPosition);
address += SIZE_OF_POINT;
marshalPoint(address, edit.newEndPosition);
address += SIZE_OF_POINT;
C.setValue(address, edit.startIndex, "i32");
address += SIZE_OF_INT;
C.setValue(address, edit.oldEndIndex, "i32");
address += SIZE_OF_INT;
C.setValue(address, edit.newEndIndex, "i32");
address += SIZE_OF_INT;
}
__name(marshalEdit, "marshalEdit");
function unmarshalLanguageMetadata(address) {
const result = {};
result.major_version = C.getValue(address, "i32");
address += SIZE_OF_INT;
result.minor_version = C.getValue(address, "i32");
address += SIZE_OF_INT;
result.field_count = C.getValue(address, "i32");
return result;
}
__name(unmarshalLanguageMetadata, "unmarshalLanguageMetadata");
// src/query.ts
var PREDICATE_STEP_TYPE_CAPTURE = 1;
var PREDICATE_STEP_TYPE_STRING = 2;
var QUERY_WORD_REGEX = /[\w-]+/g;
var CaptureQuantifier = {
Zero: 0,
ZeroOrOne: 1,
ZeroOrMore: 2,
One: 3,
OneOrMore: 4
};
var isCaptureStep = /* @__PURE__ */ __name((step) => step.type === "capture", "isCaptureStep");
var isStringStep = /* @__PURE__ */ __name((step) => step.type === "string", "isStringStep");
var QueryErrorKind = {
Syntax: 1,
NodeName: 2,
FieldName: 3,
CaptureName: 4,
PatternStructure: 5
};
var QueryError = class _QueryError extends Error {
constructor(kind, info2, index, length) {
super(_QueryError.formatMessage(kind, info2));
this.kind = kind;
this.info = info2;
this.index = index;
this.length = length;
this.name = "QueryError";
}
static {
__name(this, "QueryError");
}
/** Formats an error message based on the error kind and info */
static formatMessage(kind, info2) {
switch (kind) {
case QueryErrorKind.NodeName:
return `Bad node name '${info2.word}'`;
case QueryErrorKind.FieldName:
return `Bad field name '${info2.word}'`;
case QueryErrorKind.CaptureName:
return `Bad capture name @${info2.word}`;
case QueryErrorKind.PatternStructure:
return `Bad pattern structure at offset ${info2.suffix}`;
case QueryErrorKind.Syntax:
return `Bad syntax at offset ${info2.suffix}`;
}
}
};
function parseAnyPredicate(steps, index, operator, textPredicates) {
if (steps.length !== 3) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}`
);
}
if (!isCaptureStep(steps[1])) {
throw new Error(
`First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}"`
);
}
const isPositive = operator === "eq?" || operator === "any-eq?";
const matchAll = !operator.startsWith("any-");
if (isCaptureStep(steps[2])) {
const captureName1 = steps[1].name;
const captureName2 = steps[2].name;
textPredicates[index].push((captures) => {
const nodes1 = [];
const nodes2 = [];
for (const c of captures) {
if (c.name === captureName1) nodes1.push(c.node);
if (c.name === captureName2) nodes2.push(c.node);
}
const compare = /* @__PURE__ */ __name((n1, n2, positive) => {
return positive ? n1.text === n2.text : n1.text !== n2.text;
}, "compare");
return matchAll ? nodes1.every((n1) => nodes2.some((n2) => compare(n1, n2, isPositive))) : nodes1.some((n1) => nodes2.some((n2) => compare(n1, n2, isPositive)));
});
} else {
const captureName = steps[1].name;
const stringValue = steps[2].value;
const matches = /* @__PURE__ */ __name((n) => n.text === stringValue, "matches");
const doesNotMatch = /* @__PURE__ */ __name((n) => n.text !== stringValue, "doesNotMatch");
textPredicates[index].push((captures) => {
const nodes = [];
for (const c of captures) {
if (c.name === captureName) nodes.push(c.node);
}
const test = isPositive ? matches : doesNotMatch;
return matchAll ? nodes.every(test) : nodes.some(test);
});
}
}
__name(parseAnyPredicate, "parseAnyPredicate");
function parseMatchPredicate(steps, index, operator, textPredicates) {
if (steps.length !== 3) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}.`
);
}
if (steps[1].type !== "capture") {
throw new Error(
`First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
);
}
if (steps[2].type !== "string") {
throw new Error(
`Second argument of \`#${operator}\` predicate must be a string. Got @${steps[2].name}.`
);
}
const isPositive = operator === "match?" || operator === "any-match?";
const matchAll = !operator.startsWith("any-");
const captureName = steps[1].name;
const regex = new RegExp(steps[2].value);
textPredicates[index].push((captures) => {
const nodes = [];
for (const c of captures) {
if (c.name === captureName) nodes.push(c.node.text);
}
const test = /* @__PURE__ */ __name((text, positive) => {
return positive ? regex.test(text) : !regex.test(text);
}, "test");
if (nodes.length === 0) return !isPositive;
return matchAll ? nodes.every((text) => test(text, isPositive)) : nodes.some((text) => test(text, isPositive));
});
}
__name(parseMatchPredicate, "parseMatchPredicate");
function parseAnyOfPredicate(steps, index, operator, textPredicates) {
if (steps.length < 2) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected at least 1. Got ${steps.length - 1}.`
);
}
if (steps[1].type !== "capture") {
throw new Error(
`First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
);
}
const isPositive = operator === "any-of?";
const captureName = steps[1].name;
const stringSteps = steps.slice(2);
if (!stringSteps.every(isStringStep)) {
throw new Error(
`Arguments to \`#${operator}\` predicate must be strings.".`
);
}
const values = stringSteps.map((s) => s.value);
textPredicates[index].push((captures) => {
const nodes = [];
for (const c of captures) {
if (c.name === captureName) nodes.push(c.node.text);
}
if (nodes.length === 0) return !isPositive;
return nodes.every((text) => values.includes(text)) === isPositive;
});
}
__name(parseAnyOfPredicate, "parseAnyOfPredicate");
function parseIsPredicate(steps, index, operator, assertedProperties, refutedProperties) {
if (steps.length < 2 || steps.length > 3) {
throw new Error(
`Wrong number of arguments to \`#${operator}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
);
}
if (!steps.every(isStringStep)) {
throw new Error(
`Arguments to \`#${operator}\` predicate must be strings.".`
);
}
const properties = operator === "is?" ? assertedProperties : refutedProperties;
if (!properties[index]) properties[index] = {};
properties[index][steps[1].value] = steps[2]?.value ?? null;
}
__name(parseIsPredicate, "parseIsPredicate");
function parseSetDirective(steps, index, setProperties) {
if (steps.length < 2 || steps.length > 3) {
throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
}
if (!steps.every(isStringStep)) {
throw new Error(`Arguments to \`#set!\` predicate must be strings.".`);
}
if (!setProperties[index]) setProperties[index] = {};
setProperties[index][steps[1].value] = steps[2]?.value ?? null;
}
__name(parseSetDirective, "parseSetDirective");
function parsePattern(index, stepType, stepValueId, captureNames, stringValues, steps, textPredicates, predicates, setProperties, assertedProperties, refutedProperties) {
if (stepType === PREDICATE_STEP_TYPE_CAPTURE) {
const name2 = captureNames[stepValueId];
steps.push({ type: "capture", name: name2 });
} else if (stepType === PREDICATE_STEP_TYPE_STRING) {
steps.push({ type: "string", value: stringValues[stepValueId] });
} else if (steps.length > 0) {
if (steps[0].type !== "string") {
throw new Error("Predicates must begin with a literal value");
}
const operator = steps[0].value;
switch (operator) {
case "any-not-eq?":
case "not-eq?":
case "any-eq?":
case "eq?":
parseAnyPredicate(steps, index, operator, textPredicates);
break;
case "any-not-match?":
case "not-match?":
case "any-match?":
case "match?":
parseMatchPredicate(steps, index, operator, textPredicates);
break;
case "not-any-of?":
case "any-of?":
parseAnyOfPredicate(steps, index, operator, textPredicates);
break;
case "is?":
case "is-not?":
parseIsPredicate(steps, index, operator, assertedProperties, refutedProperties);
break;
case "set!":
parseSetDirective(steps, index, setProperties);
break;
default:
predicates[index].push({ operator, operands: steps.slice(1) });
}
steps.length = 0;
}
}
__name(parsePattern, "parsePattern");
var Query = class {
static {
__name(this, "Query");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/** @internal */
exceededMatchLimit;
/** @internal */
textPredicates;
/** The names of the captures used in the query. */
captureNames;
/** The quantifiers of the captures used in the query. */
captureQuantifiers;
/**
* The other user-defined predicates associated with the given index.
*
* This includes predicates with operators other than:
* - `match?`
* - `eq?` and `not-eq?`
* - `any-of?` and `not-any-of?`
* - `is?` and `is-not?`
* - `set!`
*/
predicates;
/** The properties for predicates with the operator `set!`. */
setProperties;
/** The properties for predicates with the operator `is?`. */
assertedProperties;
/** The properties for predicates with the operator `is-not?`. */
refutedProperties;
/** The maximum number of in-progress matches for this cursor. */
matchLimit;
/**
* Create a new query from a string containing one or more S-expression
* patterns.
*
* The query is associated with a particular language, and can only be run
* on syntax nodes parsed with that language. References to Queries can be
* shared between multiple threads.
*
* @link {@see https://tree-sitter.github.io/tree-sitter/using-parsers/queries}
*/
constructor(language, source) {
const sourceLength = C.lengthBytesUTF8(source);
const sourceAddress = C._malloc(sourceLength + 1);
C.stringToUTF8(source, sourceAddress, sourceLength + 1);
const address = C._ts_query_new(
language[0],
sourceAddress,
sourceLength,
TRANSFER_BUFFER,
TRANSFER_BUFFER + SIZE_OF_INT
);
if (!address) {
const errorId = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const errorByte = C.getValue(TRANSFER_BUFFER, "i32");
const errorIndex = C.UTF8ToString(sourceAddress, errorByte).length;
const suffix = source.slice(errorIndex, errorIndex + 100).split("\n")[0];
const word = suffix.match(QUERY_WORD_REGEX)?.[0] ?? "";
C._free(sourceAddress);
switch (errorId) {
case QueryErrorKind.Syntax:
throw new QueryError(QueryErrorKind.Syntax, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
case QueryErrorKind.NodeName:
throw new QueryError(errorId, { word }, errorIndex, word.length);
case QueryErrorKind.FieldName:
throw new QueryError(errorId, { word }, errorIndex, word.length);
case QueryErrorKind.CaptureName:
throw new QueryError(errorId, { word }, errorIndex, word.length);
case QueryErrorKind.PatternStructure:
throw new QueryError(errorId, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
}
}
const stringCount = C._ts_query_string_count(address);
const captureCount = C._ts_query_capture_count(address);
const patternCount = C._ts_query_pattern_count(address);
const captureNames = new Array(captureCount);
const captureQuantifiers = new Array(patternCount);
const stringValues = new Array(stringCount);
for (let i2 = 0; i2 < captureCount; i2++) {
const nameAddress = C._ts_query_capture_name_for_id(
address,
i2,
TRANSFER_BUFFER
);
const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
captureNames[i2] = C.UTF8ToString(nameAddress, nameLength);
}
for (let i2 = 0; i2 < patternCount; i2++) {
const captureQuantifiersArray = new Array(captureCount);
for (let j = 0; j < captureCount; j++) {
const quantifier = C._ts_query_capture_quantifier_for_id(address, i2, j);
captureQuantifiersArray[j] = quantifier;
}
captureQuantifiers[i2] = captureQuantifiersArray;
}
for (let i2 = 0; i2 < stringCount; i2++) {
const valueAddress = C._ts_query_string_value_for_id(
address,
i2,
TRANSFER_BUFFER
);
const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
stringValues[i2] = C.UTF8ToString(valueAddress, nameLength);
}
const setProperties = new Array(patternCount);
const assertedProperties = new Array(patternCount);
const refutedProperties = new Array(patternCount);
const predicates = new Array(patternCount);
const textPredicates = new Array(patternCount);
for (let i2 = 0; i2 < patternCount; i2++) {
const predicatesAddress = C._ts_query_predicates_for_pattern(address, i2, TRANSFER_BUFFER);
const stepCount = C.getValue(TRANSFER_BUFFER, "i32");
predicates[i2] = [];
textPredicates[i2] = [];
const steps = new Array();
let stepAddress = predicatesAddress;
for (let j = 0; j < stepCount; j++) {
const stepType = C.getValue(stepAddress, "i32");
stepAddress += SIZE_OF_INT;
const stepValueId = C.getValue(stepAddress, "i32");
stepAddress += SIZE_OF_INT;
parsePattern(
i2,
stepType,
stepValueId,
captureNames,
stringValues,
steps,
textPredicates,
predicates,
setProperties,
assertedProperties,
refutedProperties
);
}
Object.freeze(textPredicates[i2]);
Object.freeze(predicates[i2]);
Object.freeze(setProperties[i2]);
Object.freeze(assertedProperties[i2]);
Object.freeze(refutedProperties[i2]);
}
C._free(sourceAddress);
this[0] = address;
this.captureNames = captureNames;
this.captureQuantifiers = captureQuantifiers;
this.textPredicates = textPredicates;
this.predicates = predicates;
this.setProperties = setProperties;
this.assertedProperties = assertedProperties;
this.refutedProperties = refutedProperties;
this.exceededMatchLimit = false;
}
/** Delete the query, freeing its resources. */
delete() {
C._ts_query_delete(this[0]);
this[0] = 0;
}
/**
* Iterate over all of the matches in the order that they were found.
*
* Each match contains the index of the pattern that matched, and a list of
* captures. Because multiple patterns can match the same set of nodes,
* one match may contain captures that appear *before* some of the
* captures from a previous match.
*
* @param {Node} node - The node to execute the query on.
*
* @param {QueryOptions} options - Options for query execution.
*/
matches(node, options = {}) {
const startPosition = options.startPosition ?? ZERO_POINT;
const endPosition = options.endPosition ?? ZERO_POINT;
const startIndex = options.startIndex ?? 0;
const endIndex = options.endIndex ?? 0;
const matchLimit = options.matchLimit ?? 4294967295;
const maxStartDepth = options.maxStartDepth ?? 4294967295;
const timeoutMicros = options.timeoutMicros ?? 0;
const progressCallback = options.progressCallback;
if (typeof matchLimit !== "number") {
throw new Error("Arguments must be numbers");
}
this.matchLimit = matchLimit;
if (endIndex !== 0 && startIndex > endIndex) {
throw new Error("`startIndex` cannot be greater than `endIndex`");
}
if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
throw new Error("`startPosition` cannot be greater than `endPosition`");
}
if (progressCallback) {
C.currentQueryProgressCallback = progressCallback;
}
marshalNode(node);
C._ts_query_matches_wasm(
this[0],
node.tree[0],
startPosition.row,
startPosition.column,
endPosition.row,
endPosition.column,
startIndex,
endIndex,
matchLimit,
maxStartDepth,
timeoutMicros
);
const rawCount = C.getValue(TRANSFER_BUFFER, "i32");
const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
const result = new Array(rawCount);
this.exceededMatchLimit = Boolean(didExceedMatchLimit);
let filteredCount = 0;
let address = startAddress;
for (let i2 = 0; i2 < rawCount; i2++) {
const patternIndex = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captureCount = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captures = new Array(captureCount);
address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
if (this.textPredicates[patternIndex].every((p) => p(captures))) {
result[filteredCount] = { pattern: patternIndex, patternIndex, captures };
const setProperties = this.setProperties[patternIndex];
result[filteredCount].setProperties = setProperties;
const assertedProperties = this.assertedProperties[patternIndex];
result[filteredCount].assertedProperties = assertedProperties;
const refutedProperties = this.refutedProperties[patternIndex];
result[filteredCount].refutedProperties = refutedProperties;
filteredCount++;
}
}
result.length = filteredCount;
C._free(startAddress);
C.currentQueryProgressCallback = null;
return result;
}
/**
* Iterate over all of the individual captures in the order that they
* appear.
*
* This is useful if you don't care about which pattern matched, and just
* want a single, ordered sequence of captures.
*
* @param {Node} node - The node to execute the query on.
*
* @param {QueryOptions} options - Options for query execution.
*/
captures(node, options = {}) {
const startPosition = options.startPosition ?? ZERO_POINT;
const endPosition = options.endPosition ?? ZERO_POINT;
const startIndex = options.startIndex ?? 0;
const endIndex = options.endIndex ?? 0;
const matchLimit = options.matchLimit ?? 4294967295;
const maxStartDepth = options.maxStartDepth ?? 4294967295;
const timeoutMicros = options.timeoutMicros ?? 0;
const progressCallback = options.progressCallback;
if (typeof matchLimit !== "number") {
throw new Error("Arguments must be numbers");
}
this.matchLimit = matchLimit;
if (endIndex !== 0 && startIndex > endIndex) {
throw new Error("`startIndex` cannot be greater than `endIndex`");
}
if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
throw new Error("`startPosition` cannot be greater than `endPosition`");
}
if (progressCallback) {
C.currentQueryProgressCallback = progressCallback;
}
marshalNode(node);
C._ts_query_captures_wasm(
this[0],
node.tree[0],
startPosition.row,
startPosition.column,
endPosition.row,
endPosition.column,
startIndex,
endIndex,
matchLimit,
maxStartDepth,
timeoutMicros
);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
const result = new Array();
this.exceededMatchLimit = Boolean(didExceedMatchLimit);
const captures = new Array();
let address = startAddress;
for (let i2 = 0; i2 < count; i2++) {
const patternIndex = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captureCount = C.getValue(address, "i32");
address += SIZE_OF_INT;
const captureIndex = C.getValue(address, "i32");
address += SIZE_OF_INT;
captures.length = captureCount;
address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
if (this.textPredicates[patternIndex].every((p) => p(captures))) {
const capture = captures[captureIndex];
const setProperties = this.setProperties[patternIndex];
capture.setProperties = setProperties;
const assertedProperties = this.assertedProperties[patternIndex];
capture.assertedProperties = assertedProperties;
const refutedProperties = this.refutedProperties[patternIndex];
capture.refutedProperties = refutedProperties;
result.push(capture);
}
}
C._free(startAddress);
C.currentQueryProgressCallback = null;
return result;
}
/** Get the predicates for a given pattern. */
predicatesForPattern(patternIndex) {
return this.predicates[patternIndex];
}
/**
* Disable a certain capture within a query.
*
* This prevents the capture from being returned in matches, and also
* avoids any resource usage associated with recording the capture.
*/
disableCapture(captureName) {
const captureNameLength = C.lengthBytesUTF8(captureName);
const captureNameAddress = C._malloc(captureNameLength + 1);
C.stringToUTF8(captureName, captureNameAddress, captureNameLength + 1);
C._ts_query_disable_capture(this[0], captureNameAddress, captureNameLength);
C._free(captureNameAddress);
}
/**
* Disable a certain pattern within a query.
*
* This prevents the pattern from matching, and also avoids any resource
* usage associated with the pattern. This throws an error if the pattern
* index is out of bounds.
*/
disablePattern(patternIndex) {
if (patternIndex >= this.predicates.length) {
throw new Error(
`Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
);
}
C._ts_query_disable_pattern(this[0], patternIndex);
}
/**
* Check if, on its last execution, this cursor exceeded its maximum number
* of in-progress matches.
*/
didExceedMatchLimit() {
return this.exceededMatchLimit;
}
/** Get the byte offset where the given pattern starts in the query's source. */
startIndexForPattern(patternIndex) {
if (patternIndex >= this.predicates.length) {
throw new Error(
`Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
);
}
return C._ts_query_start_byte_for_pattern(this[0], patternIndex);
}
/** Get the byte offset where the given pattern ends in the query's source. */
endIndexForPattern(patternIndex) {
if (patternIndex >= this.predicates.length) {
throw new Error(
`Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
);
}
return C._ts_query_end_byte_for_pattern(this[0], patternIndex);
}
/** Get the number of patterns in the query. */
patternCount() {
return C._ts_query_pattern_count(this[0]);
}
/** Get the index for a given capture name. */
captureIndexForName(captureName) {
return this.captureNames.indexOf(captureName);
}
/** Check if a given pattern within a query has a single root node. */
isPatternRooted(patternIndex) {
return C._ts_query_is_pattern_rooted(this[0], patternIndex) === 1;
}
/** Check if a given pattern within a query has a single root node. */
isPatternNonLocal(patternIndex) {
return C._ts_query_is_pattern_non_local(this[0], patternIndex) === 1;
}
/**
* Check if a given step in a query is 'definite'.
*
* A query step is 'definite' if its parent pattern will be guaranteed to
* match successfully once it reaches the step.
*/
isPatternGuaranteedAtStep(byteIndex) {
return C._ts_query_is_pattern_guaranteed_at_step(this[0], byteIndex) === 1;
}
};
// src/language.ts
var LANGUAGE_FUNCTION_REGEX = /^tree_sitter_\w+$/;
var Language = class _Language {
static {
__name(this, "Language");
}
/** @internal */
[0] = 0;
// Internal handle for WASM
/**
* A list of all node types in the language. The index of each type in this
* array is its node type id.
*/
types;
/**
* A list of all field names in the language. The index of each field name in
* this array is its field id.
*/
fields;
/** @internal */
constructor(internal, address) {
assertInternal(internal);
this[0] = address;
this.types = new Array(C._ts_language_symbol_count(this[0]));
for (let i2 = 0, n = this.types.length; i2 < n; i2++) {
if (C._ts_language_symbol_type(this[0], i2) < 2) {
this.types[i2] = C.UTF8ToString(C._ts_language_symbol_name(this[0], i2));
}
}
this.fields = new Array(C._ts_language_field_count(this[0]) + 1);
for (let i2 = 0, n = this.fields.length; i2 < n; i2++) {
const fieldName = C._ts_language_field_name_for_id(this[0], i2);
if (fieldName !== 0) {
this.fields[i2] = C.UTF8ToString(fieldName);
} else {
this.fields[i2] = null;
}
}
}
/**
* Gets the name of the language.
*/
get name() {
const ptr = C._ts_language_name(this[0]);
if (ptr === 0) return null;
return C.UTF8ToString(ptr);
}
/**
* @deprecated since version 0.25.0, use {@link Language#abiVersion} instead
* Gets the version of the language.
*/
get version() {
return C._ts_language_version(this[0]);
}
/**
* Gets the ABI version of the language.
*/
get abiVersion() {
return C._ts_language_abi_version(this[0]);
}
/**
* Get the metadata for this language. This information is generated by the
* CLI, and relies on the language author providing the correct metadata in
* the language's `tree-sitter.json` file.
*/
get metadata() {
C._ts_language_metadata(this[0]);
const length = C.getValue(TRANSFER_BUFFER, "i32");
const address = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
if (length === 0) return null;
return unmarshalLanguageMetadata(address);
}
/**
* Gets the number of fields in the language.
*/
get fieldCount() {
return this.fields.length - 1;
}
/**
* Gets the number of states in the language.
*/
get stateCount() {
return C._ts_language_state_count(this[0]);
}
/**
* Get the field id for a field name.
*/
fieldIdForName(fieldName) {
const result = this.fields.indexOf(fieldName);
return result !== -1 ? result : null;
}
/**
* Get the field name for a field id.
*/
fieldNameForId(fieldId) {
return this.fields[fieldId] ?? null;
}
/**
* Get the node type id for a node type name.
*/
idForNodeType(type, named) {
const typeLength = C.lengthBytesUTF8(type);
const typeAddress = C._malloc(typeLength + 1);
C.stringToUTF8(type, typeAddress, typeLength + 1);
const result = C._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named ? 1 : 0);
C._free(typeAddress);
return result || null;
}
/**
* Gets the number of node types in the language.
*/
get nodeTypeCount() {
return C._ts_language_symbol_count(this[0]);
}
/**
* Get the node type name for a node type id.
*/
nodeTypeForId(typeId) {
const name2 = C._ts_language_symbol_name(this[0], typeId);
return name2 ? C.UTF8ToString(name2) : null;
}
/**
* Check if a node type is named.
*
* @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/2-basic-parsing.html#named-vs-anonymous-nodes}
*/
nodeTypeIsNamed(typeId) {
return C._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
}
/**
* Check if a node type is visible.
*/
nodeTypeIsVisible(typeId) {
return C._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
}
/**
* Get the supertypes ids of this language.
*
* @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types.html?highlight=supertype#supertype-nodes}
*/
get supertypes() {
C._ts_language_supertypes_wasm(this[0]);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
result[i2] = C.getValue(address, "i16");
address += SIZE_OF_SHORT;
}
}
return result;
}
/**
* Get the subtype ids for a given supertype node id.
*/
subtypes(supertype) {
C._ts_language_subtypes_wasm(this[0], supertype);
const count = C.getValue(TRANSFER_BUFFER, "i32");
const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
const result = new Array(count);
if (count > 0) {
let address = buffer;
for (let i2 = 0; i2 < count; i2++) {
result[i2] = C.getValue(address, "i16");
address += SIZE_OF_SHORT;
}
}
return result;
}
/**
* Get the next state id for a given state id and node type id.
*/
nextState(stateId, typeId) {
return C._ts_language_next_state(this[0], stateId, typeId);
}
/**
* Create a new lookahead iterator for this language and parse state.
*
* This returns `null` if state is invalid for this language.
*
* Iterating {@link LookaheadIterator} will yield valid symbols in the given
* parse state. Newly created lookahead iterators will return the `ERROR`
* symbol from {@link LookaheadIterator#currentType}.
*
* Lookahead iterators can be useful for generating suggestions and improving
* syntax error diagnostics. To get symbols valid in an `ERROR` node, use the
* lookahead iterator on its first leaf node state. For `MISSING` nodes, a
* lookahead iterator created on the previous non-extra leaf node may be
* appropriate.
*/
lookaheadIterator(stateId) {
const address = C._ts_lookahead_iterator_new(this[0], stateId);
if (address) return new LookaheadIterator(INTERNAL, address, this);
return null;
}
/**
* @deprecated since version 0.25.0, call `new` on a {@link Query} instead
*
* Create a new query from a string containing one or more S-expression
* patterns.
*
* The query is associated with a particular language, and can only be run
* on syntax nodes parsed with that language. References to Queries can be
* shared between multiple threads.
*
* @link {@see https://tree-sitter.github.io/tree-sitter/using-parsers/queries}
*/
query(source) {
console.warn("Language.query is deprecated. Use new Query(language, source) instead.");
return new Query(this, source);
}
/**
* Load a language from a WebAssembly module.
* The module can be provided as a path to a file or as a buffer.
*/
static async load(input) {
let bytes;
if (input instanceof Uint8Array) {
bytes = Promise.resolve(input);
} else {
if (globalThis.process?.versions.node) {
const fs2 = __require("fs/promises");
bytes = fs2.readFile(input);
} else {
bytes = fetch(input).then((response) => response.arrayBuffer().then((buffer) => {
if (response.ok) {
return new Uint8Array(buffer);
} else {
const body2 = new TextDecoder("utf-8").decode(buffer);
throw new Error(`Language.load failed with status ${response.status}.
${body2}`);
}
}));
}
}
const mod = await C.loadWebAssemblyModule(await bytes, { loadAsync: true });
const symbolNames = Object.keys(mod);
const functionName = symbolNames.find((key) => LANGUAGE_FUNCTION_REGEX.test(key) && !key.includes("external_scanner_"));
if (!functionName) {
console.log(`Couldn't find language function in WASM file. Symbols:
${JSON.stringify(symbolNames, null, 2)}`);
throw new Error("Language.load failed: no language function found in WASM file");
}
const languageAddress = mod[functionName]();
return new _Language(INTERNAL, languageAddress);
}
};
// lib/tree-sitter.mjs
var Module2 = (() => {
var _scriptName = import.meta.url;
return async function(moduleArg = {}) {
var moduleRtn;
var Module = moduleArg;
var readyPromiseResolve, readyPromiseReject;
var readyPromise = new Promise((resolve, reject) => {
readyPromiseResolve = resolve;
readyPromiseReject = reject;
});
var ENVIRONMENT_IS_WEB = typeof window == "object";
var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != "undefined";
var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string" && process.type != "renderer";
var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER;
if (ENVIRONMENT_IS_NODE) {
const { createRequire } = await import("module");
var require = createRequire("/");
}
Module.currentQueryProgressCallback = null;
Module.currentProgressCallback = null;
Module.currentLogCallback = null;
Module.currentParseCallback = null;
var moduleOverrides = Object.assign({}, Module);
var arguments_ = [];
var thisProgram = "./this.program";
var quit_ = /* @__PURE__ */ __name((status, toThrow) => {
throw toThrow;
}, "quit_");
var scriptDirectory = "";
function locateFile(path) {
if (Module["locateFile"]) {
return Module["locateFile"](path, scriptDirectory);
}
return scriptDirectory + path;
}
__name(locateFile, "locateFile");
var readAsync, readBinary;
if (ENVIRONMENT_IS_NODE) {
var fs = require("fs");
var nodePath = require("path");
if (!import.meta.url.startsWith("data:")) {
scriptDirectory = nodePath.dirname(require("url").fileURLToPath(import.meta.url)) + "/";
}
readBinary = /* @__PURE__ */ __name((filename) => {
filename = isFileURI(filename) ? new URL(filename) : filename;
var ret = fs.readFileSync(filename);
return ret;
}, "readBinary");
readAsync = /* @__PURE__ */ __name(async (filename, binary2 = true) => {
filename = isFileURI(filename) ? new URL(filename) : filename;
var ret = fs.readFileSync(filename, binary2 ? void 0 : "utf8");
return ret;
}, "readAsync");
if (!Module["thisProgram"] && process.argv.length > 1) {
thisProgram = process.argv[1].replace(/\\/g, "/");
}
arguments_ = process.argv.slice(2);
quit_ = /* @__PURE__ */ __name((status, toThrow) => {
process.exitCode = status;
throw toThrow;
}, "quit_");
} else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
if (ENVIRONMENT_IS_WORKER) {
scriptDirectory = self.location.href;
} else if (typeof document != "undefined" && document.currentScript) {
scriptDirectory = document.currentScript.src;
}
if (_scriptName) {
scriptDirectory = _scriptName;
}
if (scriptDirectory.startsWith("blob:")) {
scriptDirectory = "";
} else {
scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1);
}
{
if (ENVIRONMENT_IS_WORKER) {
readBinary = /* @__PURE__ */ __name((url) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.responseType = "arraybuffer";
xhr.send(null);
return new Uint8Array(
/** @type{!ArrayBuffer} */
xhr.response
);
}, "readBinary");
}
readAsync = /* @__PURE__ */ __name(async (url) => {
if (isFileURI(url)) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
xhr.onload = () => {
if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
resolve(xhr.response);
return;
}
reject(xhr.status);
};
xhr.onerror = reject;
xhr.send(null);
});
}
var response = await fetch(url, {
credentials: "same-origin"
});
if (response.ok) {
return response.arrayBuffer();
}
throw new Error(response.status + " : " + response.url);
}, "readAsync");
}
} else {
}
var out = Module["print"] || console.log.bind(console);
var err = Module["printErr"] || console.error.bind(console);
Object.assign(Module, moduleOverrides);
moduleOverrides = null;
if (Module["arguments"]) arguments_ = Module["arguments"];
if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
var dynamicLibraries = Module["dynamicLibraries"] || [];
var wasmBinary = Module["wasmBinary"];
var wasmMemory;
var ABORT = false;
var EXITSTATUS;
function assert(condition, text) {
if (!condition) {
abort(text);
}
}
__name(assert, "assert");
var HEAP, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64;
var HEAP_DATA_VIEW;
var runtimeInitialized = false;
var dataURIPrefix = "data:application/octet-stream;base64,";
var isDataURI = /* @__PURE__ */ __name((filename) => filename.startsWith(dataURIPrefix), "isDataURI");
var isFileURI = /* @__PURE__ */ __name((filename) => filename.startsWith("file://"), "isFileURI");
function updateMemoryViews() {
var b = wasmMemory.buffer;
Module["HEAP_DATA_VIEW"] = HEAP_DATA_VIEW = new DataView(b);
Module["HEAP8"] = HEAP8 = new Int8Array(b);
Module["HEAP16"] = HEAP16 = new Int16Array(b);
Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
Module["HEAP32"] = HEAP32 = new Int32Array(b);
Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
Module["HEAPF64"] = HEAPF64 = new Float64Array(b);
Module["HEAP64"] = HEAP64 = new BigInt64Array(b);
Module["HEAPU64"] = HEAPU64 = new BigUint64Array(b);
}
__name(updateMemoryViews, "updateMemoryViews");
if (Module["wasmMemory"]) {
wasmMemory = Module["wasmMemory"];
} else {
var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 33554432;
wasmMemory = new WebAssembly.Memory({
"initial": INITIAL_MEMORY / 65536,
// In theory we should not need to emit the maximum if we want "unlimited"
// or 4GB of memory, but VMs error on that atm, see
// https://github.com/emscripten-core/emscripten/issues/14130
// And in the pthreads case we definitely need to emit a maximum. So
// always emit one.
"maximum": 32768
});
}
updateMemoryViews();
var __ATPRERUN__ = [];
var __ATINIT__ = [];
var __ATMAIN__ = [];
var __ATEXIT__ = [];
var __ATPOSTRUN__ = [];
var __RELOC_FUNCS__ = [];
function preRun() {
if (Module["preRun"]) {
if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]];
while (Module["preRun"].length) {
addOnPreRun(Module["preRun"].shift());
}
}
callRuntimeCallbacks(__ATPRERUN__);
}
__name(preRun, "preRun");
function initRuntime() {
runtimeInitialized = true;
callRuntimeCallbacks(__RELOC_FUNCS__);
callRuntimeCallbacks(__ATINIT__);
}
__name(initRuntime, "initRuntime");
function preMain() {
callRuntimeCallbacks(__ATMAIN__);
}
__name(preMain, "preMain");
function postRun() {
if (Module["postRun"]) {
if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]];
while (Module["postRun"].length) {
addOnPostRun(Module["postRun"].shift());
}
}
callRuntimeCallbacks(__ATPOSTRUN__);
}
__name(postRun, "postRun");
function addOnPreRun(cb) {
__ATPRERUN__.unshift(cb);
}
__name(addOnPreRun, "addOnPreRun");
function addOnInit(cb) {
__ATINIT__.unshift(cb);
}
__name(addOnInit, "addOnInit");
function addOnPreMain(cb) {
__ATMAIN__.unshift(cb);
}
__name(addOnPreMain, "addOnPreMain");
function addOnExit(cb) {
}
__name(addOnExit, "addOnExit");
function addOnPostRun(cb) {
__ATPOSTRUN__.unshift(cb);
}
__name(addOnPostRun, "addOnPostRun");
var runDependencies = 0;
var dependenciesFulfilled = null;
function getUniqueRunDependency(id) {
return id;
}
__name(getUniqueRunDependency, "getUniqueRunDependency");
function addRunDependency(id) {
runDependencies++;
Module["monitorRunDependencies"]?.(runDependencies);
}
__name(addRunDependency, "addRunDependency");
function removeRunDependency(id) {
runDependencies--;
Module["monitorRunDependencies"]?.(runDependencies);
if (runDependencies == 0) {
if (dependenciesFulfilled) {
var callback = dependenciesFulfilled;
dependenciesFulfilled = null;
callback();
}
}
}
__name(removeRunDependency, "removeRunDependency");
function abort(what) {
Module["onAbort"]?.(what);
what = "Aborted(" + what + ")";
err(what);
ABORT = true;
what += ". Build with -sASSERTIONS for more info.";
var e = new WebAssembly.RuntimeError(what);
readyPromiseReject(e);
throw e;
}
__name(abort, "abort");
var wasmBinaryFile;
function findWasmBinary() {
if (Module["locateFile"]) {
var f = "tree-sitter.wasm";
if (!isDataURI(f)) {
return locateFile(f);
}
return f;
}
return new URL("tree-sitter.wasm", import.meta.url).href;
}
__name(findWasmBinary, "findWasmBinary");
function getBinarySync(file) {
if (file == wasmBinaryFile && wasmBinary) {
return new Uint8Array(wasmBinary);
}
if (readBinary) {
return readBinary(file);
}
throw "both async and sync fetching of the wasm failed";
}
__name(getBinarySync, "getBinarySync");
async function getWasmBinary(binaryFile) {
if (!wasmBinary) {
try {
var response = await readAsync(binaryFile);
return new Uint8Array(response);
} catch {
}
}
return getBinarySync(binaryFile);
}
__name(getWasmBinary, "getWasmBinary");
async function instantiateArrayBuffer(binaryFile, imports) {
try {
var binary2 = await getWasmBinary(binaryFile);
var instance2 = await WebAssembly.instantiate(binary2, imports);
return instance2;
} catch (reason) {
err(`failed to asynchronously prepare wasm: ${reason}`);
abort(reason);
}
}
__name(instantiateArrayBuffer, "instantiateArrayBuffer");
async function instantiateAsync(binary2, binaryFile, imports) {
if (!binary2 && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {
try {
var response = fetch(binaryFile, {
credentials: "same-origin"
});
var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);
return instantiationResult;
} catch (reason) {
err(`wasm streaming compile failed: ${reason}`);
err("falling back to ArrayBuffer instantiation");
}
}
return instantiateArrayBuffer(binaryFile, imports);
}
__name(instantiateAsync, "instantiateAsync");
function getWasmImports() {
return {
"env": wasmImports,
"wasi_snapshot_preview1": wasmImports,
"GOT.mem": new Proxy(wasmImports, GOTHandler),
"GOT.func": new Proxy(wasmImports, GOTHandler)
};
}
__name(getWasmImports, "getWasmImports");
async function createWasm() {
function receiveInstance(instance2, module2) {
wasmExports = instance2.exports;
wasmExports = relocateExports(wasmExports, 1024);
var metadata2 = getDylinkMetadata(module2);
if (metadata2.neededDynlibs) {
dynamicLibraries = metadata2.neededDynlibs.concat(dynamicLibraries);
}
mergeLibSymbols(wasmExports, "main");
LDSO.init();
loadDylibs();
addOnInit(wasmExports["__wasm_call_ctors"]);
__RELOC_FUNCS__.push(wasmExports["__wasm_apply_data_relocs"]);
removeRunDependency("wasm-instantiate");
return wasmExports;
}
__name(receiveInstance, "receiveInstance");
addRunDependency("wasm-instantiate");
function receiveInstantiationResult(result2) {
return receiveInstance(result2["instance"], result2["module"]);
}
__name(receiveInstantiationResult, "receiveInstantiationResult");
var info2 = getWasmImports();
if (Module["instantiateWasm"]) {
try {
return Module["instantiateWasm"](info2, receiveInstance);
} catch (e) {
err(`Module.instantiateWasm callback failed with error: ${e}`);
readyPromiseReject(e);
}
}
wasmBinaryFile ??= findWasmBinary();
try {
var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info2);
var exports = receiveInstantiationResult(result);
return exports;
} catch (e) {
readyPromiseReject(e);
return Promise.reject(e);
}
}
__name(createWasm, "createWasm");
var ASM_CONSTS = {};
class ExitStatus {
static {
__name(this, "ExitStatus");
}
name = "ExitStatus";
constructor(status) {
this.message = `Program terminated with exit(${status})`;
this.status = status;
}
}
var GOT = {};
var currentModuleWeakSymbols = /* @__PURE__ */ new Set([]);
var GOTHandler = {
get(obj, symName) {
var rtn = GOT[symName];
if (!rtn) {
rtn = GOT[symName] = new WebAssembly.Global({
"value": "i32",
"mutable": true
});
}
if (!currentModuleWeakSymbols.has(symName)) {
rtn.required = true;
}
return rtn;
}
};
var LE_HEAP_LOAD_F32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat32(byteOffset, true), "LE_HEAP_LOAD_F32");
var LE_HEAP_LOAD_F64 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat64(byteOffset, true), "LE_HEAP_LOAD_F64");
var LE_HEAP_LOAD_I16 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt16(byteOffset, true), "LE_HEAP_LOAD_I16");
var LE_HEAP_LOAD_I32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt32(byteOffset, true), "LE_HEAP_LOAD_I32");
var LE_HEAP_LOAD_U16 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getUint16(byteOffset, true), "LE_HEAP_LOAD_U16");
var LE_HEAP_LOAD_U32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getUint32(byteOffset, true), "LE_HEAP_LOAD_U32");
var LE_HEAP_STORE_F32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat32(byteOffset, value, true), "LE_HEAP_STORE_F32");
var LE_HEAP_STORE_F64 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat64(byteOffset, value, true), "LE_HEAP_STORE_F64");
var LE_HEAP_STORE_I16 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt16(byteOffset, value, true), "LE_HEAP_STORE_I16");
var LE_HEAP_STORE_I32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt32(byteOffset, value, true), "LE_HEAP_STORE_I32");
var LE_HEAP_STORE_U16 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setUint16(byteOffset, value, true), "LE_HEAP_STORE_U16");
var LE_HEAP_STORE_U32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setUint32(byteOffset, value, true), "LE_HEAP_STORE_U32");
var callRuntimeCallbacks = /* @__PURE__ */ __name((callbacks) => {
while (callbacks.length > 0) {
callbacks.shift()(Module);
}
}, "callRuntimeCallbacks");
var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
var UTF8ArrayToString = /* @__PURE__ */ __name((heapOrArray, idx = 0, maxBytesToRead = NaN) => {
var endIdx = idx + maxBytesToRead;
var endPtr = idx;
while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
}
var str = "";
while (idx < endPtr) {
var u0 = heapOrArray[idx++];
if (!(u0 & 128)) {
str += String.fromCharCode(u0);
continue;
}
var u1 = heapOrArray[idx++] & 63;
if ((u0 & 224) == 192) {
str += String.fromCharCode((u0 & 31) << 6 | u1);
continue;
}
var u2 = heapOrArray[idx++] & 63;
if ((u0 & 240) == 224) {
u0 = (u0 & 15) << 12 | u1 << 6 | u2;
} else {
u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
}
if (u0 < 65536) {
str += String.fromCharCode(u0);
} else {
var ch = u0 - 65536;
str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
}
}
return str;
}, "UTF8ArrayToString");
var getDylinkMetadata = /* @__PURE__ */ __name((binary2) => {
var offset = 0;
var end = 0;
function getU8() {
return binary2[offset++];
}
__name(getU8, "getU8");
function getLEB() {
var ret = 0;
var mul = 1;
while (1) {
var byte = binary2[offset++];
ret += (byte & 127) * mul;
mul *= 128;
if (!(byte & 128)) break;
}
return ret;
}
__name(getLEB, "getLEB");
function getString() {
var len = getLEB();
offset += len;
return UTF8ArrayToString(binary2, offset - len, len);
}
__name(getString, "getString");
function failIf(condition, message) {
if (condition) throw new Error(message);
}
__name(failIf, "failIf");
var name2 = "dylink.0";
if (binary2 instanceof WebAssembly.Module) {
var dylinkSection = WebAssembly.Module.customSections(binary2, name2);
if (dylinkSection.length === 0) {
name2 = "dylink";
dylinkSection = WebAssembly.Module.customSections(binary2, name2);
}
failIf(dylinkSection.length === 0, "need dylink section");
binary2 = new Uint8Array(dylinkSection[0]);
end = binary2.length;
} else {
var int32View = new Uint32Array(new Uint8Array(binary2.subarray(0, 24)).buffer);
var magicNumberFound = int32View[0] == 1836278016 || int32View[0] == 6386541;
failIf(!magicNumberFound, "need to see wasm magic number");
failIf(binary2[8] !== 0, "need the dylink section to be first");
offset = 9;
var section_size = getLEB();
end = offset + section_size;
name2 = getString();
}
var customSection = {
neededDynlibs: [],
tlsExports: /* @__PURE__ */ new Set(),
weakImports: /* @__PURE__ */ new Set()
};
if (name2 == "dylink") {
customSection.memorySize = getLEB();
customSection.memoryAlign = getLEB();
customSection.tableSize = getLEB();
customSection.tableAlign = getLEB();
var neededDynlibsCount = getLEB();
for (var i2 = 0; i2 < neededDynlibsCount; ++i2) {
var libname = getString();
customSection.neededDynlibs.push(libname);
}
} else {
failIf(name2 !== "dylink.0");
var WASM_DYLINK_MEM_INFO = 1;
var WASM_DYLINK_NEEDED = 2;
var WASM_DYLINK_EXPORT_INFO = 3;
var WASM_DYLINK_IMPORT_INFO = 4;
var WASM_SYMBOL_TLS = 256;
var WASM_SYMBOL_BINDING_MASK = 3;
var WASM_SYMBOL_BINDING_WEAK = 1;
while (offset < end) {
var subsectionType = getU8();
var subsectionSize = getLEB();
if (subsectionType === WASM_DYLINK_MEM_INFO) {
customSection.memorySize = getLEB();
customSection.memoryAlign = getLEB();
customSection.tableSize = getLEB();
customSection.tableAlign = getLEB();
} else if (subsectionType === WASM_DYLINK_NEEDED) {
var neededDynlibsCount = getLEB();
for (var i2 = 0; i2 < neededDynlibsCount; ++i2) {
libname = getString();
customSection.neededDynlibs.push(libname);
}
} else if (subsectionType === WASM_DYLINK_EXPORT_INFO) {
var count = getLEB();
while (count--) {
var symname = getString();
var flags2 = getLEB();
if (flags2 & WASM_SYMBOL_TLS) {
customSection.tlsExports.add(symname);
}
}
} else if (subsectionType === WASM_DYLINK_IMPORT_INFO) {
var count = getLEB();
while (count--) {
var modname = getString();
var symname = getString();
var flags2 = getLEB();
if ((flags2 & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK) {
customSection.weakImports.add(symname);
}
}
} else {
offset += subsectionSize;
}
}
}
return customSection;
}, "getDylinkMetadata");
function getValue(ptr, type = "i8") {
if (type.endsWith("*")) type = "*";
switch (type) {
case "i1":
return HEAP8[ptr];
case "i8":
return HEAP8[ptr];
case "i16":
return LE_HEAP_LOAD_I16((ptr >> 1) * 2);
case "i32":
return LE_HEAP_LOAD_I32((ptr >> 2) * 4);
case "i64":
return HEAP64[ptr >> 3];
case "float":
return LE_HEAP_LOAD_F32((ptr >> 2) * 4);
case "double":
return LE_HEAP_LOAD_F64((ptr >> 3) * 8);
case "*":
return LE_HEAP_LOAD_U32((ptr >> 2) * 4);
default:
abort(`invalid type for getValue: ${type}`);
}
}
__name(getValue, "getValue");
var newDSO = /* @__PURE__ */ __name((name2, handle2, syms) => {
var dso = {
refcount: Infinity,
name: name2,
exports: syms,
global: true
};
LDSO.loadedLibsByName[name2] = dso;
if (handle2 != void 0) {
LDSO.loadedLibsByHandle[handle2] = dso;
}
return dso;
}, "newDSO");
var LDSO = {
loadedLibsByName: {},
loadedLibsByHandle: {},
init() {
newDSO("__main__", 0, wasmImports);
}
};
var ___heap_base = 78224;
var alignMemory = /* @__PURE__ */ __name((size, alignment) => Math.ceil(size / alignment) * alignment, "alignMemory");
var getMemory = /* @__PURE__ */ __name((size) => {
if (runtimeInitialized) {
return _calloc(size, 1);
}
var ret = ___heap_base;
var end = ret + alignMemory(size, 16);
___heap_base = end;
GOT["__heap_base"].value = end;
return ret;
}, "getMemory");
var isInternalSym = /* @__PURE__ */ __name((symName) => ["__cpp_exception", "__c_longjmp", "__wasm_apply_data_relocs", "__dso_handle", "__tls_size", "__tls_align", "__set_stack_limits", "_emscripten_tls_init", "__wasm_init_tls", "__wasm_call_ctors", "__start_em_asm", "__stop_em_asm", "__start_em_js", "__stop_em_js"].includes(symName) || symName.startsWith("__em_js__"), "isInternalSym");
var uleb128Encode = /* @__PURE__ */ __name((n, target) => {
if (n < 128) {
target.push(n);
} else {
target.push(n % 128 | 128, n >> 7);
}
}, "uleb128Encode");
var sigToWasmTypes = /* @__PURE__ */ __name((sig) => {
var typeNames = {
"i": "i32",
"j": "i64",
"f": "f32",
"d": "f64",
"e": "externref",
"p": "i32"
};
var type = {
parameters: [],
results: sig[0] == "v" ? [] : [typeNames[sig[0]]]
};
for (var i2 = 1; i2 < sig.length; ++i2) {
type.parameters.push(typeNames[sig[i2]]);
}
return type;
}, "sigToWasmTypes");
var generateFuncType = /* @__PURE__ */ __name((sig, target) => {
var sigRet = sig.slice(0, 1);
var sigParam = sig.slice(1);
var typeCodes = {
"i": 127,
// i32
"p": 127,
// i32
"j": 126,
// i64
"f": 125,
// f32
"d": 124,
// f64
"e": 111
};
target.push(96);
uleb128Encode(sigParam.length, target);
for (var i2 = 0; i2 < sigParam.length; ++i2) {
target.push(typeCodes[sigParam[i2]]);
}
if (sigRet == "v") {
target.push(0);
} else {
target.push(1, typeCodes[sigRet]);
}
}, "generateFuncType");
var convertJsFunctionToWasm = /* @__PURE__ */ __name((func2, sig) => {
if (typeof WebAssembly.Function == "function") {
return new WebAssembly.Function(sigToWasmTypes(sig), func2);
}
var typeSectionBody = [1];
generateFuncType(sig, typeSectionBody);
var bytes = [
0,
97,
115,
109,
// magic ("\0asm")
1,
0,
0,
0,
// version: 1
1
];
uleb128Encode(typeSectionBody.length, bytes);
bytes.push(...typeSectionBody);
bytes.push(
2,
7,
// import section
// (import "e" "f" (func 0 (type 0)))
1,
1,
101,
1,
102,
0,
0,
7,
5,
// export section
// (export "f" (func 0 (type 0)))
1,
1,
102,
0,
0
);
var module2 = new WebAssembly.Module(new Uint8Array(bytes));
var instance2 = new WebAssembly.Instance(module2, {
"e": {
"f": func2
}
});
var wrappedFunc = instance2.exports["f"];
return wrappedFunc;
}, "convertJsFunctionToWasm");
var wasmTableMirror = [];
var wasmTable = new WebAssembly.Table({
"initial": 31,
"element": "anyfunc"
});
var getWasmTableEntry = /* @__PURE__ */ __name((funcPtr) => {
var func2 = wasmTableMirror[funcPtr];
if (!func2) {
if (funcPtr >= wasmTableMirror.length) wasmTableMirror.length = funcPtr + 1;
wasmTableMirror[funcPtr] = func2 = wasmTable.get(funcPtr);
}
return func2;
}, "getWasmTableEntry");
var updateTableMap = /* @__PURE__ */ __name((offset, count) => {
if (functionsInTableMap) {
for (var i2 = offset; i2 < offset + count; i2++) {
var item = getWasmTableEntry(i2);
if (item) {
functionsInTableMap.set(item, i2);
}
}
}
}, "updateTableMap");
var functionsInTableMap;
var getFunctionAddress = /* @__PURE__ */ __name((func2) => {
if (!functionsInTableMap) {
functionsInTableMap = /* @__PURE__ */ new WeakMap();
updateTableMap(0, wasmTable.length);
}
return functionsInTableMap.get(func2) || 0;
}, "getFunctionAddress");
var freeTableIndexes = [];
var getEmptyTableSlot = /* @__PURE__ */ __name(() => {
if (freeTableIndexes.length) {
return freeTableIndexes.pop();
}
try {
wasmTable.grow(1);
} catch (err2) {
if (!(err2 instanceof RangeError)) {
throw err2;
}
throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.";
}
return wasmTable.length - 1;
}, "getEmptyTableSlot");
var setWasmTableEntry = /* @__PURE__ */ __name((idx, func2) => {
wasmTable.set(idx, func2);
wasmTableMirror[idx] = wasmTable.get(idx);
}, "setWasmTableEntry");
var addFunction = /* @__PURE__ */ __name((func2, sig) => {
var rtn = getFunctionAddress(func2);
if (rtn) {
return rtn;
}
var ret = getEmptyTableSlot();
try {
setWasmTableEntry(ret, func2);
} catch (err2) {
if (!(err2 instanceof TypeError)) {
throw err2;
}
var wrapped = convertJsFunctionToWasm(func2, sig);
setWasmTableEntry(ret, wrapped);
}
functionsInTableMap.set(func2, ret);
return ret;
}, "addFunction");
var updateGOT = /* @__PURE__ */ __name((exports, replace) => {
for (var symName in exports) {
if (isInternalSym(symName)) {
continue;
}
var value = exports[symName];
GOT[symName] ||= new WebAssembly.Global({
"value": "i32",
"mutable": true
});
if (replace || GOT[symName].value == 0) {
if (typeof value == "function") {
GOT[symName].value = addFunction(value);
} else if (typeof value == "number") {
GOT[symName].value = value;
} else {
err(`unhandled export type for '${symName}': ${typeof value}`);
}
}
}
}, "updateGOT");
var relocateExports = /* @__PURE__ */ __name((exports, memoryBase2, replace) => {
var relocated = {};
for (var e in exports) {
var value = exports[e];
if (typeof value == "object") {
value = value.value;
}
if (typeof value == "number") {
value += memoryBase2;
}
relocated[e] = value;
}
updateGOT(relocated, replace);
return relocated;
}, "relocateExports");
var isSymbolDefined = /* @__PURE__ */ __name((symName) => {
var existing = wasmImports[symName];
if (!existing || existing.stub) {
return false;
}
return true;
}, "isSymbolDefined");
var dynCall = /* @__PURE__ */ __name((sig, ptr, args2 = []) => {
var rtn = getWasmTableEntry(ptr)(...args2);
return rtn;
}, "dynCall");
var stackSave = /* @__PURE__ */ __name(() => _emscripten_stack_get_current(), "stackSave");
var stackRestore = /* @__PURE__ */ __name((val) => __emscripten_stack_restore(val), "stackRestore");
var createInvokeFunction = /* @__PURE__ */ __name((sig) => (ptr, ...args2) => {
var sp = stackSave();
try {
return dynCall(sig, ptr, args2);
} catch (e) {
stackRestore(sp);
if (e !== e + 0) throw e;
_setThrew(1, 0);
if (sig[0] == "j") return 0n;
}
}, "createInvokeFunction");
var resolveGlobalSymbol = /* @__PURE__ */ __name((symName, direct = false) => {
var sym;
if (isSymbolDefined(symName)) {
sym = wasmImports[symName];
} else if (symName.startsWith("invoke_")) {
sym = wasmImports[symName] = createInvokeFunction(symName.split("_")[1]);
}
return {
sym,
name: symName
};
}, "resolveGlobalSymbol");
var UTF8ToString = /* @__PURE__ */ __name((ptr, maxBytesToRead) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "", "UTF8ToString");
var loadWebAssemblyModule = /* @__PURE__ */ __name((binary, flags, libName, localScope, handle) => {
var metadata = getDylinkMetadata(binary);
currentModuleWeakSymbols = metadata.weakImports;
function loadModule() {
var firstLoad = !handle || !HEAP8[handle + 8];
if (firstLoad) {
var memAlign = Math.pow(2, metadata.memoryAlign);
var memoryBase = metadata.memorySize ? alignMemory(getMemory(metadata.memorySize + memAlign), memAlign) : 0;
var tableBase = metadata.tableSize ? wasmTable.length : 0;
if (handle) {
HEAP8[handle + 8] = 1;
LE_HEAP_STORE_U32((handle + 12 >> 2) * 4, memoryBase);
LE_HEAP_STORE_I32((handle + 16 >> 2) * 4, metadata.memorySize);
LE_HEAP_STORE_U32((handle + 20 >> 2) * 4, tableBase);
LE_HEAP_STORE_I32((handle + 24 >> 2) * 4, metadata.tableSize);
}
} else {
memoryBase = LE_HEAP_LOAD_U32((handle + 12 >> 2) * 4);
tableBase = LE_HEAP_LOAD_U32((handle + 20 >> 2) * 4);
}
var tableGrowthNeeded = tableBase + metadata.tableSize - wasmTable.length;
if (tableGrowthNeeded > 0) {
wasmTable.grow(tableGrowthNeeded);
}
var moduleExports;
function resolveSymbol(sym) {
var resolved = resolveGlobalSymbol(sym).sym;
if (!resolved && localScope) {
resolved = localScope[sym];
}
if (!resolved) {
resolved = moduleExports[sym];
}
return resolved;
}
__name(resolveSymbol, "resolveSymbol");
var proxyHandler = {
get(stubs, prop) {
switch (prop) {
case "__memory_base":
return memoryBase;
case "__table_base":
return tableBase;
}
if (prop in wasmImports && !wasmImports[prop].stub) {
return wasmImports[prop];
}
if (!(prop in stubs)) {
var resolved;
stubs[prop] = (...args2) => {
resolved ||= resolveSymbol(prop);
return resolved(...args2);
};
}
return stubs[prop];
}
};
var proxy = new Proxy({}, proxyHandler);
var info = {
"GOT.mem": new Proxy({}, GOTHandler),
"GOT.func": new Proxy({}, GOTHandler),
"env": proxy,
"wasi_snapshot_preview1": proxy
};
function postInstantiation(module, instance) {
updateTableMap(tableBase, metadata.tableSize);
moduleExports = relocateExports(instance.exports, memoryBase);
if (!flags.allowUndefined) {
reportUndefinedSymbols();
}
function addEmAsm(addr, body) {
var args = [];
var arity = 0;
for (; arity < 16; arity++) {
if (body.indexOf("$" + arity) != -1) {
args.push("$" + arity);
} else {
break;
}
}
args = args.join(",");
var func = `(${args}) => { ${body} };`;
ASM_CONSTS[start] = eval(func);
}
__name(addEmAsm, "addEmAsm");
if ("__start_em_asm" in moduleExports) {
var start = moduleExports["__start_em_asm"];
var stop = moduleExports["__stop_em_asm"];
while (start < stop) {
var jsString = UTF8ToString(start);
addEmAsm(start, jsString);
start = HEAPU8.indexOf(0, start) + 1;
}
}
function addEmJs(name, cSig, body) {
var jsArgs = [];
cSig = cSig.slice(1, -1);
if (cSig != "void") {
cSig = cSig.split(",");
for (var i in cSig) {
var jsArg = cSig[i].split(" ").pop();
jsArgs.push(jsArg.replace("*", ""));
}
}
var func = `(${jsArgs}) => ${body};`;
moduleExports[name] = eval(func);
}
__name(addEmJs, "addEmJs");
for (var name in moduleExports) {
if (name.startsWith("__em_js__")) {
var start = moduleExports[name];
var jsString = UTF8ToString(start);
var parts = jsString.split("<::>");
addEmJs(name.replace("__em_js__", ""), parts[0], parts[1]);
delete moduleExports[name];
}
}
var applyRelocs = moduleExports["__wasm_apply_data_relocs"];
if (applyRelocs) {
if (runtimeInitialized) {
applyRelocs();
} else {
__RELOC_FUNCS__.push(applyRelocs);
}
}
var init = moduleExports["__wasm_call_ctors"];
if (init) {
if (runtimeInitialized) {
init();
} else {
__ATINIT__.push(init);
}
}
return moduleExports;
}
__name(postInstantiation, "postInstantiation");
if (flags.loadAsync) {
if (binary instanceof WebAssembly.Module) {
var instance = new WebAssembly.Instance(binary, info);
return Promise.resolve(postInstantiation(binary, instance));
}
return WebAssembly.instantiate(binary, info).then((result) => postInstantiation(result.module, result.instance));
}
var module = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary);
var instance = new WebAssembly.Instance(module, info);
return postInstantiation(module, instance);
}
__name(loadModule, "loadModule");
if (flags.loadAsync) {
return metadata.neededDynlibs.reduce((chain, dynNeeded) => chain.then(() => loadDynamicLibrary(dynNeeded, flags, localScope)), Promise.resolve()).then(loadModule);
}
metadata.neededDynlibs.forEach((needed) => loadDynamicLibrary(needed, flags, localScope));
return loadModule();
}, "loadWebAssemblyModule");
var mergeLibSymbols = /* @__PURE__ */ __name((exports, libName2) => {
for (var [sym, exp] of Object.entries(exports)) {
const setImport = /* @__PURE__ */ __name((target) => {
if (!isSymbolDefined(target)) {
wasmImports[target] = exp;
}
}, "setImport");
setImport(sym);
const main_alias = "__main_argc_argv";
if (sym == "main") {
setImport(main_alias);
}
if (sym == main_alias) {
setImport("main");
}
}
}, "mergeLibSymbols");
var asyncLoad = /* @__PURE__ */ __name(async (url) => {
var arrayBuffer = await readAsync(url);
return new Uint8Array(arrayBuffer);
}, "asyncLoad");
function loadDynamicLibrary(libName2, flags2 = {
global: true,
nodelete: true
}, localScope2, handle2) {
var dso = LDSO.loadedLibsByName[libName2];
if (dso) {
if (!flags2.global) {
if (localScope2) {
Object.assign(localScope2, dso.exports);
}
} else if (!dso.global) {
dso.global = true;
mergeLibSymbols(dso.exports, libName2);
}
if (flags2.nodelete && dso.refcount !== Infinity) {
dso.refcount = Infinity;
}
dso.refcount++;
if (handle2) {
LDSO.loadedLibsByHandle[handle2] = dso;
}
return flags2.loadAsync ? Promise.resolve(true) : true;
}
dso = newDSO(libName2, handle2, "loading");
dso.refcount = flags2.nodelete ? Infinity : 1;
dso.global = flags2.global;
function loadLibData() {
if (handle2) {
var data = LE_HEAP_LOAD_U32((handle2 + 28 >> 2) * 4);
var dataSize = LE_HEAP_LOAD_U32((handle2 + 32 >> 2) * 4);
if (data && dataSize) {
var libData = HEAP8.slice(data, data + dataSize);
return flags2.loadAsync ? Promise.resolve(libData) : libData;
}
}
var libFile = locateFile(libName2);
if (flags2.loadAsync) {
return asyncLoad(libFile);
}
if (!readBinary) {
throw new Error(`${libFile}: file not found, and synchronous loading of external files is not available`);
}
return readBinary(libFile);
}
__name(loadLibData, "loadLibData");
function getExports() {
if (flags2.loadAsync) {
return loadLibData().then((libData) => loadWebAssemblyModule(libData, flags2, libName2, localScope2, handle2));
}
return loadWebAssemblyModule(loadLibData(), flags2, libName2, localScope2, handle2);
}
__name(getExports, "getExports");
function moduleLoaded(exports) {
if (dso.global) {
mergeLibSymbols(exports, libName2);
} else if (localScope2) {
Object.assign(localScope2, exports);
}
dso.exports = exports;
}
__name(moduleLoaded, "moduleLoaded");
if (flags2.loadAsync) {
return getExports().then((exports) => {
moduleLoaded(exports);
return true;
});
}
moduleLoaded(getExports());
return true;
}
__name(loadDynamicLibrary, "loadDynamicLibrary");
var reportUndefinedSymbols = /* @__PURE__ */ __name(() => {
for (var [symName, entry] of Object.entries(GOT)) {
if (entry.value == 0) {
var value = resolveGlobalSymbol(symName, true).sym;
if (!value && !entry.required) {
continue;
}
if (typeof value == "function") {
entry.value = addFunction(value, value.sig);
} else if (typeof value == "number") {
entry.value = value;
} else {
throw new Error(`bad export type for '${symName}': ${typeof value}`);
}
}
}
}, "reportUndefinedSymbols");
var loadDylibs = /* @__PURE__ */ __name(() => {
if (!dynamicLibraries.length) {
reportUndefinedSymbols();
return;
}
addRunDependency("loadDylibs");
dynamicLibraries.reduce((chain, lib) => chain.then(() => loadDynamicLibrary(lib, {
loadAsync: true,
global: true,
nodelete: true,
allowUndefined: true
})), Promise.resolve()).then(() => {
reportUndefinedSymbols();
removeRunDependency("loadDylibs");
});
}, "loadDylibs");
var noExitRuntime = Module["noExitRuntime"] || true;
function setValue(ptr, value, type = "i8") {
if (type.endsWith("*")) type = "*";
switch (type) {
case "i1":
HEAP8[ptr] = value;
break;
case "i8":
HEAP8[ptr] = value;
break;
case "i16":
LE_HEAP_STORE_I16((ptr >> 1) * 2, value);
break;
case "i32":
LE_HEAP_STORE_I32((ptr >> 2) * 4, value);
break;
case "i64":
HEAP64[ptr >> 3] = BigInt(value);
break;
case "float":
LE_HEAP_STORE_F32((ptr >> 2) * 4, value);
break;
case "double":
LE_HEAP_STORE_F64((ptr >> 3) * 8, value);
break;
case "*":
LE_HEAP_STORE_U32((ptr >> 2) * 4, value);
break;
default:
abort(`invalid type for setValue: ${type}`);
}
}
__name(setValue, "setValue");
var ___memory_base = new WebAssembly.Global({
"value": "i32",
"mutable": false
}, 1024);
var ___stack_pointer = new WebAssembly.Global({
"value": "i32",
"mutable": true
}, 78224);
var ___table_base = new WebAssembly.Global({
"value": "i32",
"mutable": false
}, 1);
var __abort_js = /* @__PURE__ */ __name(() => abort(""), "__abort_js");
__abort_js.sig = "v";
var _emscripten_get_now = /* @__PURE__ */ __name(() => performance.now(), "_emscripten_get_now");
_emscripten_get_now.sig = "d";
var _emscripten_date_now = /* @__PURE__ */ __name(() => Date.now(), "_emscripten_date_now");
_emscripten_date_now.sig = "d";
var nowIsMonotonic = 1;
var checkWasiClock = /* @__PURE__ */ __name((clock_id) => clock_id >= 0 && clock_id <= 3, "checkWasiClock");
var INT53_MAX = 9007199254740992;
var INT53_MIN = -9007199254740992;
var bigintToI53Checked = /* @__PURE__ */ __name((num) => num < INT53_MIN || num > INT53_MAX ? NaN : Number(num), "bigintToI53Checked");
function _clock_time_get(clk_id, ignored_precision, ptime) {
ignored_precision = bigintToI53Checked(ignored_precision);
if (!checkWasiClock(clk_id)) {
return 28;
}
var now;
if (clk_id === 0) {
now = _emscripten_date_now();
} else if (nowIsMonotonic) {
now = _emscripten_get_now();
} else {
return 52;
}
var nsec = Math.round(now * 1e3 * 1e3);
HEAP64[ptime >> 3] = BigInt(nsec);
return 0;
}
__name(_clock_time_get, "_clock_time_get");
_clock_time_get.sig = "iijp";
var getHeapMax = /* @__PURE__ */ __name(() => (
// Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
// full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
// for any code that deals with heap sizes, which would require special
// casing all heap size related code to treat 0 specially.
2147483648
), "getHeapMax");
var growMemory = /* @__PURE__ */ __name((size) => {
var b = wasmMemory.buffer;
var pages = (size - b.byteLength + 65535) / 65536 | 0;
try {
wasmMemory.grow(pages);
updateMemoryViews();
return 1;
} catch (e) {
}
}, "growMemory");
var _emscripten_resize_heap = /* @__PURE__ */ __name((requestedSize) => {
var oldSize = HEAPU8.length;
requestedSize >>>= 0;
var maxHeapSize = getHeapMax();
if (requestedSize > maxHeapSize) {
return false;
}
for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
var replacement = growMemory(newSize);
if (replacement) {
return true;
}
}
return false;
}, "_emscripten_resize_heap");
_emscripten_resize_heap.sig = "ip";
var _fd_close = /* @__PURE__ */ __name((fd) => 52, "_fd_close");
_fd_close.sig = "ii";
function _fd_seek(fd, offset, whence, newOffset) {
offset = bigintToI53Checked(offset);
return 70;
}
__name(_fd_seek, "_fd_seek");
_fd_seek.sig = "iijip";
var printCharBuffers = [null, [], []];
var printChar = /* @__PURE__ */ __name((stream, curr) => {
var buffer = printCharBuffers[stream];
if (curr === 0 || curr === 10) {
(stream === 1 ? out : err)(UTF8ArrayToString(buffer));
buffer.length = 0;
} else {
buffer.push(curr);
}
}, "printChar");
var flush_NO_FILESYSTEM = /* @__PURE__ */ __name(() => {
if (printCharBuffers[1].length) printChar(1, 10);
if (printCharBuffers[2].length) printChar(2, 10);
}, "flush_NO_FILESYSTEM");
var SYSCALLS = {
varargs: void 0,
getStr(ptr) {
var ret = UTF8ToString(ptr);
return ret;
}
};
var _fd_write = /* @__PURE__ */ __name((fd, iov, iovcnt, pnum) => {
var num = 0;
for (var i2 = 0; i2 < iovcnt; i2++) {
var ptr = LE_HEAP_LOAD_U32((iov >> 2) * 4);
var len = LE_HEAP_LOAD_U32((iov + 4 >> 2) * 4);
iov += 8;
for (var j = 0; j < len; j++) {
printChar(fd, HEAPU8[ptr + j]);
}
num += len;
}
LE_HEAP_STORE_U32((pnum >> 2) * 4, num);
return 0;
}, "_fd_write");
_fd_write.sig = "iippp";
function _tree_sitter_log_callback(isLexMessage, messageAddress) {
if (Module.currentLogCallback) {
const message = UTF8ToString(messageAddress);
Module.currentLogCallback(message, isLexMessage !== 0);
}
}
__name(_tree_sitter_log_callback, "_tree_sitter_log_callback");
function _tree_sitter_parse_callback(inputBufferAddress, index, row, column, lengthAddress) {
const INPUT_BUFFER_SIZE = 10 * 1024;
const string = Module.currentParseCallback(index, {
row,
column
});
if (typeof string === "string") {
setValue(lengthAddress, string.length, "i32");
stringToUTF16(string, inputBufferAddress, INPUT_BUFFER_SIZE);
} else {
setValue(lengthAddress, 0, "i32");
}
}
__name(_tree_sitter_parse_callback, "_tree_sitter_parse_callback");
function _tree_sitter_progress_callback(currentOffset, hasError) {
if (Module.currentProgressCallback) {
return Module.currentProgressCallback({
currentOffset,
hasError
});
}
return false;
}
__name(_tree_sitter_progress_callback, "_tree_sitter_progress_callback");
function _tree_sitter_query_progress_callback(currentOffset) {
if (Module.currentQueryProgressCallback) {
return Module.currentQueryProgressCallback({
currentOffset
});
}
return false;
}
__name(_tree_sitter_query_progress_callback, "_tree_sitter_query_progress_callback");
var runtimeKeepaliveCounter = 0;
var keepRuntimeAlive = /* @__PURE__ */ __name(() => noExitRuntime || runtimeKeepaliveCounter > 0, "keepRuntimeAlive");
var _proc_exit = /* @__PURE__ */ __name((code) => {
EXITSTATUS = code;
if (!keepRuntimeAlive()) {
Module["onExit"]?.(code);
ABORT = true;
}
quit_(code, new ExitStatus(code));
}, "_proc_exit");
_proc_exit.sig = "vi";
var exitJS = /* @__PURE__ */ __name((status, implicit) => {
EXITSTATUS = status;
_proc_exit(status);
}, "exitJS");
var handleException = /* @__PURE__ */ __name((e) => {
if (e instanceof ExitStatus || e == "unwind") {
return EXITSTATUS;
}
quit_(1, e);
}, "handleException");
var lengthBytesUTF8 = /* @__PURE__ */ __name((str) => {
var len = 0;
for (var i2 = 0; i2 < str.length; ++i2) {
var c = str.charCodeAt(i2);
if (c <= 127) {
len++;
} else if (c <= 2047) {
len += 2;
} else if (c >= 55296 && c <= 57343) {
len += 4;
++i2;
} else {
len += 3;
}
}
return len;
}, "lengthBytesUTF8");
var stringToUTF8Array = /* @__PURE__ */ __name((str, heap, outIdx, maxBytesToWrite) => {
if (!(maxBytesToWrite > 0)) return 0;
var startIdx = outIdx;
var endIdx = outIdx + maxBytesToWrite - 1;
for (var i2 = 0; i2 < str.length; ++i2) {
var u = str.charCodeAt(i2);
if (u >= 55296 && u <= 57343) {
var u1 = str.charCodeAt(++i2);
u = 65536 + ((u & 1023) << 10) | u1 & 1023;
}
if (u <= 127) {
if (outIdx >= endIdx) break;
heap[outIdx++] = u;
} else if (u <= 2047) {
if (outIdx + 1 >= endIdx) break;
heap[outIdx++] = 192 | u >> 6;
heap[outIdx++] = 128 | u & 63;
} else if (u <= 65535) {
if (outIdx + 2 >= endIdx) break;
heap[outIdx++] = 224 | u >> 12;
heap[outIdx++] = 128 | u >> 6 & 63;
heap[outIdx++] = 128 | u & 63;
} else {
if (outIdx + 3 >= endIdx) break;
heap[outIdx++] = 240 | u >> 18;
heap[outIdx++] = 128 | u >> 12 & 63;
heap[outIdx++] = 128 | u >> 6 & 63;
heap[outIdx++] = 128 | u & 63;
}
}
heap[outIdx] = 0;
return outIdx - startIdx;
}, "stringToUTF8Array");
var stringToUTF8 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite), "stringToUTF8");
var stackAlloc = /* @__PURE__ */ __name((sz) => __emscripten_stack_alloc(sz), "stackAlloc");
var stringToUTF8OnStack = /* @__PURE__ */ __name((str) => {
var size = lengthBytesUTF8(str) + 1;
var ret = stackAlloc(size);
stringToUTF8(str, ret, size);
return ret;
}, "stringToUTF8OnStack");
var AsciiToString = /* @__PURE__ */ __name((ptr) => {
var str = "";
while (1) {
var ch = HEAPU8[ptr++];
if (!ch) return str;
str += String.fromCharCode(ch);
}
}, "AsciiToString");
var stringToUTF16 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite) => {
maxBytesToWrite ??= 2147483647;
if (maxBytesToWrite < 2) return 0;
maxBytesToWrite -= 2;
var startPtr = outPtr;
var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
for (var i2 = 0; i2 < numCharsToWrite; ++i2) {
var codeUnit = str.charCodeAt(i2);
LE_HEAP_STORE_I16((outPtr >> 1) * 2, codeUnit);
outPtr += 2;
}
LE_HEAP_STORE_I16((outPtr >> 1) * 2, 0);
return outPtr - startPtr;
}, "stringToUTF16");
var wasmImports = {
/** @export */
__heap_base: ___heap_base,
/** @export */
__indirect_function_table: wasmTable,
/** @export */
__memory_base: ___memory_base,
/** @export */
__stack_pointer: ___stack_pointer,
/** @export */
__table_base: ___table_base,
/** @export */
_abort_js: __abort_js,
/** @export */
clock_time_get: _clock_time_get,
/** @export */
emscripten_resize_heap: _emscripten_resize_heap,
/** @export */
fd_close: _fd_close,
/** @export */
fd_seek: _fd_seek,
/** @export */
fd_write: _fd_write,
/** @export */
memory: wasmMemory,
/** @export */
tree_sitter_log_callback: _tree_sitter_log_callback,
/** @export */
tree_sitter_parse_callback: _tree_sitter_parse_callback,
/** @export */
tree_sitter_progress_callback: _tree_sitter_progress_callback,
/** @export */
tree_sitter_query_progress_callback: _tree_sitter_query_progress_callback
};
var wasmExports = await createWasm();
var ___wasm_call_ctors = wasmExports["__wasm_call_ctors"];
var _malloc = Module["_malloc"] = wasmExports["malloc"];
var _calloc = Module["_calloc"] = wasmExports["calloc"];
var _realloc = Module["_realloc"] = wasmExports["realloc"];
var _free = Module["_free"] = wasmExports["free"];
var _memcmp = Module["_memcmp"] = wasmExports["memcmp"];
var _ts_language_symbol_count = Module["_ts_language_symbol_count"] = wasmExports["ts_language_symbol_count"];
var _ts_language_state_count = Module["_ts_language_state_count"] = wasmExports["ts_language_state_count"];
var _ts_language_version = Module["_ts_language_version"] = wasmExports["ts_language_version"];
var _ts_language_abi_version = Module["_ts_language_abi_version"] = wasmExports["ts_language_abi_version"];
var _ts_language_metadata = Module["_ts_language_metadata"] = wasmExports["ts_language_metadata"];
var _ts_language_name = Module["_ts_language_name"] = wasmExports["ts_language_name"];
var _ts_language_field_count = Module["_ts_language_field_count"] = wasmExports["ts_language_field_count"];
var _ts_language_next_state = Module["_ts_language_next_state"] = wasmExports["ts_language_next_state"];
var _ts_language_symbol_name = Module["_ts_language_symbol_name"] = wasmExports["ts_language_symbol_name"];
var _ts_language_symbol_for_name = Module["_ts_language_symbol_for_name"] = wasmExports["ts_language_symbol_for_name"];
var _strncmp = Module["_strncmp"] = wasmExports["strncmp"];
var _ts_language_symbol_type = Module["_ts_language_symbol_type"] = wasmExports["ts_language_symbol_type"];
var _ts_language_field_name_for_id = Module["_ts_language_field_name_for_id"] = wasmExports["ts_language_field_name_for_id"];
var _ts_lookahead_iterator_new = Module["_ts_lookahead_iterator_new"] = wasmExports["ts_lookahead_iterator_new"];
var _ts_lookahead_iterator_delete = Module["_ts_lookahead_iterator_delete"] = wasmExports["ts_lookahead_iterator_delete"];
var _ts_lookahead_iterator_reset_state = Module["_ts_lookahead_iterator_reset_state"] = wasmExports["ts_lookahead_iterator_reset_state"];
var _ts_lookahead_iterator_reset = Module["_ts_lookahead_iterator_reset"] = wasmExports["ts_lookahead_iterator_reset"];
var _ts_lookahead_iterator_next = Module["_ts_lookahead_iterator_next"] = wasmExports["ts_lookahead_iterator_next"];
var _ts_lookahead_iterator_current_symbol = Module["_ts_lookahead_iterator_current_symbol"] = wasmExports["ts_lookahead_iterator_current_symbol"];
var _ts_parser_delete = Module["_ts_parser_delete"] = wasmExports["ts_parser_delete"];
var _ts_parser_reset = Module["_ts_parser_reset"] = wasmExports["ts_parser_reset"];
var _ts_parser_set_language = Module["_ts_parser_set_language"] = wasmExports["ts_parser_set_language"];
var _ts_parser_timeout_micros = Module["_ts_parser_timeout_micros"] = wasmExports["ts_parser_timeout_micros"];
var _ts_parser_set_timeout_micros = Module["_ts_parser_set_timeout_micros"] = wasmExports["ts_parser_set_timeout_micros"];
var _ts_parser_set_included_ranges = Module["_ts_parser_set_included_ranges"] = wasmExports["ts_parser_set_included_ranges"];
var _ts_query_new = Module["_ts_query_new"] = wasmExports["ts_query_new"];
var _ts_query_delete = Module["_ts_query_delete"] = wasmExports["ts_query_delete"];
var _iswspace = Module["_iswspace"] = wasmExports["iswspace"];
var _iswalnum = Module["_iswalnum"] = wasmExports["iswalnum"];
var _ts_query_pattern_count = Module["_ts_query_pattern_count"] = wasmExports["ts_query_pattern_count"];
var _ts_query_capture_count = Module["_ts_query_capture_count"] = wasmExports["ts_query_capture_count"];
var _ts_query_string_count = Module["_ts_query_string_count"] = wasmExports["ts_query_string_count"];
var _ts_query_capture_name_for_id = Module["_ts_query_capture_name_for_id"] = wasmExports["ts_query_capture_name_for_id"];
var _ts_query_capture_quantifier_for_id = Module["_ts_query_capture_quantifier_for_id"] = wasmExports["ts_query_capture_quantifier_for_id"];
var _ts_query_string_value_for_id = Module["_ts_query_string_value_for_id"] = wasmExports["ts_query_string_value_for_id"];
var _ts_query_predicates_for_pattern = Module["_ts_query_predicates_for_pattern"] = wasmExports["ts_query_predicates_for_pattern"];
var _ts_query_start_byte_for_pattern = Module["_ts_query_start_byte_for_pattern"] = wasmExports["ts_query_start_byte_for_pattern"];
var _ts_query_end_byte_for_pattern = Module["_ts_query_end_byte_for_pattern"] = wasmExports["ts_query_end_byte_for_pattern"];
var _ts_query_is_pattern_rooted = Module["_ts_query_is_pattern_rooted"] = wasmExports["ts_query_is_pattern_rooted"];
var _ts_query_is_pattern_non_local = Module["_ts_query_is_pattern_non_local"] = wasmExports["ts_query_is_pattern_non_local"];
var _ts_query_is_pattern_guaranteed_at_step = Module["_ts_query_is_pattern_guaranteed_at_step"] = wasmExports["ts_query_is_pattern_guaranteed_at_step"];
var _ts_query_disable_capture = Module["_ts_query_disable_capture"] = wasmExports["ts_query_disable_capture"];
var _ts_query_disable_pattern = Module["_ts_query_disable_pattern"] = wasmExports["ts_query_disable_pattern"];
var _ts_tree_copy = Module["_ts_tree_copy"] = wasmExports["ts_tree_copy"];
var _ts_tree_delete = Module["_ts_tree_delete"] = wasmExports["ts_tree_delete"];
var _ts_init = Module["_ts_init"] = wasmExports["ts_init"];
var _ts_parser_new_wasm = Module["_ts_parser_new_wasm"] = wasmExports["ts_parser_new_wasm"];
var _ts_parser_enable_logger_wasm = Module["_ts_parser_enable_logger_wasm"] = wasmExports["ts_parser_enable_logger_wasm"];
var _ts_parser_parse_wasm = Module["_ts_parser_parse_wasm"] = wasmExports["ts_parser_parse_wasm"];
var _ts_parser_included_ranges_wasm = Module["_ts_parser_included_ranges_wasm"] = wasmExports["ts_parser_included_ranges_wasm"];
var _ts_language_type_is_named_wasm = Module["_ts_language_type_is_named_wasm"] = wasmExports["ts_language_type_is_named_wasm"];
var _ts_language_type_is_visible_wasm = Module["_ts_language_type_is_visible_wasm"] = wasmExports["ts_language_type_is_visible_wasm"];
var _ts_language_supertypes_wasm = Module["_ts_language_supertypes_wasm"] = wasmExports["ts_language_supertypes_wasm"];
var _ts_language_subtypes_wasm = Module["_ts_language_subtypes_wasm"] = wasmExports["ts_language_subtypes_wasm"];
var _ts_tree_root_node_wasm = Module["_ts_tree_root_node_wasm"] = wasmExports["ts_tree_root_node_wasm"];
var _ts_tree_root_node_with_offset_wasm = Module["_ts_tree_root_node_with_offset_wasm"] = wasmExports["ts_tree_root_node_with_offset_wasm"];
var _ts_tree_edit_wasm = Module["_ts_tree_edit_wasm"] = wasmExports["ts_tree_edit_wasm"];
var _ts_tree_included_ranges_wasm = Module["_ts_tree_included_ranges_wasm"] = wasmExports["ts_tree_included_ranges_wasm"];
var _ts_tree_get_changed_ranges_wasm = Module["_ts_tree_get_changed_ranges_wasm"] = wasmExports["ts_tree_get_changed_ranges_wasm"];
var _ts_tree_cursor_new_wasm = Module["_ts_tree_cursor_new_wasm"] = wasmExports["ts_tree_cursor_new_wasm"];
var _ts_tree_cursor_copy_wasm = Module["_ts_tree_cursor_copy_wasm"] = wasmExports["ts_tree_cursor_copy_wasm"];
var _ts_tree_cursor_delete_wasm = Module["_ts_tree_cursor_delete_wasm"] = wasmExports["ts_tree_cursor_delete_wasm"];
var _ts_tree_cursor_reset_wasm = Module["_ts_tree_cursor_reset_wasm"] = wasmExports["ts_tree_cursor_reset_wasm"];
var _ts_tree_cursor_reset_to_wasm = Module["_ts_tree_cursor_reset_to_wasm"] = wasmExports["ts_tree_cursor_reset_to_wasm"];
var _ts_tree_cursor_goto_first_child_wasm = Module["_ts_tree_cursor_goto_first_child_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_wasm"];
var _ts_tree_cursor_goto_last_child_wasm = Module["_ts_tree_cursor_goto_last_child_wasm"] = wasmExports["ts_tree_cursor_goto_last_child_wasm"];
var _ts_tree_cursor_goto_first_child_for_index_wasm = Module["_ts_tree_cursor_goto_first_child_for_index_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_for_index_wasm"];
var _ts_tree_cursor_goto_first_child_for_position_wasm = Module["_ts_tree_cursor_goto_first_child_for_position_wasm"] = wasmExports["ts_tree_cursor_goto_first_child_for_position_wasm"];
var _ts_tree_cursor_goto_next_sibling_wasm = Module["_ts_tree_cursor_goto_next_sibling_wasm"] = wasmExports["ts_tree_cursor_goto_next_sibling_wasm"];
var _ts_tree_cursor_goto_previous_sibling_wasm = Module["_ts_tree_cursor_goto_previous_sibling_wasm"] = wasmExports["ts_tree_cursor_goto_previous_sibling_wasm"];
var _ts_tree_cursor_goto_descendant_wasm = Module["_ts_tree_cursor_goto_descendant_wasm"] = wasmExports["ts_tree_cursor_goto_descendant_wasm"];
var _ts_tree_cursor_goto_parent_wasm = Module["_ts_tree_cursor_goto_parent_wasm"] = wasmExports["ts_tree_cursor_goto_parent_wasm"];
var _ts_tree_cursor_current_node_type_id_wasm = Module["_ts_tree_cursor_current_node_type_id_wasm"] = wasmExports["ts_tree_cursor_current_node_type_id_wasm"];
var _ts_tree_cursor_current_node_state_id_wasm = Module["_ts_tree_cursor_current_node_state_id_wasm"] = wasmExports["ts_tree_cursor_current_node_state_id_wasm"];
var _ts_tree_cursor_current_node_is_named_wasm = Module["_ts_tree_cursor_current_node_is_named_wasm"] = wasmExports["ts_tree_cursor_current_node_is_named_wasm"];
var _ts_tree_cursor_current_node_is_missing_wasm = Module["_ts_tree_cursor_current_node_is_missing_wasm"] = wasmExports["ts_tree_cursor_current_node_is_missing_wasm"];
var _ts_tree_cursor_current_node_id_wasm = Module["_ts_tree_cursor_current_node_id_wasm"] = wasmExports["ts_tree_cursor_current_node_id_wasm"];
var _ts_tree_cursor_start_position_wasm = Module["_ts_tree_cursor_start_position_wasm"] = wasmExports["ts_tree_cursor_start_position_wasm"];
var _ts_tree_cursor_end_position_wasm = Module["_ts_tree_cursor_end_position_wasm"] = wasmExports["ts_tree_cursor_end_position_wasm"];
var _ts_tree_cursor_start_index_wasm = Module["_ts_tree_cursor_start_index_wasm"] = wasmExports["ts_tree_cursor_start_index_wasm"];
var _ts_tree_cursor_end_index_wasm = Module["_ts_tree_cursor_end_index_wasm"] = wasmExports["ts_tree_cursor_end_index_wasm"];
var _ts_tree_cursor_current_field_id_wasm = Module["_ts_tree_cursor_current_field_id_wasm"] = wasmExports["ts_tree_cursor_current_field_id_wasm"];
var _ts_tree_cursor_current_depth_wasm = Module["_ts_tree_cursor_current_depth_wasm"] = wasmExports["ts_tree_cursor_current_depth_wasm"];
var _ts_tree_cursor_current_descendant_index_wasm = Module["_ts_tree_cursor_current_descendant_index_wasm"] = wasmExports["ts_tree_cursor_current_descendant_index_wasm"];
var _ts_tree_cursor_current_node_wasm = Module["_ts_tree_cursor_current_node_wasm"] = wasmExports["ts_tree_cursor_current_node_wasm"];
var _ts_node_symbol_wasm = Module["_ts_node_symbol_wasm"] = wasmExports["ts_node_symbol_wasm"];
var _ts_node_field_name_for_child_wasm = Module["_ts_node_field_name_for_child_wasm"] = wasmExports["ts_node_field_name_for_child_wasm"];
var _ts_node_field_name_for_named_child_wasm = Module["_ts_node_field_name_for_named_child_wasm"] = wasmExports["ts_node_field_name_for_named_child_wasm"];
var _ts_node_children_by_field_id_wasm = Module["_ts_node_children_by_field_id_wasm"] = wasmExports["ts_node_children_by_field_id_wasm"];
var _ts_node_first_child_for_byte_wasm = Module["_ts_node_first_child_for_byte_wasm"] = wasmExports["ts_node_first_child_for_byte_wasm"];
var _ts_node_first_named_child_for_byte_wasm = Module["_ts_node_first_named_child_for_byte_wasm"] = wasmExports["ts_node_first_named_child_for_byte_wasm"];
var _ts_node_grammar_symbol_wasm = Module["_ts_node_grammar_symbol_wasm"] = wasmExports["ts_node_grammar_symbol_wasm"];
var _ts_node_child_count_wasm = Module["_ts_node_child_count_wasm"] = wasmExports["ts_node_child_count_wasm"];
var _ts_node_named_child_count_wasm = Module["_ts_node_named_child_count_wasm"] = wasmExports["ts_node_named_child_count_wasm"];
var _ts_node_child_wasm = Module["_ts_node_child_wasm"] = wasmExports["ts_node_child_wasm"];
var _ts_node_named_child_wasm = Module["_ts_node_named_child_wasm"] = wasmExports["ts_node_named_child_wasm"];
var _ts_node_child_by_field_id_wasm = Module["_ts_node_child_by_field_id_wasm"] = wasmExports["ts_node_child_by_field_id_wasm"];
var _ts_node_next_sibling_wasm = Module["_ts_node_next_sibling_wasm"] = wasmExports["ts_node_next_sibling_wasm"];
var _ts_node_prev_sibling_wasm = Module["_ts_node_prev_sibling_wasm"] = wasmExports["ts_node_prev_sibling_wasm"];
var _ts_node_next_named_sibling_wasm = Module["_ts_node_next_named_sibling_wasm"] = wasmExports["ts_node_next_named_sibling_wasm"];
var _ts_node_prev_named_sibling_wasm = Module["_ts_node_prev_named_sibling_wasm"] = wasmExports["ts_node_prev_named_sibling_wasm"];
var _ts_node_descendant_count_wasm = Module["_ts_node_descendant_count_wasm"] = wasmExports["ts_node_descendant_count_wasm"];
var _ts_node_parent_wasm = Module["_ts_node_parent_wasm"] = wasmExports["ts_node_parent_wasm"];
var _ts_node_child_with_descendant_wasm = Module["_ts_node_child_with_descendant_wasm"] = wasmExports["ts_node_child_with_descendant_wasm"];
var _ts_node_descendant_for_index_wasm = Module["_ts_node_descendant_for_index_wasm"] = wasmExports["ts_node_descendant_for_index_wasm"];
var _ts_node_named_descendant_for_index_wasm = Module["_ts_node_named_descendant_for_index_wasm"] = wasmExports["ts_node_named_descendant_for_index_wasm"];
var _ts_node_descendant_for_position_wasm = Module["_ts_node_descendant_for_position_wasm"] = wasmExports["ts_node_descendant
gitextract_sr4e69ap/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ ├── ci.yaml │ └── publish.yml ├── .gitignore ├── CMakeLists.txt ├── Cargo.toml ├── LICENSE ├── Makefile ├── Package.swift ├── README.md ├── binding.gyp ├── bindings/ │ ├── c/ │ │ ├── tree-sitter-comment.pc.in │ │ └── tree_sitter/ │ │ └── tree-sitter-comment.h │ ├── go/ │ │ ├── binding.go │ │ └── binding_test.go │ ├── node/ │ │ ├── binding.cc │ │ ├── binding_test.js │ │ ├── index.d.ts │ │ └── index.js │ ├── python/ │ │ ├── tests/ │ │ │ └── test_binding.py │ │ └── tree_sitter_comment/ │ │ ├── __init__.py │ │ ├── __init__.pyi │ │ ├── binding.c │ │ └── py.typed │ ├── rust/ │ │ ├── build.rs │ │ └── lib.rs │ └── swift/ │ ├── TreeSitterComment/ │ │ └── comment.h │ └── TreeSitterCommentTests/ │ └── TreeSitterCommentTests.swift ├── compile_flags.txt ├── docs/ │ ├── .nojekyll │ ├── index.html │ └── js/ │ ├── playground.js │ └── tree-sitter.js ├── go.mod ├── grammar.js ├── package.json ├── pyproject.toml ├── setup.py ├── src/ │ ├── grammar.json │ ├── node-types.json │ ├── parser.c │ ├── scanner.c │ ├── tree_sitter/ │ │ ├── alloc.h │ │ ├── array.h │ │ └── parser.h │ └── tree_sitter_comment/ │ ├── chars.c │ ├── chars.h │ ├── parser.c │ ├── parser.h │ └── tokens.h ├── test/ │ └── corpus/ │ └── source.txt └── tree-sitter.json
SYMBOL INDEX (309 symbols across 23 files)
FILE: bindings/c/tree_sitter/tree-sitter-comment.h
type TSLanguage (line 4) | typedef struct TSLanguage TSLanguage;
FILE: bindings/go/binding.go
function Language (line 13) | func Language() unsafe.Pointer {
FILE: bindings/go/binding_test.go
function TestCanLoadGrammar (line 10) | func TestCanLoadGrammar(t *testing.T) {
FILE: bindings/node/binding.cc
type TSLanguage (line 3) | struct TSLanguage
function Init (line 12) | Napi::Object Init(Napi::Env env, Napi::Object exports) {
FILE: bindings/node/index.d.ts
type BaseNode (line 1) | type BaseNode = {
type ChildNode (line 6) | type ChildNode = {
type NodeInfo (line 12) | type NodeInfo =
type Language (line 21) | type Language = {
FILE: bindings/python/tests/test_binding.py
class TestLanguage (line 7) | class TestLanguage(TestCase):
method test_can_load_grammar (line 8) | def test_can_load_grammar(self):
FILE: bindings/python/tree_sitter_comment/__init__.py
function _get_query (line 8) | def _get_query(name, file):
function __getattr__ (line 14) | def __getattr__(name):
function __dir__ (line 38) | def __dir__():
FILE: bindings/python/tree_sitter_comment/__init__.pyi
function language (line 10) | def language() -> object: ...
FILE: bindings/python/tree_sitter_comment/binding.c
type TSLanguage (line 3) | typedef struct TSLanguage TSLanguage;
function PyObject (line 7) | static PyObject* _binding_language(PyObject *Py_UNUSED(self), PyObject *...
type PyModuleDef_Slot (line 11) | struct PyModuleDef_Slot
type PyModuleDef (line 24) | struct PyModuleDef
function PyMODINIT_FUNC (line 33) | PyMODINIT_FUNC PyInit__binding(void) {
FILE: bindings/rust/build.rs
function main (line 1) | fn main() {
FILE: bindings/rust/lib.rs
function tree_sitter_comment (line 24) | fn tree_sitter_comment() -> *const ();
constant LANGUAGE (line 30) | pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitt...
constant NODE_TYPES (line 35) | pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");
function test_can_load_grammar (line 47) | fn test_can_load_grammar() {
FILE: bindings/swift/TreeSitterComment/comment.h
type TSLanguage (line 4) | typedef struct TSLanguage TSLanguage;
FILE: docs/js/playground.js
function initializeLocalTheme (line 1) | function initializeLocalTheme() {
function initializeCustomSelect (line 21) | function initializeCustomSelect({ initialValue = null, addListeners = fa...
function handleLanguageChange (line 187) | async function handleLanguageChange() {
function handleCodeChange (line 210) | async function handleCodeChange(editor, changes) {
function renderTree (line 232) | async function renderTree() {
function getCaptureCSS (line 328) | function getCaptureCSS(name) {
function runTreeQuery (line 336) | function runTreeQuery(_, startRow, endRow) {
function handleQueryChange (line 387) | function handleQueryChange() {
function handleCursorMovement (line 448) | function handleCursorMovement() {
function handleTreeClick (line 499) | function handleTreeClick(event) {
function handleLoggingChange (line 512) | function handleLoggingChange() {
function handleQueryEnableChange (line 526) | function handleQueryEnableChange() {
function treeEditForEditorChange (line 537) | function treeEditForEditorChange(change) {
function colorForCaptureName (line 569) | function colorForCaptureName(capture) {
function loadState (line 579) | function loadState() {
function saveState (line 595) | function saveState() {
function saveQueryState (line 602) | function saveQueryState() {
function debounce (line 607) | function debounce(func, wait, immediate) {
FILE: docs/js/tree-sitter.js
function assertInternal (line 19) | function assertInternal(x) {
function isPoint (line 23) | function isPoint(point) {
function setModule (line 27) | function setModule(module2) {
method constructor (line 44) | constructor(internal, address, language) {
method currentTypeId (line 50) | get currentTypeId() {
method currentType (line 54) | get currentType() {
method delete (line 58) | delete() {
method reset (line 68) | reset(language, stateId) {
method resetState (line 81) | resetState(stateId) {
method [Symbol.iterator] (line 90) | [Symbol.iterator]() {
function getText (line 103) | function getText(tree, startIndex, endIndex, startPosition) {
method constructor (line 136) | constructor(internal, address, language, textCallback) {
method copy (line 143) | copy() {
method delete (line 148) | delete() {
method rootNode (line 153) | get rootNode() {
method rootNodeWithOffset (line 161) | rootNodeWithOffset(offsetBytes, offsetExtent) {
method edit (line 175) | edit(edit) {
method walk (line 180) | walk() {
method getChangedRanges (line 194) | getChangedRanges(other) {
method getIncludedRanges (line 213) | getIncludedRanges() {
method constructor (line 250) | constructor(internal, tree) {
method copy (line 256) | copy() {
method delete (line 263) | delete() {
method currentNode (line 269) | get currentNode() {
method currentFieldId (line 279) | get currentFieldId() {
method currentFieldName (line 284) | get currentFieldName() {
method currentDepth (line 291) | get currentDepth() {
method currentDescendantIndex (line 299) | get currentDescendantIndex() {
method nodeType (line 304) | get nodeType() {
method nodeTypeId (line 308) | get nodeTypeId() {
method nodeStateId (line 313) | get nodeStateId() {
method nodeId (line 318) | get nodeId() {
method nodeIsNamed (line 328) | get nodeIsNamed() {
method nodeIsMissing (line 338) | get nodeIsMissing() {
method nodeText (line 343) | get nodeText() {
method startPosition (line 352) | get startPosition() {
method endPosition (line 358) | get endPosition() {
method startIndex (line 364) | get startIndex() {
method endIndex (line 369) | get endIndex() {
method gotoFirstChild (line 379) | gotoFirstChild() {
method gotoLastChild (line 395) | gotoLastChild() {
method gotoParent (line 411) | gotoParent() {
method gotoNextSibling (line 426) | gotoNextSibling() {
method gotoPreviousSibling (line 445) | gotoPreviousSibling() {
method gotoDescendant (line 456) | gotoDescendant(goalDescendantIndex) {
method gotoFirstChildForIndex (line 468) | gotoFirstChildForIndex(goalIndex) {
method gotoFirstChildForPosition (line 482) | gotoFirstChildForPosition(goalPosition) {
method reset (line 493) | reset(node) {
method resetTo (line 505) | resetTo(cursor) {
method constructor (line 526) | constructor(internal, {
method typeId (line 560) | get typeId() {
method grammarId (line 568) | get grammarId() {
method type (line 573) | get type() {
method grammarType (line 580) | get grammarType() {
method isNamed (line 589) | get isNamed() {
method isExtra (line 599) | get isExtra() {
method isError (line 609) | get isError() {
method isMissing (line 619) | get isMissing() {
method hasChanges (line 624) | get hasChanges() {
method hasError (line 632) | get hasError() {
method endIndex (line 637) | get endIndex() {
method endPosition (line 642) | get endPosition() {
method text (line 648) | get text() {
method parseState (line 652) | get parseState() {
method nextParseState (line 657) | get nextParseState() {
method equals (line 662) | equals(other) {
method child (line 672) | child(index) {
method namedChild (line 685) | namedChild(index) {
method childForFieldId (line 696) | childForFieldId(fieldId) {
method childForFieldName (line 707) | childForFieldName(fieldName) {
method fieldNameForChild (line 713) | fieldNameForChild(index) {
method fieldNameForNamedChild (line 720) | fieldNameForNamedChild(index) {
method childrenForFieldName (line 731) | childrenForFieldName(fieldName) {
method childrenForFieldId (line 741) | childrenForFieldId(fieldId) {
method firstChildForIndex (line 758) | firstChildForIndex(index) {
method firstNamedChildForIndex (line 766) | firstNamedChildForIndex(index) {
method childCount (line 774) | get childCount() {
method namedChildCount (line 783) | get namedChildCount() {
method firstChild (line 788) | get firstChild() {
method firstNamedChild (line 796) | get firstNamedChild() {
method lastChild (line 800) | get lastChild() {
method lastNamedChild (line 808) | get lastNamedChild() {
method children (line 817) | get children() {
method namedChildren (line 840) | get namedChildren() {
method descendantsOfType (line 865) | descendantsOfType(types, startPosition = ZERO_POINT, endPosition = ZERO_...
method nextSibling (line 908) | get nextSibling() {
method previousSibling (line 914) | get previousSibling() {
method nextNamedSibling (line 924) | get nextNamedSibling() {
method previousNamedSibling (line 934) | get previousNamedSibling() {
method descendantCount (line 940) | get descendantCount() {
method parent (line 948) | get parent() {
method childWithDescendant (line 958) | childWithDescendant(descendant) {
method descendantForIndex (line 965) | descendantForIndex(start2, end = start2) {
method namedDescendantForIndex (line 977) | namedDescendantForIndex(start2, end = start2) {
method descendantForPosition (line 989) | descendantForPosition(start2, end = start2) {
method namedDescendantForPosition (line 1001) | namedDescendantForPosition(start2, end = start2) {
method walk (line 1018) | walk() {
method edit (line 1032) | edit(edit) {
method toString (line 1060) | toString() {
function unmarshalCaptures (line 1070) | function unmarshalCaptures(query, tree, address, patternIndex, result) {
function marshalNode (line 1081) | function marshalNode(node) {
function unmarshalNode (line 1094) | function unmarshalNode(tree, address = TRANSFER_BUFFER) {
function marshalTreeCursor (line 1115) | function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
function unmarshalTreeCursor (line 1122) | function unmarshalTreeCursor(cursor) {
function marshalPoint (line 1129) | function marshalPoint(address, point) {
function unmarshalPoint (line 1134) | function unmarshalPoint(address) {
function marshalRange (line 1142) | function marshalRange(address, range) {
function unmarshalRange (line 1153) | function unmarshalRange(address) {
function marshalEdit (line 1165) | function marshalEdit(edit, address = TRANSFER_BUFFER) {
function unmarshalLanguageMetadata (line 1180) | function unmarshalLanguageMetadata(address) {
method constructor (line 1212) | constructor(kind, info2, index, length) {
method formatMessage (line 1224) | static formatMessage(kind, info2) {
function parseAnyPredicate (line 1239) | function parseAnyPredicate(steps, index, operator, textPredicates) {
function parseMatchPredicate (line 1283) | function parseMatchPredicate(steps, index, operator, textPredicates) {
function parseAnyOfPredicate (line 1316) | function parseAnyOfPredicate(steps, index, operator, textPredicates) {
function parseIsPredicate (line 1346) | function parseIsPredicate(steps, index, operator, assertedProperties, re...
function parseSetDirective (line 1362) | function parseSetDirective(steps, index, setProperties) {
function parsePattern (line 1373) | function parsePattern(index, stepType, stepValueId, captureNames, string...
method constructor (line 1459) | constructor(language, source) {
method delete (line 1571) | delete() {
method matches (line 1587) | matches(node, options = {}) {
method captures (line 1664) | captures(node, options = {}) {
method predicatesForPattern (line 1732) | predicatesForPattern(patternIndex) {
method disableCapture (line 1741) | disableCapture(captureName) {
method disablePattern (line 1755) | disablePattern(patternIndex) {
method didExceedMatchLimit (line 1767) | didExceedMatchLimit() {
method startIndexForPattern (line 1771) | startIndexForPattern(patternIndex) {
method endIndexForPattern (line 1780) | endIndexForPattern(patternIndex) {
method patternCount (line 1789) | patternCount() {
method captureIndexForName (line 1793) | captureIndexForName(captureName) {
method isPatternRooted (line 1797) | isPatternRooted(patternIndex) {
method isPatternNonLocal (line 1801) | isPatternNonLocal(patternIndex) {
method isPatternGuaranteedAtStep (line 1810) | isPatternGuaranteedAtStep(byteIndex) {
method constructor (line 1835) | constructor(internal, address) {
method name (line 1857) | get name() {
method version (line 1866) | get version() {
method abiVersion (line 1872) | get abiVersion() {
method metadata (line 1880) | get metadata() {
method fieldCount (line 1890) | get fieldCount() {
method stateCount (line 1896) | get stateCount() {
method fieldIdForName (line 1902) | fieldIdForName(fieldName) {
method fieldNameForId (line 1909) | fieldNameForId(fieldId) {
method idForNodeType (line 1915) | idForNodeType(type, named) {
method nodeTypeCount (line 1926) | get nodeTypeCount() {
method nodeTypeForId (line 1932) | nodeTypeForId(typeId) {
method nodeTypeIsNamed (line 1941) | nodeTypeIsNamed(typeId) {
method nodeTypeIsVisible (line 1947) | nodeTypeIsVisible(typeId) {
method supertypes (line 1955) | get supertypes() {
method subtypes (line 1972) | subtypes(supertype) {
method nextState (line 1989) | nextState(stateId, typeId) {
method lookaheadIterator (line 2007) | lookaheadIterator(stateId) {
method query (line 2024) | query(source) {
method load (line 2032) | static async load(input) {
function locateFile (line 2096) | function locateFile(path) {
function assert (line 2194) | function assert(condition, text) {
function updateMemoryViews (line 2206) | function updateMemoryViews() {
function preRun (line 2242) | function preRun() {
function initRuntime (line 2252) | function initRuntime() {
function preMain (line 2258) | function preMain() {
function postRun (line 2262) | function postRun() {
function addOnPreRun (line 2272) | function addOnPreRun(cb) {
function addOnInit (line 2276) | function addOnInit(cb) {
function addOnPreMain (line 2280) | function addOnPreMain(cb) {
function addOnExit (line 2284) | function addOnExit(cb) {
function addOnPostRun (line 2287) | function addOnPostRun(cb) {
function getUniqueRunDependency (line 2293) | function getUniqueRunDependency(id) {
function addRunDependency (line 2297) | function addRunDependency(id) {
function removeRunDependency (line 2302) | function removeRunDependency(id) {
function abort (line 2314) | function abort(what) {
function findWasmBinary (line 2326) | function findWasmBinary() {
function getBinarySync (line 2337) | function getBinarySync(file) {
function getWasmBinary (line 2347) | async function getWasmBinary(binaryFile) {
function instantiateArrayBuffer (line 2358) | async function instantiateArrayBuffer(binaryFile, imports) {
function instantiateAsync (line 2369) | async function instantiateAsync(binary2, binaryFile, imports) {
function getWasmImports (line 2385) | function getWasmImports() {
function createWasm (line 2394) | async function createWasm() {
class ExitStatus (line 2437) | class ExitStatus {
method constructor (line 2442) | constructor(status) {
method get (line 2450) | get(obj, symName) {
function getU8 (line 2519) | function getU8() {
function getLEB (line 2523) | function getLEB() {
function getString (line 2535) | function getString() {
function failIf (line 2541) | function failIf(condition, message) {
function getValue (line 2629) | function getValue(ptr, type = "i8") {
method init (line 2669) | init() {
function loadModule (line 2934) | function loadModule() {
function loadDynamicLibrary (line 3106) | function loadDynamicLibrary(libName2, flags2 = {
function setValue (line 3211) | function setValue(ptr, value, type = "i8") {
function _clock_time_get (line 3266) | function _clock_time_get(clk_id, ignored_precision, ptime) {
function _fd_seek (line 3323) | function _fd_seek(fd, offset, whence, newOffset) {
method getStr (line 3345) | getStr(ptr) {
function _tree_sitter_log_callback (line 3365) | function _tree_sitter_log_callback(isLexMessage, messageAddress) {
function _tree_sitter_parse_callback (line 3372) | function _tree_sitter_parse_callback(inputBufferAddress, index, row, col...
function _tree_sitter_progress_callback (line 3386) | function _tree_sitter_progress_callback(currentOffset, hasError) {
function _tree_sitter_query_progress_callback (line 3396) | function _tree_sitter_query_progress_callback(currentOffset) {
function callMain (line 3702) | function callMain(args2 = []) {
function run (line 3727) | function run(args2 = arguments_) {
function initializeBinding (line 3775) | async function initializeBinding(moduleOptions) {
function checkModule (line 3782) | function checkModule() {
method init (line 3811) | static async init(moduleOptions) {
method constructor (line 3820) | constructor() {
method initialize (line 3824) | initialize() {
method delete (line 3833) | delete() {
method setLanguage (line 3848) | setLanguage(language) {
method parse (line 3884) | parse(callback, oldTree, options) {
method reset (line 3946) | reset() {
method getIncludedRanges (line 3950) | getIncludedRanges() {
method getTimeoutMicros (line 3972) | getTimeoutMicros() {
method setTimeoutMicros (line 3984) | setTimeoutMicros(timeout) {
method setLogger (line 3988) | setLogger(callback) {
method getLogger (line 3999) | getLogger() {
FILE: grammar.js
constant END_CHARS (line 10) | const END_CHARS = [
constant STOP_CHARS (line 27) | const STOP_CHARS = [
function get_uri_regex (line 105) | function get_uri_regex() {
function notmatching (line 115) | function notmatching(chars) {
function escapeRegExp (line 125) | function escapeRegExp(string) {
FILE: setup.py
class Build (line 30) | class Build(build):
method run (line 31) | def run(self):
class BdistWheel (line 38) | class BdistWheel(bdist_wheel):
method get_tag (line 39) | def get_tag(self):
class EggInfo (line 46) | class EggInfo(egg_info):
method find_sources (line 47) | def find_sources(self):
FILE: src/parser.c
type ts_symbol_identifiers (line 22) | enum ts_symbol_identifiers {
function ts_lex (line 315) | static bool ts_lex(TSLexer *lexer, TSStateId state) {
type ts_external_scanner_symbol_identifiers (line 900) | enum ts_external_scanner_symbol_identifiers {
function TS_PUBLIC (line 937) | TS_PUBLIC const TSLanguage *tree_sitter_comment(void) {
FILE: src/scanner.c
function tree_sitter_comment_external_scanner_destroy (line 11) | void tree_sitter_comment_external_scanner_destroy(void* payload)
function tree_sitter_comment_external_scanner_serialize (line 15) | unsigned tree_sitter_comment_external_scanner_serialize(
function tree_sitter_comment_external_scanner_deserialize (line 22) | void tree_sitter_comment_external_scanner_deserialize(
function tree_sitter_comment_external_scanner_scan (line 29) | bool tree_sitter_comment_external_scanner_scan(
FILE: src/tree_sitter/array.h
type Array (line 160) | typedef Array(void) Array;
function _array__delete (line 163) | static inline void _array__delete(Array *self) {
function _array__erase (line 173) | static inline void _array__erase(Array *self, size_t element_size,
function _array__reserve (line 183) | static inline void _array__reserve(Array *self, size_t element_size, uin...
function _array__assign (line 195) | static inline void _array__assign(Array *self, const Array *other, size_...
function _array__swap (line 202) | static inline void _array__swap(Array *self, Array *other) {
function _array__grow (line 209) | static inline void _array__grow(Array *self, uint32_t count, size_t elem...
function _array__splice (line 220) | static inline void _array__splice(Array *self, size_t element_size,
FILE: src/tree_sitter/parser.h
type TSStateId (line 17) | typedef uint16_t TSStateId;
type TSSymbol (line 18) | typedef uint16_t TSSymbol;
type TSFieldId (line 19) | typedef uint16_t TSFieldId;
type TSLanguage (line 20) | typedef struct TSLanguage TSLanguage;
type TSLanguageMetadata (line 21) | typedef struct TSLanguageMetadata TSLanguageMetadata;
type TSLanguageMetadata (line 22) | typedef struct TSLanguageMetadata {
type TSFieldMapEntry (line 29) | typedef struct {
type TSMapSlice (line 36) | typedef struct {
type TSSymbolMetadata (line 41) | typedef struct {
type TSLexer (line 47) | typedef struct TSLexer TSLexer;
type TSLexer (line 49) | struct TSLexer {
type TSParseActionType (line 60) | typedef enum {
type TSParseAction (line 67) | typedef union {
type TSLexMode (line 84) | typedef struct {
type TSLexerMode (line 89) | typedef struct {
type TSParseActionEntry (line 95) | typedef union {
type TSCharacterRange (line 103) | typedef struct {
type TSLanguage (line 108) | struct TSLanguage {
function set_contains (line 155) | static inline bool set_contains(const TSCharacterRange *ranges, uint32_t...
FILE: src/tree_sitter_comment/chars.c
function is_upper (line 3) | static bool is_upper(int32_t c)
function is_digit (line 10) | static bool is_digit(int32_t c)
function is_newline (line 17) | static bool is_newline(int32_t c)
function is_space (line 33) | static bool is_space(int32_t c)
function is_internal_char (line 53) | static bool is_internal_char(int32_t c)
FILE: src/tree_sitter_comment/parser.c
function parse_tagname (line 16) | static bool parse_tagname(TSLexer* lexer, const bool* valid_symbols)
function parse (line 84) | static bool parse(TSLexer* lexer, const bool* valid_symbols)
FILE: src/tree_sitter_comment/tokens.h
type TokenType (line 4) | enum TokenType {
Condensed preview — 54 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (296K chars).
[
{
"path": ".editorconfig",
"chars": 541,
"preview": "root = true\n\n[*]\ncharset = utf-8\n\n[*.{json,toml,yml,gyp}]\nindent_style = space\nindent_size = 2\n\n[*.js]\nindent_style = sp"
},
{
"path": ".gitattributes",
"chars": 941,
"preview": "* text=auto eol=lf\n\n# Generated source files\nsrc/*.json linguist-generated\nsrc/parser.c linguist-generated\nsrc/tree_sitt"
},
{
"path": ".github/FUNDING.yml",
"chars": 92,
"preview": "github: stsewd\ncustom:\n - https://paypal.me/stsewd\n - https://www.buymeacoffee.com/stsewd\n"
},
{
"path": ".github/workflows/ci.yaml",
"chars": 1235,
"preview": "name: CI\n\non:\n push:\n branches: [ master ]\n pull_request:\n branches: [ master ]\n\njobs:\n build:\n runs-on: ubu"
},
{
"path": ".github/workflows/publish.yml",
"chars": 727,
"preview": "name: Publish package\n\non:\n push:\n tags: [\"*\"]\n\nconcurrency:\n group: ${{github.workflow}}-${{github.ref}}\n cancel-"
},
{
"path": ".gitignore",
"chars": 403,
"preview": "/log.html\n\n# Rust artifacts\n/target\nbuild/\n\n# Node artifacts\nbuild/\nprebuilds/\nnode_modules/\n\n# Swift artifacts\n.build/\n"
},
{
"path": "CMakeLists.txt",
"chars": 2898,
"preview": "cmake_minimum_required(VERSION 3.13)\n\nproject(tree-sitter-comment\n VERSION \"0.3.0\"\n DESCRIPTION \"Grammar f"
},
{
"path": "Cargo.toml",
"chars": 776,
"preview": "[package]\nname = \"tree-sitter-comment\"\ndescription = \"Grammar for code tags like TODO:, FIXME(user): for the tree-sitter"
},
{
"path": "LICENSE",
"chars": 1072,
"preview": "MIT License\n\nCopyright (c) 2021 Santos Gallegos\n\nPermission is hereby granted, free of charge, to any person obtaining a"
},
{
"path": "Makefile",
"chars": 3780,
"preview": "ifeq ($(OS),Windows_NT)\n$(error Windows is not supported)\nendif\n\nLANGUAGE_NAME := tree-sitter-comment\nHOMEPAGE_URL := ht"
},
{
"path": "Package.swift",
"chars": 1097,
"preview": "// swift-tools-version:5.3\n\nimport Foundation\nimport PackageDescription\n\nvar sources = [\"src/parser.c\"]\nif FileManager.d"
},
{
"path": "README.md",
"chars": 3165,
"preview": "# tree-sitter-comment\n\n[](https://github.com/"
},
{
"path": "binding.gyp",
"chars": 766,
"preview": "{\n \"targets\": [\n {\n \"target_name\": \"tree_sitter_comment_binding\",\n \"dependencies\": [\n \"<!(node -p \\"
},
{
"path": "bindings/c/tree-sitter-comment.pc.in",
"chars": 299,
"preview": "prefix=@CMAKE_INSTALL_PREFIX@\nlibdir=${prefix}/@CMAKE_INSTALL_LIBDIR@\nincludedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@\n\nN"
},
{
"path": "bindings/c/tree_sitter/tree-sitter-comment.h",
"chars": 250,
"preview": "#ifndef TREE_SITTER_COMMENT_H_\n#define TREE_SITTER_COMMENT_H_\n\ntypedef struct TSLanguage TSLanguage;\n\n#ifdef __cplusplus"
},
{
"path": "bindings/go/binding.go",
"chars": 343,
"preview": "package tree_sitter_comment\n\n// #cgo CFLAGS: -std=c11 -fPIC\n// #include \"../../src/parser.c\"\n// #if __has_include(\"../.."
},
{
"path": "bindings/go/binding_test.go",
"chars": 364,
"preview": "package tree_sitter_comment_test\n\nimport (\n\t\"testing\"\n\n\ttree_sitter \"github.com/tree-sitter/go-tree-sitter\"\n\ttree_sitter"
},
{
"path": "bindings/node/binding.cc",
"chars": 532,
"preview": "#include <napi.h>\n\ntypedef struct TSLanguage TSLanguage;\n\nextern \"C\" TSLanguage *tree_sitter_comment();\n\n// \"tree-sitter"
},
{
"path": "bindings/node/binding_test.js",
"chars": 250,
"preview": "const assert = require(\"node:assert\");\nconst { test } = require(\"node:test\");\n\nconst Parser = require(\"tree-sitter\");\n\nt"
},
{
"path": "bindings/node/index.d.ts",
"chars": 436,
"preview": "type BaseNode = {\n type: string;\n named: boolean;\n};\n\ntype ChildNode = {\n multiple: boolean;\n required: boolean;\n t"
},
{
"path": "bindings/node/index.js",
"chars": 456,
"preview": "const root = require(\"path\").join(__dirname, \"..\", \"..\");\n\nmodule.exports =\n typeof process.versions.bun === \"string\"\n "
},
{
"path": "bindings/python/tests/test_binding.py",
"chars": 305,
"preview": "from unittest import TestCase\n\nimport tree_sitter\nimport tree_sitter_comment\n\n\nclass TestLanguage(TestCase):\n def tes"
},
{
"path": "bindings/python/tree_sitter_comment/__init__.py",
"chars": 1207,
"preview": "\"\"\"Grammar for code tags like TODO:, FIXME(user): for the tree-sitter parsing library\"\"\"\n\nfrom importlib.resources impor"
},
{
"path": "bindings/python/tree_sitter_comment/__init__.pyi",
"chars": 247,
"preview": "from typing import Final\n\n# NOTE: uncomment these to include any queries that this grammar contains:\n\n# HIGHLIGHTS_QUERY"
},
{
"path": "bindings/python/tree_sitter_comment/binding.c",
"chars": 838,
"preview": "#include <Python.h>\n\ntypedef struct TSLanguage TSLanguage;\n\nTSLanguage *tree_sitter_comment(void);\n\nstatic PyObject* _bi"
},
{
"path": "bindings/python/tree_sitter_comment/py.typed",
"chars": 0,
"preview": ""
},
{
"path": "bindings/rust/build.rs",
"chars": 614,
"preview": "fn main() {\n let src_dir = std::path::Path::new(\"src\");\n\n let mut c_config = cc::Build::new();\n c_config.std(\"c"
},
{
"path": "bindings/rust/lib.rs",
"chars": 1962,
"preview": "//! This crate provides Comment language support for the [tree-sitter][] parsing library.\n//!\n//! Typically, you will us"
},
{
"path": "bindings/swift/TreeSitterComment/comment.h",
"chars": 250,
"preview": "#ifndef TREE_SITTER_COMMENT_H_\n#define TREE_SITTER_COMMENT_H_\n\ntypedef struct TSLanguage TSLanguage;\n\n#ifdef __cplusplus"
},
{
"path": "bindings/swift/TreeSitterCommentTests/TreeSitterCommentTests.swift",
"chars": 371,
"preview": "import XCTest\nimport SwiftTreeSitter\nimport TreeSitterComment\n\nfinal class TreeSitterCommentTests: XCTestCase {\n func"
},
{
"path": "compile_flags.txt",
"chars": 16,
"preview": "-Isrc/\n-std=c99\n"
},
{
"path": "docs/.nojekyll",
"chars": 0,
"preview": ""
},
{
"path": "docs/index.html",
"chars": 11656,
"preview": "<!-- Extracted from the `tree-sitter playground` command. -->\n<head>\n <meta charset=\"utf-8\">\n <title>Tree-sitter gramm"
},
{
"path": "docs/js/playground.js",
"chars": 19064,
"preview": "function initializeLocalTheme() {\n const themeToggle = document.getElementById('theme-toggle');\n if (!themeToggle) ret"
},
{
"path": "docs/js/tree-sitter.js",
"chars": 152077,
"preview": "var __defProp = Object.defineProperty;\nvar __name = (target, value) => __defProp(target, \"name\", { value, configurable: "
},
{
"path": "go.mod",
"chars": 109,
"preview": "module github.com/stsewd/tree-sitter-comment\n\ngo 1.22\n\nrequire github.com/tree-sitter/go-tree-sitter v0.24.0\n"
},
{
"path": "grammar.js",
"chars": 2651,
"preview": "/**\n * @file Grammar for code tags like TODO:, FIXME(user): for the tree-sitter parsing library\n * @author Santos Galleg"
},
{
"path": "package.json",
"chars": 1298,
"preview": "{\n \"name\": \"tree-sitter-comment\",\n \"version\": \"0.3.0\",\n \"description\": \"Grammar for code tags like TODO:, FIXME(user)"
},
{
"path": "pyproject.toml",
"chars": 869,
"preview": "[build-system]\nrequires = [\"setuptools>=42\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"tree-si"
},
{
"path": "setup.py",
"chars": 2071,
"preview": "from os import path\nfrom platform import system\nfrom sysconfig import get_config_var\n\nfrom setuptools import Extension, "
},
{
"path": "src/grammar.json",
"chars": 5423,
"preview": "{\n \"$schema\": \"https://tree-sitter.github.io/tree-sitter/assets/schemas/grammar.schema.json\",\n \"name\": \"comment\",\n \"r"
},
{
"path": "src/node-types.json",
"chars": 1736,
"preview": "[\n {\n \"type\": \"source\",\n \"named\": true,\n \"root\": true,\n \"fields\": {},\n \"children\": {\n \"multiple\": t"
},
{
"path": "src/parser.c",
"chars": 28615,
"preview": "/* Automatically generated by tree-sitter v0.25.3 (2a835ee029dca1c325e6f1c01dbce40396f6123e) */\n\n#include \"tree_sitter/p"
},
{
"path": "src/scanner.c",
"chars": 651,
"preview": "#include <tree_sitter/parser.h>\n\n#include \"tree_sitter_comment/parser.c\"\n#include \"tree_sitter_comment/tokens.h\"\n\nvoid* "
},
{
"path": "src/tree_sitter/alloc.h",
"chars": 985,
"preview": "#ifndef TREE_SITTER_ALLOC_H_\n#define TREE_SITTER_ALLOC_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdbool.h>\n"
},
{
"path": "src/tree_sitter/array.h",
"chars": 10431,
"preview": "#ifndef TREE_SITTER_ARRAY_H_\n#define TREE_SITTER_ARRAY_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include \"./alloc.h\"\n"
},
{
"path": "src/tree_sitter/parser.h",
"chars": 7678,
"preview": "#ifndef TREE_SITTER_PARSER_H_\n#define TREE_SITTER_PARSER_H_\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <stdbool.h"
},
{
"path": "src/tree_sitter_comment/chars.c",
"chars": 1319,
"preview": "#include \"chars.h\"\n\nstatic bool is_upper(int32_t c)\n{\n const int32_t upper = 65;\n const int32_t lower = 90;\n return c"
},
{
"path": "src/tree_sitter_comment/chars.h",
"chars": 520,
"preview": "#ifndef TREE_SITTER_COMMENT_CHARS_H\n#define TREE_SITTER_COMMENT_CHARS_H\n\n#include <stdbool.h>\n#include <stdint.h>\n\n#defi"
},
{
"path": "src/tree_sitter_comment/parser.c",
"chars": 2359,
"preview": "#include \"parser.h\"\n\n#include \"chars.c\"\n#include \"tokens.h\"\n#include <stdbool.h>\n#include <stdio.h>\n\n/// Parse the name "
},
{
"path": "src/tree_sitter_comment/parser.h",
"chars": 290,
"preview": "#ifndef TREE_SITTER_COMMENT_PARSER_H\n#define TREE_SITTER_COMMENT_PARSER_H\n\n#include <tree_sitter/parser.h>\n\nstatic bool "
},
{
"path": "src/tree_sitter_comment/tokens.h",
"chars": 177,
"preview": "#ifndef TREE_SITTER_COMMENT_TOKENS_H\n#define TREE_SITTER_COMMENT_TOKENS_H\n\nenum TokenType {\n T_TAGNAME,\n T_INVALID_TOK"
},
{
"path": "test/corpus/source.txt",
"chars": 2760,
"preview": "================================================================================\nSimple tags\n==========================="
},
{
"path": "tree-sitter.json",
"chars": 978,
"preview": "{\n \"$schema\": \"https://tree-sitter.github.io/tree-sitter/assets/schemas/config.schema.json\",\n \"grammars\": [\n {\n "
}
]
About this extraction
This page contains the full source code of the stsewd/tree-sitter-comment GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 54 files (273.4 KB), approximately 76.5k tokens, and a symbol index with 309 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.