Use tree-sitter-lua from crates.io

pull/795/head
Wilfred Hughes 2024-12-20 09:12:16 +07:00
parent a6eb339f71
commit cef0b569dd
57 changed files with 19 additions and 21353 deletions

@ -11,8 +11,8 @@ with YAML.
Improved language detection when one argument is a named pipe.
Updated to the latest tree-sitter parser for Bash, C, C++, C#, CSS,
Go, Haskell, HTML, Java, JavaScript, JSON, Julia, Objective-C, OCaml,
PHP, Python, Ruby, Scala, TOML and TypeScript.
Go, Haskell, HTML, Java, JavaScript, JSON, Julia, Lua, Objective-C,
OCaml, PHP, Python, Ruby, Scala, TOML and TypeScript.
### Syntax Highlighting

11
Cargo.lock generated

@ -262,6 +262,7 @@ dependencies = [
"tree-sitter-json",
"tree-sitter-julia",
"tree-sitter-language",
"tree-sitter-lua",
"tree-sitter-objc",
"tree-sitter-ocaml",
"tree-sitter-php",
@ -1147,6 +1148,16 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c199356c799a8945965bb5f2c55b2ad9d9aa7c4b4f6e587fe9dea0bc715e5f9c"
[[package]]
name = "tree-sitter-lua"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cdb9adf0965fec58e7660cbb3a059dbb12ebeec9459e6dcbae3db004739641e"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-objc"
version = "3.0.2"

@ -98,6 +98,7 @@ tree-sitter-json = "0.24.8"
tree-sitter-html = "0.23.2"
tree-sitter-css = "0.23.1"
tree-sitter-toml-ng = "0.7.0"
tree-sitter-lua = "0.2.0"
[dev-dependencies]
# assert_cmd 2.0.10 requires predicates 3.

@ -162,11 +162,6 @@ fn main() {
src_dir: "vendored_parsers/tree-sitter-latex-src",
extra_files: vec!["scanner.c"],
},
TreeSitterParser {
name: "tree-sitter-lua",
src_dir: "vendored_parsers/tree-sitter-lua-src",
extra_files: vec!["scanner.c"],
},
TreeSitterParser {
name: "tree-sitter-make",
src_dir: "vendored_parsers/tree-sitter-make-src",

@ -81,7 +81,6 @@ extern "C" {
fn tree_sitter_janet_simple() -> ts::Language;
fn tree_sitter_kotlin() -> ts::Language;
fn tree_sitter_latex() -> ts::Language;
fn tree_sitter_lua() -> ts::Language;
fn tree_sitter_make() -> ts::Language;
fn tree_sitter_newick() -> ts::Language;
fn tree_sitter_nix() -> ts::Language;
@ -683,18 +682,17 @@ pub(crate) fn from_language(language: guess::Language) -> TreeSitterConfig {
}
}
Lua => {
let language = unsafe { tree_sitter_lua() };
let language_fn = tree_sitter_lua::LANGUAGE;
let language = tree_sitter::Language::new(language_fn);
TreeSitterConfig {
language: language.clone(),
atom_nodes: vec!["string"].into_iter().collect(),
delimiter_tokens: vec![("(", ")"), ("{", "}"), ("[", "]")]
.into_iter()
.collect(),
highlight_query: ts::Query::new(
&language,
include_str!("../../vendored_parsers/highlights/lua.scm"),
)
.unwrap(),
highlight_query: ts::Query::new(&language, tree_sitter_lua::HIGHLIGHTS_QUERY)
.unwrap(),
sub_languages: vec![],
}
}

@ -1 +0,0 @@
../tree-sitter-lua/queries/highlights.scm

@ -1 +0,0 @@
tree-sitter-lua/src/

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

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

@ -1,107 +0,0 @@
name: CI
on:
push:
branches: [main]
paths:
- grammar.js
- src/**
- test/**
- bindings/**
- binding.gyp
pull_request:
paths:
- grammar.js
- src/**
- test/**
- bindings/**
- binding.gyp
concurrency:
group: ${{github.workflow}}-${{github.ref}}
cancel-in-progress: true
jobs:
test:
name: Test parser
runs-on: ${{matrix.os}}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-14]
steps:
- name: Set up repository
uses: tree-sitter/parser-setup-action@v1.1
with:
node-version: ${{vars.NODE_VERSION}}
- name: Clone apisix corpus
uses: actions/checkout@v4
with:
path: examples/apisix
repository: apache/apisix
sparse-checkout: apisix/
- name: Clone kong corpus
uses: actions/checkout@v4
with:
path: examples/kong
repository: Kong/kong
sparse-checkout: kong/
- name: Clone lua corpus
uses: actions/checkout@v4
with:
path: examples/lua
repository: lua/lua
sparse-checkout: testes/
- name: Clone luvit corpus
uses: actions/checkout@v4
with:
path: examples/luvit
repository: luvit/luvit
- name: Clone neovim corpus
uses: actions/checkout@v4
with:
path: examples/neovim
repository: neovim/neovim
sparse-checkout-cone-mode: false
sparse-checkout: |-
/test/**/*.lua
/scripts/**/*.lua
/runtime/**/*.lua
- name: Clone xmake corpus
uses: actions/checkout@v4
if: runner.os != 'Windows'
with:
path: examples/xmake
repository: xmake-io/xmake
- name: Run tests
uses: tree-sitter/parser-test-action@v1.2
with:
test-library: ${{runner.os == 'Linux'}}
corpus-files: |-
examples/apisix/**/*.lua
examples/kong/**/*.lua
examples/lua/**/*.lua
examples/luvit/**/*.lua
examples/neovim/**/*.lua
examples/xmake/**/*.lua
invalid-files: |-
examples/neovim/test/functional/fixtures/lua/syntax_error.lua
fuzz:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Check for scanner changes
id: scanner-changes
run: |-
if git diff --quiet HEAD^ -- src/scanner.c; then
printf 'changed=false\n' >> "$GITHUB_OUTPUT"
else
printf 'changed=true\n' >> "$GITHUB_OUTPUT"
fi
- name: Fuzz parser
uses: tree-sitter/fuzz-action@v4
if: steps.scanner-changes.outputs.changed == 'true'

@ -1,17 +0,0 @@
name: Publish package
on:
push:
tags: ["*"]
jobs:
npm:
uses: tree-sitter/workflows/.github/workflows/package-npm.yml@main
with:
package-name: "@tree-sitter-grammars/tree-sitter-lua"
secrets:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
crates:
uses: tree-sitter/workflows/.github/workflows/package-crates.yml@main
secrets:
CARGO_REGISTRY_TOKEN: ${{secrets.CARGO_TOKEN}}

@ -1,38 +0,0 @@
# Rust artifacts
Cargo.lock
target/
# Node artifacts
build/
node_modules/
*.tgz
# Swift artifacts
.build/
# Go artifacts
go.sum
_obj/
# Python artifacts
.venv/
dist/
*.egg-info
*.whl
# C artifacts
*.a
*.so
*.so.*
*.dylib
*.dll
*.pc
# Example dirs
/examples/*/
# Grammar volatiles
dsl.d.ts
*.wasm
*.obj
*.o

@ -1,3 +0,0 @@
{
"singleQuote": true
}

@ -1,24 +0,0 @@
[package]
name = "tree-sitter-lua"
description = "Lua grammar for tree-sitter"
version = "0.1.0"
license = "MIT"
readme = "README.md"
keywords = ["incremental", "parsing", "tree-sitter", "lua"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/tree-sitter-grammars/tree-sitter-lua"
authors = ["Munif Tanjim <hello@muniftanjim.dev>"]
edition = "2021"
autoexamples = false
build = "bindings/rust/build.rs"
include = ["bindings/rust/*", "grammar.js", "queries/*", "src/*"]
[lib]
path = "bindings/rust/lib.rs"
[dependencies]
tree-sitter = ">=0.21.0"
[build-dependencies]
cc = "^1.0.89"

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2021 Munif Tanjim
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.

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

@ -1,49 +0,0 @@
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "TreeSitterLua",
platforms: [.macOS(.v10_13), .iOS(.v11)],
products: [
.library(name: "TreeSitterLua", targets: ["TreeSitterLua"]),
],
dependencies: [],
targets: [
.target(name: "TreeSitterLua",
path: ".",
exclude: [
"Cargo.toml",
"Makefile",
"binding.gyp",
"bindings/c",
"bindings/go",
"bindings/node",
"bindings/python",
"bindings/rust",
"prebuilds",
"node_modules",
"grammar.js",
"package.json",
"package-lock.json",
"pyproject.toml",
"setup.py",
"test",
"types",
"examples",
".editorconfig",
".github",
".gitignore",
".gitattributes",
],
sources: [
"src/parser.c",
"src/scanner.c",
],
resources: [
.copy("queries")
],
publicHeadersPath: "bindings/swift",
cSettings: [.headerSearchPath("src")])
],
cLanguageStandard: .c11
)

@ -1,29 +0,0 @@
# tree-sitter-lua
[![CI][ci]](https://github.com/tree-sitter-grammars/tree-sitter-lua/actions/workflows/ci.yml)
[![discord][discord]](https://discord.gg/w7nTvsVJhm)
[![matrix][matrix]](https://matrix.to/#/#tree-sitter-chat:matrix.org)
[![npm][npm]](https://www.npmjs.com/package/%40tree-sitter-grammars%2Ftree-sitter-lua)
[![crates][crates]](https://crates.io/crates/tree-sitter-lua)
Lua grammar for tree-sitter.
- Lua 5.x
- LuaJIT 2.x
## References
- [Lua Documentation](https://www.lua.org/docs.html)
## Acknowledgement
The [external scanner](/src/scanner.c) was initially based on these repositories:
- [Azganoth/tree-sitter-lua](https://github.com/Azganoth/tree-sitter-lua)
- [euclidianAce/tree-sitter-teal](https://github.com/euclidianAce/tree-sitter-teal)
[ci]: https://img.shields.io/github/actions/workflow/status/tree-sitter-grammars/tree-sitter-lua/ci.yml?logo=github&label=CI
[discord]: https://img.shields.io/discord/1063097320771698699?logo=discord&label=discord
[matrix]: https://img.shields.io/matrix/tree-sitter-chat%3Amatrix.org?logo=matrix&label=matrix
[npm]: https://img.shields.io/npm/v/%40tree-sitter-grammars%2Ftree-sitter-lua?logo=npm
[crates]: https://img.shields.io/crates/v/tree-sitter-lua?logo=rust

@ -1,21 +0,0 @@
{
"targets": [
{
"target_name": "tree_sitter_lua_binding",
"dependencies": [
"<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
],
"include_dirs": [
"src",
],
"sources": [
"bindings/node/binding.cc",
"src/parser.c",
"src/scanner.c",
],
"cflags_c": [
"-std=c11",
],
}
]
}

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

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

@ -1,13 +0,0 @@
package tree_sitter_lua
// #cgo CFLAGS: -std=c11 -fPIC
// #include "../../src/parser.c"
// #include "../../src/scanner.c"
import "C"
import "unsafe"
// Get the tree-sitter Language for this grammar.
func Language() unsafe.Pointer {
return unsafe.Pointer(C.tree_sitter_lua())
}

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

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

@ -1,20 +0,0 @@
#include <napi.h>
typedef struct TSLanguage TSLanguage;
extern "C" TSLanguage *tree_sitter_lua();
// "tree-sitter", "language" hashed with BLAKE2
const napi_type_tag LANGUAGE_TYPE_TAG = {
0x8AF2E5212AD58ABF, 0xD5006CAD83ABBA16
};
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports["name"] = Napi::String::New(env, "lua");
auto language = Napi::External<TSLanguage>::New(env, tree_sitter_lua());
language.TypeTag(&LANGUAGE_TYPE_TAG);
exports["language"] = language;
return exports;
}
NODE_API_MODULE(tree_sitter_lua_binding, Init)

@ -1,28 +0,0 @@
type BaseNode = {
type: string;
named: boolean;
};
type ChildNode = {
multiple: boolean;
required: boolean;
types: BaseNode[];
};
type NodeInfo =
| (BaseNode & {
subtypes: BaseNode[];
})
| (BaseNode & {
fields: { [name: string]: ChildNode };
children: ChildNode[];
});
type Language = {
name: string;
language: unknown;
nodeTypeInfo: NodeInfo[];
};
declare const language: Language;
export = language;

@ -1,7 +0,0 @@
const root = require("path").join(__dirname, "..", "..");
module.exports = require("node-gyp-build")(root);
try {
module.exports.nodeTypeInfo = require("../../src/node-types.json");
} catch (_) {}

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

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

@ -1,19 +0,0 @@
fn main() {
let src_dir = std::path::Path::new("src");
let mut c_config = cc::Build::new();
c_config.include(src_dir);
c_config
.flag_if_supported("-Wno-unused-parameter")
.flag_if_supported("-Wno-unused-but-set-variable")
.flag_if_supported("-Wno-trigraphs");
let parser_path = src_dir.join("parser.c");
c_config.file(&parser_path);
println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap());
let scanner_path = src_dir.join("scanner.c");
c_config.file(&scanner_path);
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
c_config.compile("tree-sitter-lua");
}

@ -1,53 +0,0 @@
//! This crate provides Lua language support for the [tree-sitter][] parsing library.
//!
//! Typically, you will use the [language][language func] function to add this language to a
//! tree-sitter [Parser][], and then use the parser to parse some code:
//!
//! ```
//! let code = r#"
//! return 42
//! "#;
//! let mut parser = tree_sitter::Parser::new();
//! parser.set_language(&tree_sitter_lua::language()).expect("Error loading lua grammar");
//! let tree = parser.parse(code, None).unwrap();
//! assert!(!tree.root_node().has_error());
//! ```
//!
//! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
//! [language func]: fn.language.html
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/
use tree_sitter::Language;
extern "C" {
fn tree_sitter_lua() -> Language;
}
/// Get the tree-sitter [Language][] for this grammar.
///
/// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
pub fn language() -> Language {
unsafe { tree_sitter_lua() }
}
/// The content of the [`node-types.json`][] file for this grammar.
///
/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types
pub const NODE_TYPES: &str = include_str!("../../src/node-types.json");
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())
.expect("Error loading Lua language");
}
}

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

@ -1,566 +0,0 @@
const PREC = {
OR: 1, // or
AND: 2, // and
COMPARE: 3, // < > <= >= ~= ==
BIT_OR: 4, // |
BIT_NOT: 5, // ~
BIT_AND: 6, // &
BIT_SHIFT: 7, // << >>
CONCAT: 8, // ..
PLUS: 9, // + -
MULTI: 10, // * / // %
UNARY: 11, // not # - ~
POWER: 12, // ^
};
const list_seq = (rule, separator, trailing_separator = false) =>
trailing_separator
? seq(rule, repeat(seq(separator, rule)), optional(separator))
: seq(rule, repeat(seq(separator, rule)));
const optional_block = ($) => alias(optional($._block), $.block);
// namelist ::= Name {',' Name}
const name_list = ($) => list_seq(field('name', $.identifier), ',');
module.exports = grammar({
name: 'lua',
extras: ($) => [$.comment, /\s/],
externals: ($) => [
$._block_comment_start,
$._block_comment_content,
$._block_comment_end,
$._block_string_start,
$._block_string_content,
$._block_string_end,
],
supertypes: ($) => [$.statement, $.expression, $.declaration, $.variable],
word: ($) => $.identifier,
rules: {
// chunk ::= block
chunk: ($) =>
seq(
optional($.hash_bang_line),
repeat($.statement),
optional($.return_statement)
),
hash_bang_line: (_) => /#.*/,
// block ::= {stat} [retstat]
_block: ($) =>
choice(
seq(repeat1($.statement), optional($.return_statement)),
seq(repeat($.statement), $.return_statement)
),
/*
stat ::= ';' |
varlist '=' explist |
functioncall |
label |
break |
goto Name |
do block end |
while exp do block end |
repeat block until exp |
if exp then block {elseif exp then block} [else block] end |
for Name '=' exp ',' exp [',' exp] do block end |
for namelist in explist do block end |
function funcname funcbody |
local function Name funcbody |
local namelist ['=' explist]
*/
statement: ($) =>
choice(
$.empty_statement,
$.assignment_statement,
$.function_call,
$.label_statement,
$.break_statement,
$.goto_statement,
$.do_statement,
$.while_statement,
$.repeat_statement,
$.if_statement,
$.for_statement,
$.declaration
),
// retstat ::= return [explist] [';']
return_statement: ($) =>
seq(
'return',
optional(alias($._expression_list, $.expression_list)),
optional(';')
),
// ';'
empty_statement: (_) => ';',
// varlist '=' explist
assignment_statement: ($) =>
seq(
alias($._variable_assignment_varlist, $.variable_list),
'=',
alias($._variable_assignment_explist, $.expression_list)
),
// varlist ::= var {',' var}
_variable_assignment_varlist: ($) =>
list_seq(field('name', $.variable), ','),
// explist ::= exp {',' exp}
_variable_assignment_explist: ($) =>
list_seq(field('value', $.expression), ','),
// label ::= '::' Name '::'
label_statement: ($) => seq('::', $.identifier, '::'),
// break
break_statement: (_) => 'break',
// goto Name
goto_statement: ($) => seq('goto', $.identifier),
// do block end
do_statement: ($) => seq('do', field('body', optional_block($)), 'end'),
// while exp do block end
while_statement: ($) =>
seq(
'while',
field('condition', $.expression),
'do',
field('body', optional_block($)),
'end'
),
// repeat block until exp
repeat_statement: ($) =>
seq(
'repeat',
field('body', optional_block($)),
'until',
field('condition', $.expression)
),
// if exp then block {elseif exp then block} [else block] end
if_statement: ($) =>
seq(
'if',
field('condition', $.expression),
'then',
field('consequence', optional_block($)),
repeat(field('alternative', $.elseif_statement)),
optional(field('alternative', $.else_statement)),
'end'
),
// elseif exp then block
elseif_statement: ($) =>
seq(
'elseif',
field('condition', $.expression),
'then',
field('consequence', optional_block($))
),
// else block
else_statement: ($) => seq('else', field('body', optional_block($))),
// for Name '=' exp ',' exp [',' exp] do block end
// for namelist in explist do block end
for_statement: ($) =>
seq(
'for',
field('clause', choice($.for_generic_clause, $.for_numeric_clause)),
'do',
field('body', optional_block($)),
'end'
),
// namelist in explist
for_generic_clause: ($) =>
seq(
alias($._name_list, $.variable_list),
'in',
alias($._expression_list, $.expression_list)
),
// Name '=' exp ',' exp [',' exp]
for_numeric_clause: ($) =>
seq(
field('name', $.identifier),
'=',
field('start', $.expression),
',',
field('end', $.expression),
optional(seq(',', field('step', $.expression)))
),
// function funcname funcbody
// local function Name funcbody
// local namelist ['=' explist]
declaration: ($) =>
choice(
$.function_declaration,
field(
'local_declaration',
alias($._local_function_declaration, $.function_declaration)
),
field('local_declaration', $.variable_declaration)
),
// function funcname funcbody
function_declaration: ($) =>
seq('function', field('name', $._function_name), $._function_body),
// local function Name funcbody
_local_function_declaration: ($) =>
seq('local', 'function', field('name', $.identifier), $._function_body),
// funcname ::= Name {'.' Name} [':' Name]
_function_name: ($) =>
choice(
$._function_name_prefix_expression,
alias(
$._function_name_method_index_expression,
$.method_index_expression
)
),
_function_name_prefix_expression: ($) =>
choice(
$.identifier,
alias($._function_name_dot_index_expression, $.dot_index_expression)
),
_function_name_dot_index_expression: ($) =>
seq(
field('table', $._function_name_prefix_expression),
'.',
field('field', $.identifier)
),
_function_name_method_index_expression: ($) =>
seq(
field('table', $._function_name_prefix_expression),
':',
field('method', $.identifier)
),
// local namelist ['=' explist]
variable_declaration: ($) =>
seq(
'local',
choice(
alias($._att_name_list, $.variable_list),
alias($._local_variable_assignment, $.assignment_statement)
)
),
_local_variable_assignment: ($) =>
seq(
alias($._att_name_list, $.variable_list),
'=',
alias($._variable_assignment_explist, $.expression_list)
),
// namelist ::= Name {',' Name}
_name_list: ($) => name_list($),
// attnamelist ::= Name attrib {, Name attrib}
_att_name_list: ($) =>
list_seq(
seq(
field('name', $.identifier),
optional(field('attribute', alias($._attrib, $.attribute)))
),
','
),
// attrib ::= [< Name >]
_attrib: ($) => seq('<', $.identifier, '>'),
// explist ::= exp {',' exp}
_expression_list: ($) => list_seq($.expression, ','),
/*
exp ::= nil | false | true | Numeral | LiteralString | '...' | functiondef |
prefixexp | tableconstructor | exp binop exp | unop exp
*/
expression: ($) =>
choice(
$.nil,
$.false,
$.true,
$.number,
$.string,
$.vararg_expression,
$.function_definition,
$.variable,
$.function_call,
$.parenthesized_expression,
$.table_constructor,
$.binary_expression,
$.unary_expression
),
// nil
nil: (_) => 'nil',
// false
false: (_) => 'false',
// true
true: (_) => 'true',
// Numeral
number: (_) => {
function number_literal(digits, exponent_marker, exponent_digits) {
return choice(
seq(digits, /U?LL/i),
seq(
choice(
seq(optional(digits), optional('.'), digits),
seq(digits, optional('.'), optional(digits))
),
optional(
seq(
choice(
exponent_marker.toLowerCase(),
exponent_marker.toUpperCase()
),
seq(optional(choice('-', '+')), exponent_digits)
)
),
optional(choice('i', 'I'))
)
);
}
const decimal_digits = /[0-9]+/;
const decimal_literal = number_literal(
decimal_digits,
'e',
decimal_digits
);
const hex_digits = /[a-fA-F0-9]+/;
const hex_literal = seq(
choice('0x', '0X'),
number_literal(hex_digits, 'p', decimal_digits)
);
return token(choice(decimal_literal, hex_literal));
},
// LiteralString
string: ($) => choice($._quote_string, $._block_string),
_quote_string: ($) =>
choice(
seq(
field('start', alias('"', '"')),
field(
'content',
optional(alias($._doublequote_string_content, $.string_content))
),
field('end', alias('"', '"'))
),
seq(
field('start', alias("'", "'")),
field(
'content',
optional(alias($._singlequote_string_content, $.string_content))
),
field('end', alias("'", "'"))
)
),
_doublequote_string_content: ($) =>
repeat1(choice(token.immediate(prec(1, /[^"\\]+/)), $.escape_sequence)),
_singlequote_string_content: ($) =>
repeat1(choice(token.immediate(prec(1, /[^'\\]+/)), $.escape_sequence)),
_block_string: ($) =>
seq(
field('start', alias($._block_string_start, '[[')),
field('content', alias($._block_string_content, $.string_content)),
field('end', alias($._block_string_end, ']]'))
),
escape_sequence: () =>
token.immediate(
seq(
'\\',
choice(
/[\nabfnrtv\\'"]/,
/z\s*/,
/[0-9]{1,3}/,
/x[0-9a-fA-F]{2}/,
/u\{[0-9a-fA-F]+\}/
)
)
),
// '...'
vararg_expression: (_) => '...',
// functiondef ::= function funcbody
function_definition: ($) => seq('function', $._function_body),
// funcbody ::= '(' [parlist] ')' block end
_function_body: ($) =>
seq(
field('parameters', $.parameters),
field('body', optional_block($)),
'end'
),
// '(' [parlist] ')'
parameters: ($) => seq('(', optional($._parameter_list), ')'),
// parlist ::= namelist [',' '...'] | '...'
_parameter_list: ($) =>
choice(
seq(name_list($), optional(seq(',', $.vararg_expression))),
$.vararg_expression
),
// prefixexp ::= var | functioncall | '(' exp ')'
_prefix_expression: ($) =>
prec(1, choice($.variable, $.function_call, $.parenthesized_expression)),
// var ::= Name | prefixexp [ exp ] | prefixexp . Name
variable: ($) =>
choice($.identifier, $.bracket_index_expression, $.dot_index_expression),
// prefixexp [ exp ]
bracket_index_expression: ($) =>
seq(
field('table', $._prefix_expression),
'[',
field('field', $.expression),
']'
),
// prefixexp . Name
dot_index_expression: ($) =>
seq(
field('table', $._prefix_expression),
'.',
field('field', $.identifier)
),
// functioncall ::= prefixexp args | prefixexp ':' Name args
function_call: ($) =>
seq(
field('name', choice($._prefix_expression, $.method_index_expression)),
field('arguments', $.arguments)
),
// prefixexp ':' Name
method_index_expression: ($) =>
seq(
field('table', $._prefix_expression),
':',
field('method', $.identifier)
),
// args ::= '(' [explist] ')' | tableconstructor | LiteralString
arguments: ($) =>
choice(
seq('(', optional(list_seq($.expression, ',')), ')'),
$.table_constructor,
$.string
),
// '(' exp ')'
parenthesized_expression: ($) => seq('(', $.expression, ')'),
// tableconstructor ::= '{' [fieldlist] '}'
table_constructor: ($) => seq('{', optional($._field_list), '}'),
// fieldlist ::= field {fieldsep field} [fieldsep]
_field_list: ($) => list_seq($.field, $._field_sep, true),
// fieldsep ::= ',' | ';'
_field_sep: (_) => choice(',', ';'),
// field ::= '[' exp ']' '=' exp | Name '=' exp | exp
field: ($) =>
choice(
seq(
'[',
field('name', $.expression),
']',
'=',
field('value', $.expression)
),
seq(field('name', $.identifier), '=', field('value', $.expression)),
field('value', $.expression)
),
// exp binop exp
binary_expression: ($) =>
choice(
...[
['or', PREC.OR],
['and', PREC.AND],
['<', PREC.COMPARE],
['<=', PREC.COMPARE],
['==', PREC.COMPARE],
['~=', PREC.COMPARE],
['>=', PREC.COMPARE],
['>', PREC.COMPARE],
['|', PREC.BIT_OR],
['~', PREC.BIT_NOT],
['&', PREC.BIT_AND],
['<<', PREC.BIT_SHIFT],
['>>', PREC.BIT_SHIFT],
['+', PREC.PLUS],
['-', PREC.PLUS],
['*', PREC.MULTI],
['/', PREC.MULTI],
['//', PREC.MULTI],
['%', PREC.MULTI],
].map(([operator, precedence]) =>
prec.left(
precedence,
seq(
field('left', $.expression),
operator,
field('right', $.expression)
)
)
),
...[
['..', PREC.CONCAT],
['^', PREC.POWER],
].map(([operator, precedence]) =>
prec.right(
precedence,
seq(
field('left', $.expression),
operator,
field('right', $.expression)
)
)
)
),
// unop exp
unary_expression: ($) =>
prec.left(
PREC.UNARY,
seq(choice('not', '#', '-', '~'), field('operand', $.expression))
),
// Name
identifier: (_) => {
const identifier_start =
/[^\p{Control}\s+\-*/%^#&~|<>=(){}\[\];:,.\\'"\d]/;
const identifier_continue =
/[^\p{Control}\s+\-*/%^#&~|<>=(){}\[\];:,.\\'"]*/;
return token(seq(identifier_start, identifier_continue));
},
// comment
comment: ($) =>
choice(
seq(
field('start', '--'),
field('content', alias(/[^\r\n]*/, $.comment_content))
),
seq(
field('start', alias($._block_comment_start, '[[')),
field('content', alias($._block_comment_content, $.comment_content)),
field('end', alias($._block_comment_end, ']]'))
)
),
},
});

@ -1,387 +0,0 @@
{
"name": "@tree-sitter-grammars/tree-sitter-lua",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@tree-sitter-grammars/tree-sitter-lua",
"version": "0.1.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"node-addon-api": "^7.1.0",
"node-gyp-build": "^4.8.0"
},
"devDependencies": {
"prebuildify": "^6.0.0",
"tree-sitter-cli": "^0.21.0"
},
"peerDependencies": {
"tree-sitter": "^0.21.0"
},
"peerDependenciesMeta": {
"tree_sitter": {
"optional": true
}
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/bl": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
"integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
"dev": true,
"dependencies": {
"buffer": "^5.5.0",
"inherits": "^2.0.4",
"readable-stream": "^3.4.0"
}
},
"node_modules/buffer": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.1.13"
}
},
"node_modules/chownr": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
"dev": true
},
"node_modules/end-of-stream": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
"integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
"dev": true,
"dependencies": {
"once": "^1.4.0"
}
},
"node_modules/execspawn": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/execspawn/-/execspawn-1.0.1.tgz",
"integrity": "sha512-s2k06Jy9i8CUkYe0+DxRlvtkZoOkwwfhB+Xxo5HGUtrISVW2m98jO2tr67DGRFxZwkjQqloA3v/tNtjhBRBieg==",
"dev": true,
"dependencies": {
"util-extend": "^1.0.1"
}
},
"node_modules/fs-constants": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
"dev": true
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"dev": true
},
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"dev": true,
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp-classic": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
"dev": true
},
"node_modules/node-abi": {
"version": "3.56.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.56.0.tgz",
"integrity": "sha512-fZjdhDOeRcaS+rcpve7XuwHBmktS1nS1gzgghwKUQQ8nTy2FdSDr6ZT8k6YhvlJeHmmQMYiT/IH9hfco5zeW2Q==",
"dev": true,
"dependencies": {
"semver": "^7.3.5"
},
"engines": {
"node": ">=10"
}
},
"node_modules/node-addon-api": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.0.tgz",
"integrity": "sha512-mNcltoe1R8o7STTegSOHdnJNN7s5EUvhoS7ShnTHDyOSd+8H+UdWODq6qSv67PjC8Zc5JRT8+oLAMCr0SIXw7g==",
"engines": {
"node": "^16 || ^18 || >= 20"
}
},
"node_modules/node-gyp-build": {
"version": "4.8.0",
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.0.tgz",
"integrity": "sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og==",
"bin": {
"node-gyp-build": "bin.js",
"node-gyp-build-optional": "optional.js",
"node-gyp-build-test": "build-test.js"
}
},
"node_modules/npm-run-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-3.1.0.tgz",
"integrity": "sha512-Dbl4A/VfiVGLgQv29URL9xshU8XDY1GeLy+fsaZ1AA8JDSfjvr5P5+pzRbWqRSBxk6/DW7MIh8lTM/PaGnP2kg==",
"dev": true,
"dependencies": {
"path-key": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dev": true,
"dependencies": {
"wrappy": "1"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/prebuildify": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/prebuildify/-/prebuildify-6.0.0.tgz",
"integrity": "sha512-DEvK4C3tcimIp7Pzqbs036n9i6CTKGp1XVEpMnr4wV3enKU5sBogPP+lP3KZw7993i42bXnsd5eIxAXQ566Cqw==",
"dev": true,
"dependencies": {
"execspawn": "^1.0.1",
"minimist": "^1.2.5",
"mkdirp-classic": "^0.5.3",
"node-abi": "^3.3.0",
"npm-run-path": "^3.1.0",
"pump": "^3.0.0",
"tar-fs": "^2.1.0"
},
"bin": {
"prebuildify": "bin.js"
}
},
"node_modules/pump": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz",
"integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==",
"dev": true,
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dev": true,
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/semver": {
"version": "7.6.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz",
"integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==",
"dev": true,
"dependencies": {
"lru-cache": "^6.0.0"
},
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"dev": true,
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
"dev": true,
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
"pump": "^3.0.0",
"tar-stream": "^2.1.4"
}
},
"node_modules/tar-stream": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
"dev": true,
"dependencies": {
"bl": "^4.0.3",
"end-of-stream": "^1.4.1",
"fs-constants": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.1.1"
},
"engines": {
"node": ">=6"
}
},
"node_modules/tree-sitter": {
"version": "0.21.0",
"resolved": "https://registry.npmjs.org/tree-sitter/-/tree-sitter-0.21.0.tgz",
"integrity": "sha512-WDhpLxQdW7wsmmnBsf4NGqnEKs+Kxljk/CfbJJxgzZiinfA1gAWnhi/GirQjClw+woXhYsNq930BlskFulMMBQ==",
"hasInstallScript": true,
"peer": true,
"dependencies": {
"node-addon-api": "^7.1.0",
"node-gyp-build": "^4.8.0"
}
},
"node_modules/tree-sitter-cli": {
"version": "0.21.0",
"resolved": "https://registry.npmjs.org/tree-sitter-cli/-/tree-sitter-cli-0.21.0.tgz",
"integrity": "sha512-wA7wT5724fNQW82XDH6zT6ZcYonjrAKLCHHuhLsPcAKULrhp3rNuMvlgBdB5FUBvmjHNhtTZF/qpHenMoRJPBw==",
"dev": true,
"hasInstallScript": true,
"bin": {
"tree-sitter": "cli.js"
}
},
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"dev": true
},
"node_modules/util-extend": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/util-extend/-/util-extend-1.0.3.tgz",
"integrity": "sha512-mLs5zAK+ctllYBj+iAQvlDCwoxU/WDOUaJkcFudeiAX6OajC6BKXJUa9a+tbtkC11dz2Ufb7h0lyvIOVn4LADA==",
"dev": true
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"dev": true
},
"node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"dev": true
}
}
}

