Add 'vendor/tree-sitter-lua/' from commit '6f5d40190ec8a0aa8c8410699353d820f4f7d7a6'

git-subtree-dir: vendor/tree-sitter-lua
git-subtree-mainline: f26ca24df7
git-subtree-split: 6f5d40190e
pull/188/head
JafarAbdi 2022-03-28 18:07:10 +07:00
commit 02fd04189c
26 changed files with 52416 additions and 0 deletions

@ -0,0 +1,10 @@
# EditorConfig is awesome: http://EditorConfig.org
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf

@ -0,0 +1,15 @@
# dependencies
/node_modules
# testing
/parser.exp
/parser.lib
/parser.obj
/scanner.obj
# production
/build
# misc
.DS_Store
*.log

@ -0,0 +1,32 @@
language: node_js
sudo: false
node_js:
- 10
os:
- linux
matrix:
include:
- os: osx
- os: linux
env: CXX=clang++
branches:
only:
- master
- "/^v.*$/"
deploy:
provider: script
script: npm run dist && npm run dist:upload -u ${PREBUILD_UPLOAD}
skip_cleanup: true
on:
all_branches: true
tags: true
env:
global:
secure: E3vAruj6QzWt/bGJQoyM2qt0Ei1yECV/itm2WTg2QJp2pf/eyaUT9EzZUKhrglMNerFtMjrJjnQF+PLeq/JVOutDZz+rkmArmhoQqg7+qINYXNAlwUO0Rmr372KD0b6h+GRBBkiGuTSZHM5BtAc8GQnRoAkAu4aAD87oOKXpjENokkeBvdzGFX3SUcYt+CJ65dP76TOgf5Hy91d5kpuPd8e9U5wgq/LsErwFr1KmEl3ADgX5m1Xpoxb5+fZN/eNf63HcwV+Gk+G466cvyESy6F7KDGRWhToNqJvTyh8cAOJIeVpatwiq4P3DUmiQBNhRX1ZdNBsu1EFbN/Gd9Sy4IRN8rU3DNjKCS8FKP4gMBmUnVPLR4qOhtNfGaaaLObmcjwplGhRQlAe7n4YDfXrV/Nony0UpwwRmf76YLHUWNsMJ2b1yPRmGyLQjz5Vt7s5XJXe9gv/X7Nb2e7R1C2Ek4pJtjrmL5xBssdKWWinwPLwrhrdIlwI5GQmJeO0O5b6+TMR0S/8/VgbjmSWNkLANUZGCafod8Swk9VbOuIOIYaqE5c37UyiY/Oc8w0vw3PMm33FTQg0SV7R7dCDExLP7CknmUsUi4xNkXCNoMHLLE9OAUWP5S/yZA/ok6CCfHXk8HR+dyOiVNWZtU/HjETuAYheCkayreJSvKIHSIrzpPhs=