@ -1,61 +0,0 @@
{
"name": "@tree-sitter-grammars/tree-sitter-lua",
"version": "0.1.0",
"description": "Lua grammar for tree-sitter",
"repository": "tree-sitter-grammars/tree-sitter-lua",
"author": "Munif Tanjim (https://muniftanjim.dev)",
"license": "MIT",
"main": "bindings/node",
"types": "bindings/node",
"keywords": [
"incremental",
"parsing",
"tree-sitter",
"lua"
],
"files": [
"grammar.js",
"binding.gyp",
"prebuilds/**",
"bindings/node/*",
"queries/**",
"src/**"
],
"dependencies": {
"node-addon-api": "^7.1.0",
"node-gyp-build": "^4.8.0"
},
"devDependencies": {
"tree-sitter-cli": "^0.21.0",
"prebuildify": "^6.0.0"
},
"peerDependencies": {
"tree-sitter": "^0.21.0"
},
"peerDependenciesMeta": {
"tree_sitter": {
"optional": true
}
},
"scripts": {
"build": "tree-sitter generate --no-bindings",
"test": "tree-sitter test",
"install": "node-gyp-build",
"prebuildify": "prebuildify --napi --strip"
},
"publishConfig": {
"access": "public"
},
"tree-sitter": [
{
"scope": "source.lua",
"injection-regex": "^lua$",
"highlights": "queries/highlights.scm",
"injections": "queries/injections.scm",
"tags": "queries/tags.scm",
"file-types": [
"lua"
]
}
]
}

@ -1,32 +0,0 @@
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "tree-sitter-lua"
description = "Lua grammar for tree-sitter"
version = "0.1.0"
keywords = ["incremental", "parsing", "tree-sitter", "lua"]
classifiers = [
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Software Development :: Compilers",
"Topic :: Text Processing :: Linguistic",
"Typing :: Typed"
]
authors = [
{name = "Munif Tanjim", email = "hello@muniftanjim.dev"}
]
requires-python = ">=3.8"
license.text = "MIT"
readme = "README.md"
[project.urls]
Homepage = "https://github.com/tree-sitter-grammars/tree-sitter-lua"
[project.optional-dependencies]
core = ["tree-sitter~=0.21"]
[tool.cibuildwheel]
build = "cp38-*"
build-frontend = "build"

@ -1,224 +0,0 @@
;; Keywords
"return" @keyword.return
[
"goto"
"in"
"local"
] @keyword
(label_statement) @label
(break_statement) @keyword
(do_statement
[
"do"
"end"
] @keyword)
(while_statement
[
"while"
"do"
"end"
] @repeat)
(repeat_statement
[
"repeat"
"until"
] @repeat)
(if_statement
[
"if"
"elseif"
"else"
"then"
"end"
] @conditional)
(elseif_statement
[
"elseif"
"then"
"end"
] @conditional)
(else_statement
[
"else"
"end"
] @conditional)
(for_statement
[
"for"
"do"
"end"
] @repeat)
(function_declaration
[
"function"
"end"
] @keyword.function)
(function_definition
[
"function"
"end"
] @keyword.function)
;; Operators
[
"and"
"not"
"or"
] @keyword.operator
[
"+"
"-"
"*"
"/"
"%"
"^"
"#"
"=="
"~="
"<="
">="
"<"
">"
"="
"&"
"~"
"|"
"<<"
">>"
"//"
".."
] @operator
;; Punctuations
[
";"
":"
","
"."
] @punctuation.delimiter
;; Brackets
[
"("
")"
"["
"]"
"{"
"}"
] @punctuation.bracket
;; Variables
(identifier) @variable
((identifier) @variable.builtin
(#eq? @variable.builtin "self"))
(variable_list
(attribute
"<" @punctuation.bracket
(identifier) @attribute
">" @punctuation.bracket))
;; Constants
((identifier) @constant
(#match? @constant "^[A-Z][A-Z_0-9]*$"))
(vararg_expression) @constant
(nil) @constant.builtin
[
(false)
(true)
] @boolean
;; Tables
(field name: (identifier) @field)
(dot_index_expression field: (identifier) @field)
(table_constructor
[
"{"
"}"
] @constructor)
;; Functions
(parameters (identifier) @parameter)
(function_declaration
name: [
(identifier) @function
(dot_index_expression
field: (identifier) @function)
])
(function_declaration
name: (method_index_expression
method: (identifier) @method))
(assignment_statement
(variable_list .
name: [
(identifier) @function
(dot_index_expression
field: (identifier) @function)
])
(expression_list .
value: (function_definition)))
(table_constructor
(field
name: (identifier) @function
value: (function_definition)))
(function_call
name: [
(identifier) @function.call
(dot_index_expression
field: (identifier) @function.call)
(method_index_expression
method: (identifier) @method.call)
])
(function_call
(identifier) @function.builtin
(#any-of? @function.builtin
;; built-in functions in Lua 5.1
"assert" "collectgarbage" "dofile" "error" "getfenv" "getmetatable" "ipairs"
"load" "loadfile" "loadstring" "module" "next" "pairs" "pcall" "print"
"rawequal" "rawget" "rawset" "require" "select" "setfenv" "setmetatable"
"tonumber" "tostring" "type" "unpack" "xpcall"))
;; Others
(comment) @comment
(hash_bang_line) @preproc
(number) @number
(string) @string
(escape_sequence) @string.escape

@ -1,8 +0,0 @@
((function_call
name: [
(identifier) @_cdef_identifier
(_ _ (identifier) @_cdef_identifier)
]
arguments: (arguments (string content: _ @injection.content
(#set! injection.language "c"))))
(#eq? @_cdef_identifier "cdef"))

@ -1,36 +0,0 @@
; Scopes
[
(chunk)
(do_statement)
(while_statement)
(repeat_statement)
(if_statement)
(for_statement)
(function_declaration)
(function_definition)
] @local.scope
; Definitions
(assignment_statement
(variable_list
(identifier) @local.definition))
(function_declaration
name: (identifier) @local.definition)
(for_generic_clause
(variable_list
(identifier) @local.definition))
(for_numeric_clause
name: (identifier) @local.definition)
(parameters (identifier) @local.definition)
; References
[
(identifier)
] @local.reference

@ -1,34 +0,0 @@
(function_declaration
name: [
(identifier) @name
(dot_index_expression
field: (identifier) @name)
]) @definition.function
(function_declaration
name: (method_index_expression
method: (identifier) @name)) @definition.method
(assignment_statement
(variable_list .
name: [
(identifier) @name
(dot_index_expression
field: (identifier) @name)
])
(expression_list .
value: (function_definition))) @definition.function
(table_constructor
(field
name: (identifier) @name
value: (function_definition))) @definition.function
(function_call
name: [
(identifier) @name
(dot_index_expression
field: (identifier) @name)
(method_index_expression
method: (identifier) @name)
]) @reference.call

@ -1,57 +0,0 @@
from os.path import isdir, join
from platform import system
from setuptools import Extension, find_packages, setup
from setuptools.command.build import build
from wheel.bdist_wheel import bdist_wheel
class Build(build):
def run(self):
if isdir("queries"):
dest = join(self.build_lib, "tree_sitter_lua", "queries")
self.copy_tree("queries", dest)
super().run()
class BdistWheel(bdist_wheel):
def get_tag(self):
python, abi, platform = super().get_tag()
if python.startswith("cp"):
python, abi = "cp38", "abi3"
return python, abi, platform
setup(
packages=find_packages("bindings/python"),
package_dir={"": "bindings/python"},
package_data={
"tree_sitter_lua": ["*.pyi", "py.typed"],
"tree_sitter_lua.queries": ["*.scm"],
},
ext_package="tree_sitter_lua",
ext_modules=[
Extension(
name="_binding",
sources=[
"bindings/python/tree_sitter_lua/binding.c",
"src/parser.c",
"src/scanner.c",
],
extra_compile_args=(
["-std=c11"] if system() != 'Windows' else []
),
define_macros=[
("Py_LIMITED_API", "0x03080000"),
("PY_SSIZE_T_CLEAN", None)
],
include_dirs=["src"],
py_limited_api=True,
)
],
cmdclass={
"build": Build,
"bdist_wheel": BdistWheel
},
zip_safe=False
)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,194 +0,0 @@
#include <stdio.h>
#include <tree_sitter/parser.h>
#include <wctype.h>
enum TokenType {
BLOCK_COMMENT_START,
BLOCK_COMMENT_CONTENT,
BLOCK_COMMENT_END,
BLOCK_STRING_START,
BLOCK_STRING_CONTENT,
BLOCK_STRING_END,
};
static inline void consume(TSLexer *lexer) { lexer->advance(lexer, false); }
static inline void skip(TSLexer *lexer) { lexer->advance(lexer, true); }
static inline bool consume_char(char c, TSLexer *lexer) {
if (lexer->lookahead != c) {
return false;
}
consume(lexer);
return true;
}
static inline uint8_t consume_and_count_char(char c, TSLexer *lexer) {
uint8_t count = 0;
while (lexer->lookahead == c) {
++count;
consume(lexer);
}
return count;
}
static inline void skip_whitespaces(TSLexer *lexer) {
while (iswspace(lexer->lookahead)) {
skip(lexer);
}
}
typedef struct {
char ending_char;
uint8_t level_count;
} Scanner;
static inline void reset_state(Scanner *scanner) {
scanner->ending_char = 0;
scanner->level_count = 0;
}
void *tree_sitter_lua_external_scanner_create() {
Scanner *scanner = calloc(1, sizeof(Scanner));
return scanner;
}
void tree_sitter_lua_external_scanner_destroy(void *payload) {
Scanner *scanner = (Scanner *)payload;
free(scanner);
}
unsigned tree_sitter_lua_external_scanner_serialize(void *payload, char *buffer) {
Scanner *scanner = (Scanner *)payload;
buffer[0] = scanner->ending_char;
buffer[1] = (char)scanner->level_count;
return 2;
}
void tree_sitter_lua_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) {
Scanner *scanner = (Scanner *)payload;
if (length == 0) return;
scanner->ending_char = buffer[0];
if (length == 1) return;
scanner->level_count = buffer[1];
}
static bool scan_block_start(Scanner *scanner, TSLexer *lexer) {
if (consume_char('[', lexer)) {
uint8_t level = consume_and_count_char('=', lexer);
if (consume_char('[', lexer)) {
scanner->level_count = level;
return true;
}
}
return false;
}
static bool scan_block_end(Scanner *scanner, TSLexer *lexer) {
if (consume_char(']', lexer)) {
uint8_t level = consume_and_count_char('=', lexer);
if (scanner->level_count == level && consume_char(']', lexer)) {
return true;
}
}
return false;
}
static bool scan_block_content(Scanner *scanner, TSLexer *lexer) {
while (lexer->lookahead != 0) {
if (lexer->lookahead == ']') {
lexer->mark_end(lexer);
if (scan_block_end(scanner, lexer)) {
return true;
}
} else {
consume(lexer);
}
}
return false;
}
static bool scan_comment_start(Scanner *scanner, TSLexer *lexer) {
if (consume_char('-', lexer) && consume_char('-', lexer)) {
lexer->mark_end(lexer);
if (scan_block_start(scanner, lexer)) {
lexer->mark_end(lexer);
lexer->result_symbol = BLOCK_COMMENT_START;
return true;
}
}
return false;
}
static bool scan_comment_content(Scanner *scanner, TSLexer *lexer) {
if (scanner->ending_char == 0) { // block comment
if (scan_block_content(scanner, lexer)) {
lexer->result_symbol = BLOCK_COMMENT_CONTENT;
return true;
}
return false;
}
while (lexer->lookahead != 0) {
if (lexer->lookahead == scanner->ending_char) {
reset_state(scanner);
lexer->result_symbol = BLOCK_COMMENT_CONTENT;
return true;
}
consume(lexer);
}
return false;
}
bool tree_sitter_lua_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
Scanner *scanner = (Scanner *)payload;
if (valid_symbols[BLOCK_STRING_END] && scan_block_end(scanner, lexer)) {
reset_state(scanner);
lexer->result_symbol = BLOCK_STRING_END;
return true;
}
if (valid_symbols[BLOCK_STRING_CONTENT] && scan_block_content(scanner, lexer)) {
lexer->result_symbol = BLOCK_STRING_CONTENT;
return true;
}
if (valid_symbols[BLOCK_COMMENT_END] && scanner->ending_char == 0 && scan_block_end(scanner, lexer)) {
reset_state(scanner);
lexer->result_symbol = BLOCK_COMMENT_END;
return true;
}
if (valid_symbols[BLOCK_COMMENT_CONTENT] && scan_comment_content(scanner, lexer)) {
return true;
}
skip_whitespaces(lexer);
if (valid_symbols[BLOCK_STRING_START] && scan_block_start(scanner, lexer)) {
lexer->result_symbol = BLOCK_STRING_START;
return true;
}
if (valid_symbols[BLOCK_COMMENT_START]) {
if (scan_comment_start(scanner, lexer)) {
return true;
}
}
return false;
}

@ -1,54 +0,0 @@
#ifndef TREE_SITTER_ALLOC_H_
#define TREE_SITTER_ALLOC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// Allow clients to override allocation functions
#ifdef TREE_SITTER_REUSE_ALLOCATOR
extern void *(*ts_current_malloc)(size_t);
extern void *(*ts_current_calloc)(size_t, size_t);
extern void *(*ts_current_realloc)(void *, size_t);
extern void (*ts_current_free)(void *);
#ifndef ts_malloc
#define ts_malloc ts_current_malloc
#endif
#ifndef ts_calloc
#define ts_calloc ts_current_calloc
#endif
#ifndef ts_realloc
#define ts_realloc ts_current_realloc
#endif
#ifndef ts_free
#define ts_free ts_current_free
#endif
#else
#ifndef ts_malloc
#define ts_malloc malloc
#endif
#ifndef ts_calloc
#define ts_calloc calloc
#endif
#ifndef ts_realloc
#define ts_realloc realloc
#endif
#ifndef ts_free
#define ts_free free
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_ALLOC_H_

@ -1,287 +0,0 @@
#ifndef TREE_SITTER_ARRAY_H_
#define TREE_SITTER_ARRAY_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "./alloc.h"
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#pragma warning(disable : 4101)
#elif defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
#define Array(T) \
struct { \
T *contents; \
uint32_t size; \
uint32_t capacity; \
}
/// Initialize an array.
#define array_init(self) \
((self)->size = 0, (self)->capacity = 0, (self)->contents = NULL)
/// Create an empty array.
#define array_new() \
{ NULL, 0, 0 }
/// Get a pointer to the element at a given `index` in the array.
#define array_get(self, _index) \
(assert((uint32_t)(_index) < (self)->size), &(self)->contents[_index])
/// Get a pointer to the first element in the array.
#define array_front(self) array_get(self, 0)
/// Get a pointer to the last element in the array.
#define array_back(self) array_get(self, (self)->size - 1)
/// Clear the array, setting its size to zero. Note that this does not free any
/// memory allocated for the array's contents.
#define array_clear(self) ((self)->size = 0)
/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is
/// less than the array's current capacity, this function has no effect.
#define array_reserve(self, new_capacity) \
_array__reserve((Array *)(self), array_elem_size(self), new_capacity)
/// Free any memory allocated for this array. Note that this does not free any
/// memory allocated for the array's contents.
#define array_delete(self) _array__delete((Array *)(self))
/// Push a new `element` onto the end of the array.
#define array_push(self, element) \
(_array__grow((Array *)(self), 1, array_elem_size(self)), \
(self)->contents[(self)->size++] = (element))
/// Increase the array's size by `count` elements.
/// New elements are zero-initialized.
#define array_grow_by(self, count) \
(_array__grow((Array *)(self), count, array_elem_size(self)), \
memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)), \
(self)->size += (count))
/// Append all elements from one array to the end of another.
#define array_push_all(self, other) \
array_extend((self), (other)->size, (other)->contents)
/// Append `count` elements to the end of the array, reading their values from the
/// `contents` pointer.
#define array_extend(self, count, contents) \
_array__splice( \
(Array *)(self), array_elem_size(self), (self)->size, \
0, count, contents \
)
/// Remove `old_count` elements from the array starting at the given `index`. At
/// the same index, insert `new_count` new elements, reading their values from the
/// `new_contents` pointer.
#define array_splice(self, _index, old_count, new_count, new_contents) \
_array__splice( \
(Array *)(self), array_elem_size(self), _index, \
old_count, new_count, new_contents \
)
/// Insert one `element` into the array at the given `index`.
#define array_insert(self, _index, element) \
_array__splice((Array *)(self), array_elem_size(self), _index, 0, 1, &(element))
/// Remove one element from the array at the given `index`.
#define array_erase(self, _index) \
_array__erase((Array *)(self), array_elem_size(self), _index)
/// Pop the last element off the array, returning the element by value.
#define array_pop(self) ((self)->contents[--(self)->size])
/// Assign the contents of one array to another, reallocating if necessary.
#define array_assign(self, other) \
_array__assign((Array *)(self), (const Array *)(other), array_elem_size(self))
/// Swap one array with another
#define array_swap(self, other) \
_array__swap((Array *)(self), (Array *)(other))
/// Get the size of the array contents
#define array_elem_size(self) (sizeof *(self)->contents)
/// Search a sorted array for a given `needle` value, using the given `compare`
/// callback to determine the order.
///
/// If an existing element is found to be equal to `needle`, then the `index`
/// out-parameter is set to the existing value's index, and the `exists`
/// out-parameter is set to true. Otherwise, `index` is set to an index where
/// `needle` should be inserted in order to preserve the sorting, and `exists`
/// is set to false.
#define array_search_sorted_with(self, compare, needle, _index, _exists) \
_array__search_sorted(self, 0, compare, , needle, _index, _exists)
/// Search a sorted array for a given `needle` value, using integer comparisons
/// of a given struct field (specified with a leading dot) to determine the order.
///
/// See also `array_search_sorted_with`.
#define array_search_sorted_by(self, field, needle, _index, _exists) \
_array__search_sorted(self, 0, _compare_int, field, needle, _index, _exists)
/// Insert a given `value` into a sorted array, using the given `compare`
/// callback to determine the order.
#define array_insert_sorted_with(self, compare, value) \
do { \
unsigned _index, _exists; \
array_search_sorted_with(self, compare, &(value), &_index, &_exists); \
if (!_exists) array_insert(self, _index, value); \
} while (0)
/// Insert a given `value` into a sorted array, using integer comparisons of
/// a given struct field (specified with a leading dot) to determine the order.
///
/// See also `array_search_sorted_by`.
#define array_insert_sorted_by(self, field, value) \
do { \
unsigned _index, _exists; \
array_search_sorted_by(self, field, (value) field, &_index, &_exists); \
if (!_exists) array_insert(self, _index, value); \
} while (0)
// Private
typedef Array(void) Array;
/// This is not what you're looking for, see `array_delete`.
static inline void _array__delete(Array *self) {
if (self->contents) {
ts_free(self->contents);
self->contents = NULL;
self->size = 0;
self->capacity = 0;
}
}
/// This is not what you're looking for, see `array_erase`.
static inline void _array__erase(Array *self, size_t element_size,
uint32_t index) {
assert(index < self->size);
char *contents = (char *)self->contents;
memmove(contents + index * element_size, contents + (index + 1) * element_size,
(self->size - index - 1) * element_size);
self->size--;
}
/// This is not what you're looking for, see `array_reserve`.
static inline void _array__reserve(Array *self, size_t element_size, uint32_t new_capacity) {
if (new_capacity > self->capacity) {
if (self->contents) {
self->contents = ts_realloc(self->contents, new_capacity * element_size);
} else {
self->contents = ts_malloc(new_capacity * element_size);
}
self->capacity = new_capacity;
}
}
/// This is not what you're looking for, see `array_assign`.
static inline void _array__assign(Array *self, const Array *other, size_t element_size) {
_array__reserve(self, element_size, other->size);
self->size = other->size;
memcpy(self->contents, other->contents, self->size * element_size);
}
/// This is not what you're looking for, see `array_swap`.
static inline void _array__swap(Array *self, Array *other) {
Array swap = *other;
*other = *self;
*self = swap;
}
/// This is not what you're looking for, see `array_push` or `array_grow_by`.
static inline void _array__grow(Array *self, uint32_t count, size_t element_size) {
uint32_t new_size = self->size + count;
if (new_size > self->capacity) {
uint32_t new_capacity = self->capacity * 2;
if (new_capacity < 8) new_capacity = 8;
if (new_capacity < new_size) new_capacity = new_size;
_array__reserve(self, element_size, new_capacity);
}
}
/// This is not what you're looking for, see `array_splice`.
static inline void _array__splice(Array *self, size_t element_size,
uint32_t index, uint32_t old_count,
uint32_t new_count, const void *elements) {
uint32_t new_size = self->size + new_count - old_count;
uint32_t old_end = index + old_count;
uint32_t new_end = index + new_count;
assert(old_end <= self->size);
_array__reserve(self, element_size, new_size);
char *contents = (char *)self->contents;
if (self->size > old_end) {
memmove(
contents + new_end * element_size,
contents + old_end * element_size,
(self->size - old_end) * element_size
);
}
if (new_count > 0) {
if (elements) {
memcpy(
(contents + index * element_size),
elements,
new_count * element_size
);
} else {
memset(
(contents + index * element_size),
0,
new_count * element_size
);
}
}
self->size += new_count - old_count;
}
/// A binary search routine, based on Rust's `std::slice::binary_search_by`.
/// This is not what you're looking for, see `array_search_sorted_with` or `array_search_sorted_by`.
#define _array__search_sorted(self, start, compare, suffix, needle, _index, _exists) \
do { \
*(_index) = start; \
*(_exists) = false; \
uint32_t size = (self)->size - *(_index); \
if (size == 0) break; \
int comparison; \
while (size > 1) { \
uint32_t half_size = size / 2; \
uint32_t mid_index = *(_index) + half_size; \
comparison = compare(&((self)->contents[mid_index] suffix), (needle)); \
if (comparison <= 0) *(_index) = mid_index; \
size -= half_size; \
} \
comparison = compare(&((self)->contents[*(_index)] suffix), (needle)); \
if (comparison == 0) *(_exists) = true; \
else if (comparison < 0) *(_index) += 1; \
} while (0)
/// Helper macro for the `_sorted_by` routines below. This takes the left (existing)
/// parameter by reference in order to work with the generic sorting function above.
#define _compare_int(a, b) ((int)*(a) - (int)(b))
#ifdef _MSC_VER
#pragma warning(default : 4101)
#elif defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_ARRAY_H_

@ -1,230 +0,0 @@
#ifndef TREE_SITTER_PARSER_H_
#define TREE_SITTER_PARSER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#define ts_builtin_sym_error ((TSSymbol)-1)
#define ts_builtin_sym_end 0
#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024
#ifndef TREE_SITTER_API_H_
typedef uint16_t TSStateId;
typedef uint16_t TSSymbol;
typedef uint16_t TSFieldId;
typedef struct TSLanguage TSLanguage;
#endif
typedef struct {
TSFieldId field_id;
uint8_t child_index;
bool inherited;
} TSFieldMapEntry;
typedef struct {
uint16_t index;
uint16_t length;
} TSFieldMapSlice;
typedef struct {
bool visible;
bool named;
bool supertype;
} TSSymbolMetadata;
typedef struct TSLexer TSLexer;
struct TSLexer {
int32_t lookahead;
TSSymbol result_symbol;
void (*advance)(TSLexer *, bool);
void (*mark_end)(TSLexer *);
uint32_t (*get_column)(TSLexer *);
bool (*is_at_included_range_start)(const TSLexer *);
bool (*eof)(const TSLexer *);
};
typedef enum {
TSParseActionTypeShift,
TSParseActionTypeReduce,
TSParseActionTypeAccept,
TSParseActionTypeRecover,
} TSParseActionType;
typedef union {
struct {
uint8_t type;
TSStateId state;
bool extra;
bool repetition;
} shift;
struct {
uint8_t type;
uint8_t child_count;
TSSymbol symbol;
int16_t dynamic_precedence;
uint16_t production_id;
} reduce;
uint8_t type;
} TSParseAction;
typedef struct {
uint16_t lex_state;
uint16_t external_lex_state;
} TSLexMode;
typedef union {
TSParseAction action;
struct {
uint8_t count;
bool reusable;
} entry;
} TSParseActionEntry;
struct TSLanguage {
uint32_t version;
uint32_t symbol_count;
uint32_t alias_count;
uint32_t token_count;
uint32_t external_token_count;
uint32_t state_count;
uint32_t large_state_count;
uint32_t production_id_count;
uint32_t field_count;
uint16_t max_alias_sequence_length;
const uint16_t *parse_table;
const uint16_t *small_parse_table;
const uint32_t *small_parse_table_map;
const TSParseActionEntry *parse_actions;
const char * const *symbol_names;
const char * const *field_names;
const TSFieldMapSlice *field_map_slices;
const TSFieldMapEntry *field_map_entries;
const TSSymbolMetadata *symbol_metadata;
const TSSymbol *public_symbol_map;
const uint16_t *alias_map;
const TSSymbol *alias_sequences;
const TSLexMode *lex_modes;
bool (*lex_fn)(TSLexer *, TSStateId);
bool (*keyword_lex_fn)(TSLexer *, TSStateId);
TSSymbol keyword_capture_token;
struct {
const bool *states;
const TSSymbol *symbol_map;
void *(*create)(void);
void (*destroy)(void *);
bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist);
unsigned (*serialize)(void *, char *);
void (*deserialize)(void *, const char *, unsigned);
} external_scanner;
const TSStateId *primary_state_ids;
};
/*
* Lexer Macros
*/
#ifdef _MSC_VER
#define UNUSED __pragma(warning(suppress : 4101))
#else
#define UNUSED __attribute__((unused))
#endif
#define START_LEXER() \
bool result = false; \
bool skip = false; \
UNUSED \
bool eof = false; \
int32_t lookahead; \
goto start; \
next_state: \
lexer->advance(lexer, skip); \
start: \
skip = false; \
lookahead = lexer->lookahead;
#define ADVANCE(state_value) \
{ \
state = state_value; \
goto next_state; \
}
#define SKIP(state_value) \
{ \
skip = true; \
state = state_value; \
goto next_state; \
}
#define ACCEPT_TOKEN(symbol_value) \
result = true; \
lexer->result_symbol = symbol_value; \
lexer->mark_end(lexer);
#define END_STATE() return result;
/*
* Parse Table Macros
*/
#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT)
#define STATE(id) id
#define ACTIONS(id) id
#define SHIFT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = (state_value) \
} \
}}
#define SHIFT_REPEAT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = (state_value), \
.repetition = true \
} \
}}
#define SHIFT_EXTRA() \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.extra = true \
} \
}}
#define REDUCE(symbol_val, child_count_val, ...) \
{{ \
.reduce = { \
.type = TSParseActionTypeReduce, \
.symbol = symbol_val, \
.child_count = child_count_val, \
__VA_ARGS__ \
}, \
}}
#define RECOVER() \
{{ \
.type = TSParseActionTypeRecover \
}}
#define ACCEPT_INPUT() \
{{ \
.type = TSParseActionTypeAccept \
}}
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_PARSER_H_