@ -0,0 +1,25 @@
[package]
name = "tree-sitter-lua"
description = "lua grammar for the tree-sitter parsing library"
version = "0.0.1"
keywords = ["incremental", "parsing", "lua"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/tree-sitter/tree-sitter-javascript"
edition = "2018"
build = "bindings/rust/build.rs"
include = [
"bindings/rust/*",
"grammar.js",
"queries/*",
"src/*",
]
[lib]
path = "bindings/rust/lib.rs"
[dependencies]
tree-sitter = "0.19"
[build-dependencies]
cc = "1.0"

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Ademir J. Ferreira Junior
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.

@ -0,0 +1,15 @@
# tree-sitter-lua
[![Build Status](https://travis-ci.org/Azganoth/tree-sitter-lua.svg?branch=master)](https://travis-ci.org/Azganoth/tree-sitter-lua)
[![Build status](https://ci.appveyor.com/api/projects/status/8rnu3n839orxosys/branch/master?svg=true)](https://ci.appveyor.com/project/Azganoth/tree-sitter-lua/branch/master)
Lua grammar for tree-sitter.
## References
- [Lua Documentation](https://www.lua.org/docs.html)
- [Lua 5.3 Reference Manual](https://www.lua.org/manual/5.3/)
## License
This package is under a [MIT license](https://github.com/Azganoth/tree-sitter-lua/blob/master/LICENSE.md).

@ -0,0 +1,28 @@
image: Visual Studio 2015
environment:
NODEJS_VERSION: "10"
PREBUILD_UPLOAD:
secure: wFXEkNtRRO23ArXLq0wwWb77936/rCD4Pquty4hHH9wSdOZftPSvveLZvNbwWf2N
platform:
- x64
- x86
install:
- ps: Install-Product node $env:NODEJS_VERSION $env:Platform
- node --version
- npm --version
- npm install
test_script:
- npm run test
build: off
branches:
only:
- master
- /^v.*$/
deploy_script: IF "%APPVEYOR_REPO_TAG%" == "true" (npm run dist && npm run dist:upload -u %PREBUILD_UPLOAD%)

@ -0,0 +1,19 @@
{
"targets": [
{
"target_name": "tree_sitter_lua_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
],
"sources": [
"src/parser.c",
"bindings/node/binding.cc",
"src/scanner.cc"
],
"cflags_c": [
"-std=c99",
]
}
]
}

@ -0,0 +1,28 @@
#include "tree_sitter/parser.h"
#include <node.h>
#include "nan.h"
using namespace v8;
extern "C" TSLanguage * tree_sitter_lua();
namespace {
NAN_METHOD(New) {}
void Init(Local<Object> exports, Local<Object> module) {
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Language").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Local<Function> constructor = Nan::GetFunction(tpl).ToLocalChecked();
Local<Object> instance = constructor->NewInstance(Nan::GetCurrentContext()).ToLocalChecked();
Nan::SetInternalFieldPointer(instance, 0, tree_sitter_lua());
Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("lua").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}
NODE_MODULE(tree_sitter_lua_binding, Init)
} // namespace

@ -0,0 +1,19 @@
try {
module.exports = require("../../build/Release/tree_sitter_lua_binding");
} catch (error1) {
if (error1.code !== 'MODULE_NOT_FOUND') {
throw error1;
}
try {
module.exports = require("../../build/Debug/tree_sitter_lua_binding");
} catch (error2) {
if (error2.code !== 'MODULE_NOT_FOUND') {
throw error2;
}
throw error1
}
}
try {
module.exports.nodeTypeInfo = require("../../src/node-types.json");
} catch (_) {}

@ -0,0 +1,40 @@
fn main() {
let src_dir = std::path::Path::new("src");
let mut c_config = cc::Build::new();
c_config.include(&src_dir);
c_config
.flag_if_supported("-Wno-unused-parameter")
.flag_if_supported("-Wno-unused-but-set-variable")
.flag_if_supported("-Wno-trigraphs");
let parser_path = src_dir.join("parser.c");
c_config.file(&parser_path);
// If your language uses an external scanner written in C,
// then include this block of code:
/*
let scanner_path = src_dir.join("scanner.c");
c_config.file(&scanner_path);
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
*/
println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap());
c_config.compile("parser");
// If your language uses an external scanner written in C++,
// then include this block of code:
/*
let mut cpp_config = cc::Build::new();
cpp_config.cpp(true);
cpp_config.include(&src_dir);
cpp_config
.flag_if_supported("-Wno-unused-parameter")
.flag_if_supported("-Wno-unused-but-set-variable");
let scanner_path = src_dir.join("scanner.cc");
cpp_config.file(&scanner_path);
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
cpp_config.compile("scanner");
*/
}

@ -0,0 +1,52 @@
//! 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 = "";
//! let mut parser = tree_sitter::Parser::new();
//! parser.set_language(tree_sitter_javascript::language()).expect("Error loading lua grammar");
//! let tree = parser.parse(code, None).unwrap();
//! ```
//!
//! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
//! [language func]: fn.language.html
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/
use tree_sitter::Language;
extern "C" {
fn tree_sitter_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: &'static str = include_str!("../../src/node-types.json");
// Uncomment these to include any queries that this grammar contains
// pub const HIGHLIGHTS_QUERY: &'static str = include_str!("../../queries/highlights.scm");
// pub const INJECTIONS_QUERY: &'static str = include_str!("../../queries/injections.scm");
// pub const LOCALS_QUERY: &'static str = include_str!("../../queries/locals.scm");
// pub const TAGS_QUERY: &'static str = include_str!("../../queries/tags.scm");
#[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");
}
}

@ -0,0 +1,52 @@
============================================
Comments
============================================
--
-- single-line comment, below an empty single-line comment
--[[
"block comment"
--]]
--[[
"block comment"
]]
-- [[
"not block comment"
--]]
--[==[
"level 2 block comment"
-- ]==]
--[==[
"level 2 block comment"
]==]
-- [==[
"not level 2 block comment"
--]==]
---
(program
(comment)
(comment)
(comment)
(comment)
(comment)
(expression (string))
(comment)
(comment)
(comment)
(comment)
(expression (string))
(comment))

@ -0,0 +1,90 @@
============================================
Tables
============================================
food = {
["favorites"] = {
['pizza'] = true,
hotdog = false
}
}
local games = {
favorites = {
{ 'the witcher', "world of warcraft", 'dragon age', "mass effect" }
}
}
---
(program
(variable_declaration (variable_declarator (identifier))
(table
(field (string)
(table
(field (string) (true))
(field (identifier) (false))))))
(local_variable_declaration (variable_declarator (identifier))
(table
(field (identifier)
(table
(field
(table
(field (string))
(field (string))
(field (string))
(field (string)))))))))
============================================
Binary operations
============================================
a = i + j * 3 - j % 5
b = k + v % 5 ^ 2
c = i * 2 ^ j
---
(program
(variable_declaration (variable_declarator (identifier))
(binary_operation
(binary_operation (identifier)
(binary_operation (identifier) (number)))
(binary_operation (identifier) (number))))
(variable_declaration (variable_declarator (identifier))
(binary_operation (identifier)
(binary_operation (identifier)
(binary_operation (number) (number)))))
(variable_declaration (variable_declarator (identifier))
(binary_operation (identifier)
(binary_operation (number) (identifier)))))
============================================
Unary operations
============================================
food_table_size = #food
negative_value = -value
tern_bool = not condition and true or false
---
(program
(variable_declaration (variable_declarator (identifier))
(unary_operation (identifier)))
(variable_declaration (variable_declarator (identifier))
(unary_operation (identifier)))
(variable_declaration (variable_declarator (identifier))
(binary_operation
(binary_operation
(unary_operation (identifier)) (true))
(false))))

@ -0,0 +1,107 @@
============================================
Function definitions
============================================
f = function() return false end
a.b.f = function() return true end
local f
f = function() return 'some string' end
a.b.f = function(self, test, ...) return 10 end
---
(program
(variable_declaration (variable_declarator (identifier))
(function_definition (parameters)
(return_statement (false))))
(variable_declaration (variable_declarator
(field_expression (field_expression (identifier) (property_identifier)) (property_identifier)))
(function_definition (parameters)
(return_statement (true))))
(local_variable_declaration (variable_declarator (identifier)))
(variable_declaration (variable_declarator (identifier))
(function_definition (parameters)
(return_statement (string))))
(variable_declaration (variable_declarator
(field_expression (field_expression (identifier) (property_identifier)) (property_identifier)))
(function_definition (parameters (self) (identifier) (spread))
(return_statement (number)))))
============================================
Function statements
============================================
function f()
return false
end
f = function() return false end
function t.a.b.c.f()
return true
end
---
(program
(function (function_name (identifier)) (parameters)
(return_statement (false)))
(variable_declaration (variable_declarator (identifier))
(function_definition (parameters)
(return_statement (false))))
(function (function_name (function_name_field (identifier) (property_identifier) (property_identifier) (property_identifier) (property_identifier))) (parameters)
(return_statement (true))))
============================================
Local function statements
============================================
local function f()
return 'some string'
end
local f
f = function() return 'some string' end
---
(program
(local_function (identifier) (parameters)
(return_statement (string)))
(local_variable_declaration (variable_declarator (identifier)))
(variable_declaration (variable_declarator (identifier))
(function_definition (parameters)
(return_statement (string)))))
============================================
Function calls
============================================
f(3)
f(r(), 10)
g(5, r())
---
(program
(function_call (identifier)
(arguments (number)))
(function_call (identifier)
(arguments (function_call (identifier) (arguments)) (number)))
(function_call (identifier)
(arguments (number) (function_call (identifier) (arguments)))))

@ -0,0 +1,83 @@
============================================
Literal strings (short/long)
============================================
'a short literal string with single \'quote\''
"a short literal string with double \"quote\""
[[
a level 0 long literal string
with double brackets [=[ a level 1 string completely ignored ]=]
]]
[==[
a level 2 long literal string
with double brackets [[ a level 0 string completely ignored ]]
]==]
"a string with comment token inside -> -- disabled comment"
[[
a level 0 long literal string with comment token inside -> -- disabled comment
]]
---
(program
(expression (string))
(expression (string))
(expression (string))
(expression (string))
(expression (string))
(expression (string)))
============================================
Numeric constants
============================================
3
345
0xff
0xBEBADA
3.0
3.1416
314.16e-2
0.31416E1
34e1
0x0.1E
0xA23p-4
0X1.921FB54442D18P+1
---
(program
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number))
(expression (number)))
=============================
Shebang
=============================
#!foobar
return
---
(program
(shebang)
(return_statement))

@ -0,0 +1,216 @@
============================================
Do statements
============================================
do
local a2 = 2 * a
local d = sqrt(b ^ 2 - 4 * a * c)
x1 = (-b + d) / a2
x2 = (-b - d) / a2
end
print(x1, x2)
---
(program
(do_statement
(local_variable_declaration (variable_declarator (identifier))
(binary_operation (number) (identifier)))
(local_variable_declaration (variable_declarator (identifier))
(function_call (identifier)
(arguments
(binary_operation
(binary_operation (identifier) (number))
(binary_operation
(binary_operation (number) (identifier))
(identifier))))))
(variable_declaration (variable_declarator (identifier))
(binary_operation
(binary_operation (unary_operation (identifier))
(identifier))
(identifier)))
(variable_declaration (variable_declarator (identifier))
(binary_operation
(binary_operation (unary_operation (identifier))
(identifier))
(identifier))))
(function_call (identifier)
(arguments (identifier) (identifier))))
============================================
If clauses
============================================
if num > 40 then
print('over 40')
elseif s ~= 'walternate' then
io.write('not over 40\n')
else
thisIsGlobal = 5
local line = io.read()
print('Winter is coming, ' .. line)
end
---
(program
(if_statement
(condition_expression (binary_operation (identifier) (number)))
(function_call (identifier)
(arguments (string)))
(elseif (condition_expression (binary_operation (identifier) (string)))
(function_call (field_expression (identifier) (property_identifier))
(arguments (string))))
(else
(variable_declaration (variable_declarator (identifier)) (number))
(local_variable_declaration (variable_declarator (identifier))
(function_call (field_expression (identifier) (property_identifier))
(arguments)))
(function_call (identifier)
(arguments (binary_operation (string) (identifier)))))))
============================================
While statements
============================================
while num < 50 do
num = num + 1
end
---
(program
(while_statement
(condition_expression
(binary_operation (identifier) (number)))
(variable_declaration (variable_declarator (identifier))
(binary_operation (identifier) (number)))))
============================================
Repeat statements
============================================
repeat
print('the way of the future')
num = num - 1
until num == 0
---
(program
(repeat_statement
(function_call (identifier) (arguments (string)))
(variable_declaration (variable_declarator (identifier))
(binary_operation (identifier) (number)))
(condition_expression (binary_operation (identifier) (number)))))
============================================
For statement
============================================
karlSum = 0
for i = 1, 100 do
karlSum = karlSum + i
end
fredSum = 0
for j = 100, 1, -1 do
fredSum = fredSum + j
end
v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do
print(v[i])
end
---
(program
(variable_declaration (variable_declarator (identifier)) (number))
(for_statement (loop_expression (identifier) (number) (number))
(variable_declaration (variable_declarator (identifier))
(binary_operation (identifier) (identifier))))
(variable_declaration (variable_declarator (identifier)) (number))
(for_statement (loop_expression (identifier) (number) (number) (unary_operation (number)))
(variable_declaration (variable_declarator (identifier))
(binary_operation (identifier) (identifier))))
(variable_declaration (variable_declarator (identifier))
(table (field (string)) (field (string)) (field (number)) (field (string))))
(for_statement (loop_expression (identifier) (number) (unary_operation (identifier)))
(function_call (identifier) (arguments (identifier) (identifier)))))
============================================
For in statements
============================================
for key, val in pairs(u) do
print(key, val)
end
for key, val in ipairs(u) do
print(key, val)
end
for key, val in next, u do
print(key, val)
end
---
(program
(for_in_statement (loop_expression (identifier) (identifier) (function_call (identifier) (arguments (identifier))))
(function_call (identifier) (arguments (identifier) (identifier))))
(for_in_statement (loop_expression (identifier) (identifier) (function_call (identifier) (arguments (identifier))))
(function_call (identifier) (arguments (identifier) (identifier))))
(for_in_statement (loop_expression (identifier) (identifier) (next) (identifier))
(function_call (identifier) (arguments (identifier) (identifier)))))
============================================
Goto statements
============================================
goto someLuaLabel
---
(program
(goto_statement (identifier)))
============================================
Break statements
============================================
for i = 1, 10 do
if i == 5 then
break
end
end
---
(program
(for_statement
(loop_expression (identifier) (number) (number))
(if_statement
(condition_expression
(binary_operation (identifier) (number)))
(break_statement))))
============================================
Label statements
============================================
:: someLuaLabel ::
---
(program
(label_statement (identifier)))

@ -0,0 +1,91 @@
# The complete syntax of Lua
Here is the complete syntax of Lua in extended BNF. As usual in extended BNF, {A} means 0 or more As, and [A] means an optional A.
---
<pre>
chunk ::=
block
block ::=
{stat} [retstat]
stat ::=
<b>';'</b> | varlist <b>'='</b> explist | functioncall | label | <b>break</b> | <b>goto</b> Name |
<b>do</b> block <b>end</b> |
<b>while</b> exp <b>do</b> block <b>end</b> |
<b>repeat</b> block <b>until</b> exp |
<b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
<b>for</b> Name <b>'='</b> exp <b>','</b> exp [<b>','</b> exp] <b>do</b> block <b>end</b> |
<b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
<b>function</b> funcname funcbody |
<b>local</b> <b>function</b> Name funcbody |
<b>local</b> namelist [<b>'='</b> explist]
retstat ::=
<b>return</b> [explist] [<b>';'</b>]
label ::=
<b>'::'</b> Name <b>'::'</b>
funcname ::=
Name {<b>'.'</b> Name} [<b>':'</b> Name]
varlist ::=
var {<b>,</b> var}
var ::=
Name | prefixexp <b>'['</b> exp <b>']'</b> | prefixexp <b>'.'</b> Name
namelist ::=
Name {<b>','</b> Name}
explist ::=
exp {<b>','</b> exp}
exp ::=
<b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | <b>'...'</b> | functiondef |
prefixexp | tableconstructor | exp binop exp | unop exp
prefixexp ::=
var | functioncall | <b>'('</b> exp <b>')'</b>
functioncall ::=
prefixexp args | prefixexp <b>':'</b> Name args
args ::=
<b>'('</b> [explist] <b>')'</b> | tableconstructor | LiteralString
functiondef ::=
<b>function</b> funcbody
funcbody ::=
<b>'('</b> [parlist] <b>')'</b> block <b>end</b>
parlist ::=
namelist [<b>','</b> <b>'...'</b>] | <b>'...'</b>
tableconstructor ::=
<b>'{'</b> [ fieldlist ] <b>'}'</b>
fieldlist ::=
field {fieldsep field} [fieldsep]
field ::=
<b>'['</b> exp <b>']'</b> <b>'='</b> exp | Name <b>'='</b> exp | exp
fieldsep ::=
<b>','</b> | <b>';'</b>
binop ::=
<b>'+'</b> | <b>'-'</b> | <b>'*'</b> | <b>'/'</b> | <b>'//'</b> | <b>'^'</b> | <b>'%'</b> |
<b>'&'</b> | <b>'~'</b> | <b>'|'</b> | <b>'>>'</b> | <b>'<<'</b> | <b>'..'</b> |
<b>'<'</b> | <b>'<='</b> | <b>'>'</b> | <b>'>='</b> | <b>'=='</b> | <b>'~='</b> |
<b>not</b> | <b>or</b>
unop ::=
<b>'-'</b> | <b>not</b> | <b>'#'</b> | <b>'~'</b>
</pre>

@ -0,0 +1,410 @@
const PREC = {
COMMA: -1,
PRIORITY: 1,
OR: 1, //=> or
AND: 2, //=> and
COMPARE: 3, //=> < <= == ~= >= >
BIT_OR: 4, //=> |
BIT_NOT: 5, //=> ~
BIT_AND: 6, //=> &
SHIFT: 7, //=> << >>
CONCAT: 8, //=> ..
PLUS: 9, //=> + -
MULTI: 10, //=> * / // %
UNARY: 11, //=> not # - ~
POWER: 12 //=> ^
}
module.exports = grammar({
name: 'lua',
extras: $ => [
$.comment,
/[\s\n]/
],
inline: $ => [
$._statement
],
conflicts: $ => [
[$._prefix],
[$._expression, $._variable_declarator],
[$._expression, $.function_call_statement],
[$.function_name, $.function_name_field]
],
externals: $ => [
$.comment,
$.string
],
rules: {
program: $ => seq(optional($.shebang), repeat($._statement), optional($.return_statement)),
shebang: $ => /#!.*\n/,
// Return statement
return_statement: $ => seq(
'return',
optional(commaSeq($._expression)),
optional($._empty_statement)
),
// Statements
_statement: $ => choice(
alias($._expression, $.expression),
$.variable_declaration,
$.local_variable_declaration,
$.do_statement,
$.if_statement,
$.while_statement,
$.repeat_statement,
$.for_statement,
$.for_in_statement,
$.goto_statement,
$.break_statement,
$.label_statement,
$._empty_statement,
alias($.function_statement, $.function),
alias($.local_function_statement, $.local_function),
alias($.function_call_statement, $.function_call)
),
// Statements: Variable eclarations
variable_declaration: $ => seq(
commaSeq(alias($._variable_declarator, $.variable_declarator)),
'=',
commaSeq($._expression)
),
local_variable_declaration: $ => seq(
'local',
alias($._local_variable_declarator, $.variable_declarator),
optional(seq('=', commaSeq($._expression)))
),
_variable_declarator: $ => choice(
$.identifier,
seq($._prefix, '[', $._expression, ']'),
$.field_expression
),
field_expression: $ => seq($._prefix, '.', alias($.identifier, $.property_identifier)),
_local_variable_declarator: $ => commaSeq($.identifier),
// Statements: Control statements
do_statement: $ => seq(
'do',
repeat($._statement),
optional($.return_statement),
'end'
),
if_statement: $ => seq(
'if',
alias($._expression, $.condition_expression),
'then',
repeat($._statement),
optional($.return_statement),
repeat($.elseif),
optional($.else),
'end'
),
elseif: $ => seq(
'elseif',
alias($._expression, $.condition_expression),
'then',
repeat($._statement),
optional($.return_statement)
),
else: $ => seq(
'else',
repeat($._statement),
optional($.return_statement)
),
while_statement: $ => seq(
'while',
alias($._expression, $.condition_expression),
'do',
repeat($._statement),
optional($.return_statement),
'end'
),
repeat_statement: $ => seq(
'repeat',
repeat($._statement),
optional($.return_statement),
'until',
alias($._expression, $.condition_expression)
),
// Statements: For statements
for_statement: $ => seq(
'for',
alias($._loop_expression, $.loop_expression),
'do',
repeat($._statement),
optional($.return_statement),
'end'
),
for_in_statement: $ => seq(
'for',
alias($._in_loop_expression, $.loop_expression),
'do',
repeat($._statement),
optional($.return_statement),
'end'
),
_loop_expression: $ => seq(
$.identifier,
'=',
$._expression,
',',
$._expression,
optional(seq(',', $._expression))
),
_in_loop_expression: $ => seq(
commaSeq($.identifier),
'in',
commaSeq($._expression),
),
// Statements: Simple statements
goto_statement: $ => seq(
'goto',
$.identifier
),
break_statement: $ => 'break',
// Statements: Void statements
label_statement: $ => seq(
'::',
$.identifier,
'::'
),
_empty_statement: $ => ';',
// Statements: Function statements
function_statement: $ => seq(
'function',
$.function_name,
$._function_body
),
local_function_statement: $ => seq(
'local',
'function',
$.identifier,
$._function_body
),
function_call_statement: $ => prec.dynamic(PREC.PRIORITY, choice(
seq($._prefix, $.arguments),
seq($._prefix, ':', alias($.identifier, $.method), $.arguments)
)),
arguments: $ => choice(
seq('(', optional(commaSeq($._expression)), ')'),
$.table,
$.string
),
function_name: $ => seq(
choice($.identifier,
$.function_name_field
),
optional(seq(':', alias($.identifier, $.method)))
),
function_name_field: $ => seq(
field("object", $.identifier),
repeat(seq('.', alias($.identifier, $.property_identifier))),
),
parameters: $ => seq(
'(',
optional(seq(
choice($.self, $.spread, $.identifier),
repeat(seq(',', $.identifier)),
optional(seq(',', $.spread))
)),
')'
),
_function_body: $ => seq(
$.parameters,
repeat($._statement),
optional($.return_statement),
'end'
),
// Expressions
_expression: $ => choice(
$.spread,
$._prefix,
$.next,
$.function_definition,
$.table,
$.binary_operation,
$.unary_operation,
$.string,
$.number,
$.nil,
$.true,
$.false,
$.identifier
),
// Expressions: Common
spread: $ => '...',
self: $ => 'self',
next: $ => 'next',
global_variable: $ => choice('_G', '_VERSION'),
_prefix: $ => choice(
$.self,
$.global_variable,
$._variable_declarator,
prec(-1, alias($.function_call_statement, $.function_call)),
seq('(', $._expression, ')')
),
// Expressions: Function definition
function_definition: $ => seq(
'function',
$._function_body
),
// Expressions: Table expressions
table: $ => seq(
'{',
optional($._field_sequence),
'}'
),
field: $ => choice(
seq('[', $._expression, ']', '=', $._expression),
seq($.identifier, '=', $._expression),
$._expression
),
_field_sequence: $ => prec(PREC.COMMA, seq(
$.field,
repeat(seq($._field_sep, $.field)),
optional($._field_sep)
)),
_field_sep: $ => choice(',', ';'),
// Expressions: Operation expressions
binary_operation: $ => 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.SHIFT],
['>>', PREC.SHIFT],
['+', PREC.PLUS],
['-', PREC.PLUS],
['*', PREC.MULTI],
['/', PREC.MULTI],
['//', PREC.MULTI],
['%', PREC.MULTI],
].map(([operator, precedence]) => prec.left(precedence, seq(
$._expression,
operator,
$._expression
))),
...[
['..', PREC.CONCAT],
['^', PREC.POWER],
].map(([operator, precedence]) => prec.right(precedence, seq(
$._expression,
operator,
$._expression
)))
),
unary_operation: $ => prec.left(PREC.UNARY, seq(
choice('not', '#', '-', '~'),
$._expression
)),
// Expressions: Primitives
number: $ => {
const decimal_digits = /[0-9]+/
const signed_integer = seq(optional(choice('-', '+')), decimal_digits)
const decimal_exponent_part = seq(choice('e', 'E'), signed_integer)
const decimal_integer_literal = choice(
'0',
seq(optional('0'), /[1-9]/, optional(decimal_digits))
)
const hex_digits = /[a-fA-F0-9]+/
const hex_exponent_part = seq(choice('p', 'P'), signed_integer)
const decimal_literal = choice(
seq(decimal_integer_literal, '.', optional(decimal_digits), optional(decimal_exponent_part)),
seq('.', decimal_digits, optional(decimal_exponent_part)),
seq(decimal_integer_literal, optional(decimal_exponent_part))
)
const hex_literal = seq(
choice('0x', '0X'),
hex_digits,
optional(seq('.', hex_digits)),
optional(hex_exponent_part)
)
return token(choice(
decimal_literal,
hex_literal
))
},
nil: $ => 'nil',
true: $ => 'true',
false: $ => 'false',
// Identifier
identifier: $ => /[a-zA-Z_][a-zA-Z0-9_]*/
}
})
function commaSeq(rule) {
return seq(rule, repeat(seq(',', rule)))
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,37 @@
{
"name": "tree-sitter-lua",
"version": "1.6.1",
"description": "Lua grammar for tree-sitter.",
"main": "bindings/node",
"keywords": [
"tree-sitter",
"parser",
"lua"
],
"repository": "https://github.com/Azganoth/tree-sitter-lua",
"author": "Ademir J. Ferreira Junior <ademirj.ferreirajunior@gmail.com> (https://github.com/Azganoth)",
"license": "MIT",
"scripts": {
"build": "tree-sitter generate && node-gyp build --debug",
"install": "prebuild-install || node-gyp rebuild",
"dist": "prebuild -r electron -t 3.0.0 -t 4.0.0 -t 4.0.4 -t 5.0.0 --strip && prebuild -t 8.16.0 -t 10.16.1 --strip",
"dist:upload": "prebuild --upload-all",
"test": "tree-sitter test"
},
"dependencies": {
"nan": "^2.14.2",
"prebuild-install": "^6.0.1"
},
"devDependencies": {
"prebuild": "^10.0.1",
"tree-sitter-cli": "^0.19.1"
},
"files": [
"src",
"binding.gyp",
"grammar.js",
"index.js",
"package.json",
"package-lock.json"
]
}

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

@ -0,0 +1,231 @@
#include <tree_sitter/parser.h>
#include <cwctype>
namespace {
using std::iswspace;
enum TokenType {
COMMENT,
STRING
};
struct Scanner {
static void skip(TSLexer *lexer) { lexer->advance(lexer, true); }
static void advance(TSLexer *lexer) { lexer->advance(lexer, false); }
static bool scan_sequence(TSLexer *lexer, const char *sequence) {
// Try to match all characters in the given 'sequence'
for (const char *c = sequence; *c; c++) {
if (lexer->lookahead == *c) {
// Consume the character in 'c'
advance(lexer);
} else {
return false;
}
}
return true;
}
static bool scan_multiline_content(TSLexer *lexer) {
// Initialize lua multiline content level count
int start_level = 0;
int end_level = 0;
if (lexer->lookahead == '[') {
// Consume first appearance of '['
advance(lexer);
if (lexer->lookahead == '[' || lexer->lookahead == '=') {
while (lexer->lookahead == '=') {
// Increment level count
++start_level;
// Consume all '=' characters
advance(lexer);
}
if (lexer->lookahead == '[') {
// Consume last appearance of '['
advance(lexer);
// Loop while not end of file (eof)
while (lexer->lookahead != 0) {
// Gives the end level count the same as start level count
end_level = start_level;
if (lexer->lookahead == ']') {
// Consume first appearance of ']'
advance(lexer);
if (lexer->lookahead == ']' || lexer->lookahead == '=') {
while (lexer->lookahead == '=' && end_level > 0) {
// Decrement level count
--end_level;
// Consume all '=' characters
advance(lexer);
}
if (lexer->lookahead == ']' && end_level == 0) {
// Consume last appearance of ']'
advance(lexer);
return true;
}
}
}
if (lexer->lookahead != 0) {
// Consume all but end of file (eof)
advance(lexer);
}
}
}
}
}
return false;
}
bool scan(TSLexer *lexer, const bool *valid_symbols) {
if (valid_symbols[COMMENT] || valid_symbols[STRING]) {
while (iswspace(lexer->lookahead)) {
skip(lexer);
}
// Try to make a short literal string with single quote
if (lexer->lookahead == '\'') {
lexer->result_symbol = STRING;
// Consume first appearance of '\''
advance(lexer);
// Loop when isn't new line neither end of file (eof)
while (lexer->lookahead != '\n' && lexer->lookahead != 0) {
if (lexer->lookahead == '\\') {
// Consume '\\'
advance(lexer);
if (lexer->lookahead != '\n' && lexer->lookahead != 0) {
// Consume any character that isn't new line neither end of file (eof)
advance(lexer);
} else {
break;
}
} else {
if (lexer->lookahead == '\'') {
// Consume last appearance of '\''
advance(lexer);
return true;
} else {
if (lexer->lookahead != '\n' && lexer->lookahead != 0) {
// Consume any character that isn't new line neither end of file (eof)
advance(lexer);
} else {
break;
}
}
}
}
}
// Try to make a short literal string with double quote
else if (lexer->lookahead == '"') {
lexer->result_symbol = STRING;
// Consume first appearance of '"'
advance(lexer);
// Loop when next character isn't new line neither end of file (eof)
while (lexer->lookahead != '\n' && lexer->lookahead != 0) {
if (lexer->lookahead == '\\') {
// Consume '\\'
advance(lexer);
if (lexer->lookahead != '\n' && lexer->lookahead != 0) {
// Consume any character that isn't new line neither end of file (eof)
advance(lexer);
} else {
break;
}
} else {
if (lexer->lookahead == '"') {
// Consume last appearance of '"'
advance(lexer);
return true;
} else {
if (lexer->lookahead != '\n' && lexer->lookahead != 0) {
// Consume any character that isn't new line neither end of file (eof)
advance(lexer);
} else {
break;
}
}
}
}
}
// Try to make a comment
else if (scan_sequence(lexer, "--")) {
if (scan_multiline_content(lexer)) {
return true;
}
while (iswspace(lexer->lookahead) && lexer->lookahead != '\n' && lexer->lookahead != 0) {
advance(lexer);
}
lexer->result_symbol = COMMENT;
while (lexer->lookahead != '\n' && lexer->lookahead != 0) {
// Consume any character that isn't new line neither end of file (eof)
advance(lexer);
}
return true;
}
// Try to make a long literal string with double bracket
else if (scan_multiline_content(lexer)) {
lexer->result_symbol = STRING;
return true;
}
return false;
}
return false;
}
};
}
extern "C" {
void *tree_sitter_lua_external_scanner_create() {
return new Scanner();
}
void tree_sitter_lua_external_scanner_destroy(void *payload) {
Scanner *scanner = static_cast<Scanner *>(payload);
delete scanner;
}
bool tree_sitter_lua_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
Scanner *scanner = static_cast<Scanner *>(payload);
return scanner->scan(lexer, valid_symbols);
}
unsigned tree_sitter_lua_external_scanner_serialize(void *payload, char *buffer) {
return 0;
}
void tree_sitter_lua_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) {}
}

@ -0,0 +1,223 @@
#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
typedef uint16_t TSStateId;
#ifndef TREE_SITTER_API_H_
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;
};
/*
* Lexer Macros
*/
#define START_LEXER() \
bool result = false; \
bool skip = false; \
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_