@ -1,42 +0,0 @@
================================================================================
chunk
================================================================================
--------------------------------------------------------------------------------
(chunk)
================================================================================
hash_bang_line
================================================================================
#!/usr/bin/env lua
--------------------------------------------------------------------------------
(chunk
(hash_bang_line))
================================================================================
hash_bang_line: ignored first line
================================================================================
# ignored first line
--------------------------------------------------------------------------------
(chunk
(hash_bang_line))
================================================================================
return_statement
================================================================================
return 42
--------------------------------------------------------------------------------
(chunk
(return_statement
(expression_list
(number))))

@ -1,102 +0,0 @@
================================================================================
comment
================================================================================
--
-- single-line comment, below an empty single-line comment
--[[]]
--[[
print("block comment")
--]]
--[[
print("block comment")
]]
-- [[
print("not block comment")
--]]
--[=[[print("level 1 block comment")]]=]
--[=[
[print("level 1 block comment")]
]=]
--[=[
[print("level 1 block comment")
]=]
--[=[
print("level 1 block comment")]
]=]
--[=[
[[print("level 1 block comment")
]=]
--[=[
print("level 1 block comment")]]
]=]
--[==[
print("level 2 block comment")
-- ]==]
--[==[
print("level 2 block comment")
]==]
-- [==[
print("not level 2 block comment")
--]==]
--------------------------------------------------------------------------------
(chunk
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(function_call
name: (identifier)
arguments: (arguments
(string
content: (string_content))))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(comment
content: (comment_content))
(function_call
name: (identifier)
arguments: (arguments
(string
content: (string_content))))
(comment
content: (comment_content)))

@ -1,673 +0,0 @@
================================================================================
nil
================================================================================
exp(nil)
--------------------------------------------------------------------------------
(chunk
(function_call
name: (identifier)
arguments: (arguments
(nil))))
================================================================================
false
================================================================================
exp(false)
--------------------------------------------------------------------------------
(chunk
(function_call
name: (identifier)
arguments: (arguments
(false))))
================================================================================
true
================================================================================
exp(true)
--------------------------------------------------------------------------------
(chunk
(function_call
name: (identifier)
arguments: (arguments
(true))))
================================================================================
number
================================================================================
exp(
3,
345,
0xff,
0xBEBADA,
.0,
3.,
3.0,
3.1416,
314.16e-2,
0.31416E1,
34e1,
0x0.1E,
0xA23p-4,
0x.0p-3,
0x.FfffFFFF,
0X1.921FB54442D18P+1,
42LL,
0x2aULL,
12.5i,
0x.01p-1I
)
--------------------------------------------------------------------------------
(chunk
(function_call
name: (identifier)
arguments: (arguments
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number)
(number))))
================================================================================
string
================================================================================
exp(
"string",
'string',
"c",
'c',
"0",
[[ string ]],
[[
string
string
]],
[=[
string
string
]=],
[=[[string]]=],
[=[
[string]
]=],
[=[
[string
]=],
[=[
string]
]=],
[=[
[[string
]=],
[=[
string]]
]=]
)
--------------------------------------------------------------------------------
(chunk
(function_call
(identifier)
(arguments
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content))
(string
(string_content)))))
================================================================================
string :: escape_sequence
================================================================================
exp(
"a\
b",
'a\z',
'a\z
',
'a\z
b',
"'a\z\
b'"
)
--------------------------------------------------------------------------------
(chunk
(function_call
name: (identifier)
arguments: (arguments
(string
content: (string_content
(escape_sequence)))
(string
content: (string_content
(escape_sequence)))
(string
content: (string_content
(escape_sequence)))
(string
content: (string_content
(escape_sequence)))
(string
content: (string_content
(escape_sequence)
(escape_sequence))))))
================================================================================
vararg_expression
================================================================================
exp(...)
--------------------------------------------------------------------------------
(chunk
(function_call
name: (identifier)
arguments: (arguments
(vararg_expression))))
================================================================================
function_definition
================================================================================
f1 = function() end
f2 = function() return end
f3 = function(...)
return ...
end
f4 = function(a1, ...)
print(...)
return a1
end
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (function_definition
parameters: (parameters))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (function_definition
parameters: (parameters)
body: (block
(return_statement)))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (function_definition
parameters: (parameters
(vararg_expression))
body: (block
(return_statement
(expression_list
(vararg_expression)))))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (function_definition
parameters: (parameters
name: (identifier)
(vararg_expression))
body: (block
(function_call
name: (identifier)
arguments: (arguments
(vararg_expression)))
(return_statement
(expression_list
(identifier))))))))
================================================================================
variable ::: identifier
================================================================================
v1 = n1
v2, v3 = n2, n3
পাই = π
🙂 = 🙃
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (identifier)))
(assignment_statement
(variable_list
name: (identifier)
name: (identifier))
(expression_list
value: (identifier)
value: (identifier)))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (identifier)))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (identifier))))
================================================================================
variable ::: bracket_index_expression
================================================================================
v1 = tbl[k1]
v2, v3[v] = tbl[k1]["k2"]
v4 = tbk[getK1()][getK2()]
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (bracket_index_expression
table: (identifier)
field: (identifier))))
(assignment_statement
(variable_list
name: (identifier)
name: (bracket_index_expression
table: (identifier)
field: (identifier)))
(expression_list
value: (bracket_index_expression
table: (bracket_index_expression
table: (identifier)
field: (identifier))
field: (string
content: (string_content)))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (bracket_index_expression
table: (bracket_index_expression
table: (identifier)
field: (function_call
name: (identifier)
arguments: (arguments)))
field: (function_call
name: (identifier)
arguments: (arguments))))))
================================================================================
variable ::: dot_index_expression
================================================================================
v1 = tbl.k1
v2 = tbl.k1.k2
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (dot_index_expression
table: (identifier)
field: (identifier))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (dot_index_expression
table: (dot_index_expression
table: (identifier)
field: (identifier))
field: (identifier)))))
================================================================================
function_call ::: bracket_index_expression | dot_index_expression
================================================================================
v1 = tbl[k1].k2(a1, "a2", a3())
v2 = tbl[k1] { f1 = true }
v3 = tbl[k1] "a1"
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (function_call
name: (dot_index_expression
table: (bracket_index_expression
table: (identifier)
field: (identifier))
field: (identifier))
arguments: (arguments
(identifier)
(string
content: (string_content))
(function_call
name: (identifier)
arguments: (arguments))))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (function_call
name: (bracket_index_expression
table: (identifier)
field: (identifier))
arguments: (arguments
(table_constructor
(field
name: (identifier)
value: (true)))))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (function_call
name: (bracket_index_expression
table: (identifier)
field: (identifier))
arguments: (arguments
(string
content: (string_content)))))))
================================================================================
function_call ::: method_index_expression
================================================================================
tbl.k1:m1(a1, "a2")
tbl[k1]:m1 { f1, "f2" }
tbl:m1 "a1"
--------------------------------------------------------------------------------
(chunk
(function_call
name: (method_index_expression
table: (dot_index_expression
table: (identifier)
field: (identifier))
method: (identifier))
arguments: (arguments
(identifier)
(string
content: (string_content))))
(function_call
name: (method_index_expression
table: (bracket_index_expression
table: (identifier)
field: (identifier))
method: (identifier))
arguments: (arguments
(table_constructor
(field
value: (identifier))
(field
value: (string
content: (string_content))))))
(function_call
name: (method_index_expression
table: (identifier)
method: (identifier))
arguments: (arguments
(string
content: (string_content)))))
================================================================================
parenthesized_expression
================================================================================
v = ( true )
v = ( ( false ) )
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (parenthesized_expression
(true))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (parenthesized_expression
(parenthesized_expression
(false))))))
================================================================================
table_constructor
================================================================================
tbl1 = {
["k1"] = {
['k2'] = true,
k3 = false
}
}
local tbl2 = {
k1 = {
{ 'v1', "v2" }
}
}
local tbl3 = { "v1", k1 = "v2" }
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (table_constructor
(field
name: (string
content: (string_content))
value: (table_constructor
(field
name: (string
content: (string_content))
value: (true))
(field
name: (identifier)
value: (false)))))))
local_declaration: (variable_declaration
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (table_constructor
(field
name: (identifier)
value: (table_constructor
(field
value: (table_constructor
(field
value: (string
content: (string_content)))
(field
value: (string
content: (string_content)))))))))))
local_declaration: (variable_declaration
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (table_constructor
(field
value: (string
content: (string_content)))
(field
name: (identifier)
value: (string
content: (string_content))))))))
================================================================================
binary_expression
================================================================================
a = i + j * 3 - k % 5
b = i + j % 3 ^ 2
c = i * 2 ^ j
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (binary_expression
left: (binary_expression
left: (identifier)
right: (binary_expression
left: (identifier)
right: (number)))
right: (binary_expression
left: (identifier)
right: (number)))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (binary_expression
left: (identifier)
right: (binary_expression
left: (identifier)
right: (binary_expression
left: (number)
right: (number))))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (binary_expression
left: (identifier)
right: (binary_expression
left: (number)
right: (identifier))))))
================================================================================
unary_expression
================================================================================
v1 = #l
v2 = -n
v3 = not c1 and r1 or r2
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (unary_expression
operand: (identifier))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (unary_expression
operand: (identifier))))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (binary_expression
left: (binary_expression
left: (unary_expression
operand: (identifier))
right: (identifier))
right: (identifier)))))

@ -1,502 +0,0 @@
================================================================================
empty_statement
================================================================================
;
;;
--------------------------------------------------------------------------------
(chunk
(empty_statement)
(empty_statement)
(empty_statement))
================================================================================
assignment_statement
================================================================================
i = 1
j, tbl[k()] = 2, i + 1
x, y = y, x
--------------------------------------------------------------------------------
(chunk
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (number)))
(assignment_statement
(variable_list
name: (identifier)
name: (bracket_index_expression
table: (identifier)
field: (function_call
name: (identifier)
arguments: (arguments))))
(expression_list
value: (number)
value: (binary_expression
left: (identifier)
right: (number))))
(assignment_statement
(variable_list
name: (identifier)
name: (identifier))
(expression_list
value: (identifier)
value: (identifier))))
================================================================================
function_call
================================================================================
f1()
tbl.f2()
tbl["f2"]()
tbl.k1:f3()
f4(a1)("a2") { a3 = "a3" }
--------------------------------------------------------------------------------
(chunk
(function_call
name: (identifier)
arguments: (arguments))
(function_call
name: (dot_index_expression
table: (identifier)
field: (identifier))
arguments: (arguments))
(function_call
name: (bracket_index_expression
table: (identifier)
field: (string
content: (string_content)))
arguments: (arguments))
(function_call
name: (method_index_expression
table: (dot_index_expression
table: (identifier)
field: (identifier))
method: (identifier))
arguments: (arguments))
(function_call
name: (function_call
name: (function_call
name: (identifier)
arguments: (arguments
(identifier)))
arguments: (arguments
(string
content: (string_content))))
arguments: (arguments
(table_constructor
(field
name: (identifier)
value: (string
content: (string_content)))))))
================================================================================
label_statement
================================================================================
:: label_name ::
--------------------------------------------------------------------------------
(chunk
(label_statement
(identifier)))
================================================================================
break_statement
================================================================================
for k, v in pairs(kv) do
if not v then
break
end
end
--------------------------------------------------------------------------------
(chunk
(for_statement
clause: (for_generic_clause
(variable_list
name: (identifier)
name: (identifier))
(expression_list
(function_call
name: (identifier)
arguments: (arguments
(identifier)))))
body: (block
(if_statement
condition: (unary_expression
operand: (identifier))
consequence: (block
(break_statement))))))
================================================================================
goto_statement
================================================================================
goto label_name
--------------------------------------------------------------------------------
(chunk
(goto_statement
(identifier)))
================================================================================
do_statement
================================================================================
do
f1()
return f2()
end
do end
--------------------------------------------------------------------------------
(chunk
(do_statement
body: (block
(function_call
name: (identifier)
arguments: (arguments))
(return_statement
(expression_list
(function_call
name: (identifier)
arguments: (arguments))))))
(do_statement))
================================================================================
while_statement
================================================================================
while i < 9 do
i = i + 1
end
while false do end
--------------------------------------------------------------------------------
(chunk
(while_statement
condition: (binary_expression
left: (identifier)
right: (number))
body: (block
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (binary_expression
left: (identifier)
right: (number))))))
(while_statement
condition: (false)))
================================================================================
repeat_statement
================================================================================
repeat
f1()
i = i - 1
until i == 0
repeat until false
--------------------------------------------------------------------------------
(chunk
(repeat_statement
body: (block
(function_call
name: (identifier)
arguments: (arguments))
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (binary_expression
left: (identifier)
right: (number)))))
condition: (binary_expression
left: (identifier)
right: (number)))
(repeat_statement
condition: (false)))
================================================================================
if_statement
================================================================================
if num % 2 == 0 then
print("even")
elseif num % 2 ~= 0 then
print("odd")
else
error("!")
end
if c1 then end
if c1 then else end
if c1 then elseif c2 then else end
--------------------------------------------------------------------------------
(chunk
(if_statement
condition: (binary_expression
left: (binary_expression
left: (identifier)
right: (number))
right: (number))
consequence: (block
(function_call
name: (identifier)
arguments: (arguments
(string
content: (string_content)))))
alternative: (elseif_statement
condition: (binary_expression
left: (binary_expression
left: (identifier)
right: (number))
right: (number))
consequence: (block
(function_call
name: (identifier)
arguments: (arguments
(string
content: (string_content))))))
alternative: (else_statement
body: (block
(function_call
name: (identifier)
arguments: (arguments
(string
content: (string_content)))))))
(if_statement
condition: (identifier))
(if_statement
condition: (identifier)
alternative: (else_statement))
(if_statement
condition: (identifier)
alternative: (elseif_statement
condition: (identifier))
alternative: (else_statement)))
================================================================================
for_statement ::: for_generic_clause
================================================================================
for k, v in pairs(kv) do
print(k, v)
end
for i in ipairs(iv) do end
--------------------------------------------------------------------------------
(chunk
(for_statement
clause: (for_generic_clause
(variable_list
name: (identifier)
name: (identifier))
(expression_list
(function_call
name: (identifier)
arguments: (arguments
(identifier)))))
body: (block
(function_call
name: (identifier)
arguments: (arguments
(identifier)
(identifier)))))
(for_statement
clause: (for_generic_clause
(variable_list
name: (identifier))
(expression_list
(function_call
name: (identifier)
arguments: (arguments
(identifier)))))))
================================================================================
for_statement ::: for_numeric_clause
================================================================================
for n = 1, 10 do
print(n)
end
for n = 1, 10, 2 do end
--------------------------------------------------------------------------------
(chunk
(for_statement
clause: (for_numeric_clause
name: (identifier)
start: (number)
end: (number))
body: (block
(function_call
name: (identifier)
arguments: (arguments
(identifier)))))
(for_statement
clause: (for_numeric_clause
name: (identifier)
start: (number)
end: (number)
step: (number))))
================================================================================
function_declaration
================================================================================
function tbl.f1() end
function tbl:f2() end
function tbl.k1:f3() end
function f4()
print('f4')
end
local function f5() end
--------------------------------------------------------------------------------
(chunk
(function_declaration
name: (dot_index_expression
table: (identifier)
field: (identifier))
parameters: (parameters))
(function_declaration
name: (method_index_expression
table: (identifier)
method: (identifier))
parameters: (parameters))
(function_declaration
name: (method_index_expression
table: (dot_index_expression
table: (identifier)
field: (identifier))
method: (identifier))
parameters: (parameters))
(function_declaration
name: (identifier)
parameters: (parameters)
body: (block
(function_call
name: (identifier)
arguments: (arguments
(string
content: (string_content))))))
local_declaration: (function_declaration
name: (identifier)
parameters: (parameters)))
================================================================================
variable_declaration
================================================================================
local v1 = 1
local v2, v3 = 2, 3
local v4, v4 = f1(), tbl:f2()
--------------------------------------------------------------------------------
(chunk
local_declaration: (variable_declaration
(assignment_statement
(variable_list
name: (identifier))
(expression_list
value: (number))))
local_declaration: (variable_declaration
(assignment_statement
(variable_list
name: (identifier)
name: (identifier))
(expression_list
value: (number)
value: (number))))
local_declaration: (variable_declaration
(assignment_statement
(variable_list
name: (identifier)
name: (identifier))
(expression_list
value: (function_call
name: (identifier)
arguments: (arguments))
value: (function_call
name: (method_index_expression
table: (identifier)
method: (identifier))
arguments: (arguments))))))
================================================================================
variable_declaration ::: attribute [Lua 5.4]
================================================================================
local c <const>, x <const> = 42
local f <close> = io.open('/file.lua')
--------------------------------------------------------------------------------
(chunk
local_declaration: (variable_declaration
(assignment_statement
(variable_list
name: (identifier)
attribute: (attribute
(identifier))
name: (identifier)
attribute: (attribute
(identifier)))
(expression_list
value: (number))))
local_declaration: (variable_declaration
(assignment_statement
(variable_list
name: (identifier)
attribute: (attribute
(identifier)))
(expression_list
value: (function_call
name: (dot_index_expression
table: (identifier)
field: (identifier))
arguments: (arguments
(string
content: (string_content))))))))

@ -1,59 +0,0 @@
-- stylua: ignore start
local _
_ = "x"
-- ^ string
_ = 'x'
-- ^ string
_ = "x\ty"
-- ^ string
-- ^ string.escape
-- ^ string.escape
-- ^ string
_ = "x\"y"
-- ^ string
-- ^ string.escape
-- ^ string.escape
-- ^ string
_ = 'x\'y'
-- ^ string
-- ^ string.escape
-- ^ string.escape
-- ^ string
_ = "x\z
y"
-- ^ string
--<- string.escape
_ = "x\x5Ay"
-- ^ string.escape
-- ^ string.escape
_ = "x\0900y"
-- ^ string.escape
-- ^ string
_ = "x\09y"
-- ^ string.escape
-- ^ string
_ = "x\0y"
-- ^ string.escape
-- ^ string
_ = "x\u{1f602}y"
-- ^ string.escape
-- ^ string.escape
-- ^ string
_ = [[x]]
-- ^ string
_ = [=[x]=]
-- ^ string

@ -1,37 +0,0 @@
local function func_one() end
-- ^ definition.function
func_one()
-- ^ reference.call
local func_two = function() end
-- ^ definition.function
func_two()
-- ^ reference.call
local tbl = {
func_one = function() end,
-- ^ definition.function
}
tbl.func_one()
-- ^ reference.call
function tbl.func_two() end
-- ^ definition.function
tbl.func_two()
-- ^ reference.call
function tbl:func_three() end
-- ^ definition.method
tbl:func_three()
-- ^ reference.call
tbl.func_four = function() end
-- ^ definition.function
tbl.func_four()
-- ^ reference.call