robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
49.3 KiB1874 linesraw
1// lua bindings for treesitter.
2// NB: this file mostly contains a generic lua interface for treesitter
3// trees and nodes, and could be broken out as a reusable lua package
4
5#include <assert.h>
6#include <ctype.h>
7#include <lauxlib.h>
8#include <limits.h>
9#include <lua.h>
10#include <stdbool.h>
11#include <stdint.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#include <uv.h>
16
17#include "nvim/os/time.h"
18
19#ifdef HAVE_WASMTIME
20# include <wasm.h>
21
22# include "nvim/os/fs.h"
23#endif
24
25#include "nvim/api/private/helpers.h"
26#include "nvim/ascii_defs.h"
27#include "nvim/buffer_defs.h"
28#include "nvim/globals.h"
29#include "nvim/lua/treesitter.h"
30#include "nvim/macros_defs.h"
31#include "nvim/map_defs.h"
32#include "nvim/memline.h"
33#include "nvim/memory.h"
34#include "nvim/pos_defs.h"
35#include "nvim/strings.h"
36#include "nvim/types_defs.h"
37
38#define TS_META_PARSER "treesitter_parser"
39#define TS_META_TREE "treesitter_tree"
40#define TS_META_NODE "treesitter_node"
41#define TS_META_QUERY "treesitter_query"
42#define TS_META_QUERYCURSOR "treesitter_querycursor"
43#define TS_META_QUERYMATCH "treesitter_querymatch"
44
45#ifdef __EMSCRIPTEN__
46extern const TSLanguage *nvim_ts_get_parser(const char *lang);
47#endif
48
49typedef struct {
50  LuaRef cb;
51  lua_State *lstate;
52  bool lex;
53  bool parse;
54} TSLuaLoggerOpts;
55
56typedef struct {
57  // We derive TSNode's, TSQueryCursor's, etc., from the TSTree, so it must not be mutated.
58  const TSTree *tree;
59} TSLuaTree;
60
61typedef struct {
62  uint64_t parse_start_time;
63  uint64_t timeout_threshold_ns;
64} TSLuaParserCallbackPayload;
65
66#include "lua/treesitter.c.generated.h"
67
68static PMap(cstr_t) langs = MAP_INIT;
69
70#ifdef HAVE_WASMTIME
71static wasm_engine_t *wasmengine;
72static TSWasmStore *ts_wasmstore;
73#endif
74
75// TSLanguage
76
77static int tslua_has_language(lua_State *L)
78{
79  const char *lang_name = luaL_checkstring(L, 1);
80  lua_pushboolean(L, map_has(cstr_t, &langs, lang_name));
81  return 1;
82}
83
84#ifdef HAVE_WASMTIME
85static char *read_file(const char *path, size_t *len)
86  FUNC_ATTR_MALLOC
87{
88  FILE *file = os_fopen(path, "r");
89  if (file == NULL) {
90    return NULL;
91  }
92  fseek(file, 0L, SEEK_END);
93  *len = (size_t)ftell(file);
94  fseek(file, 0L, SEEK_SET);
95  char *data = xmalloc(*len);
96  if (fread(data, *len, 1, file) != 1) {
97    xfree(data);
98    fclose(file);
99    return NULL;
100  }
101  fclose(file);
102  return data;
103}
104
105static const char *wasmerr_to_str(TSWasmErrorKind werr)
106{
107  switch (werr) {
108  case TSWasmErrorKindParse:
109    return "PARSE";
110  case TSWasmErrorKindCompile:
111    return "COMPILE";
112  case TSWasmErrorKindInstantiate:
113    return "INSTANTIATE";
114  case TSWasmErrorKindAllocate:
115    return "ALLOCATE";
116  default:
117    return "UNKNOWN";
118  }
119}
120#endif
121
122#ifdef HAVE_WASMTIME
123static int tslua_add_language_from_wasm(lua_State *L)
124{
125  return add_language(L, true);
126}
127#endif
128
129// Creates the language into the internal language map.
130//
131// Returns true if the language is correctly loaded in the language map
132static int tslua_add_language_from_object(lua_State *L)
133{
134  return add_language(L, false);
135}
136
137static const TSLanguage *load_language_from_object(lua_State *L, const char *path,
138                                                   const char *lang_name, const char *symbol)
139{
140#ifdef __EMSCRIPTEN__
141  const TSLanguage *static_lang = nvim_ts_get_parser(symbol);
142  if (static_lang != NULL) {
143    return static_lang;
144  }
145#endif
146
147  uv_lib_t lib;
148  if (uv_dlopen(path, &lib)) {
149    xstrlcpy(IObuff, uv_dlerror(&lib), sizeof(IObuff));
150    uv_dlclose(&lib);
151    luaL_error(L, "Failed to load parser for language '%s': uv_dlopen: %s", lang_name, IObuff);
152  }
153
154  char symbol_buf[128];
155  snprintf(symbol_buf, sizeof(symbol_buf), "tree_sitter_%s", symbol);
156
157  TSLanguage *(*lang_parser)(void);
158  if (uv_dlsym(&lib, symbol_buf, (void **)&lang_parser)) {
159    xstrlcpy(IObuff, uv_dlerror(&lib), sizeof(IObuff));
160    uv_dlclose(&lib);
161    luaL_error(L, "Failed to load parser: uv_dlsym: %s", IObuff);
162  }
163
164  TSLanguage *lang = lang_parser();
165
166  if (lang == NULL) {
167    uv_dlclose(&lib);
168    luaL_error(L, "Failed to load parser %s: internal error", path);
169  }
170
171  return lang;
172}
173
174static const TSLanguage *load_language_from_wasm(lua_State *L, const char *path,
175                                                 const char *lang_name)
176{
177#ifndef HAVE_WASMTIME
178  luaL_error(L, "Not supported");
179  return NULL;
180#else
181  if (wasmengine == NULL) {
182    wasmengine = wasm_engine_new();
183  }
184  assert(wasmengine != NULL);
185
186  TSWasmError werr = { 0 };
187  if (ts_wasmstore == NULL) {
188    ts_wasmstore = ts_wasm_store_new(wasmengine, &werr);
189  }
190
191  if (werr.kind > 0) {
192    luaL_error(L, "Failed to create WASM store: (%s) %s", wasmerr_to_str(werr.kind), werr.message);
193  }
194
195  size_t file_size = 0;
196  char *data = read_file(path, &file_size);
197
198  if (data == NULL) {
199    luaL_error(L, "Unable to read file", path);
200  }
201
202  const TSLanguage *lang = ts_wasm_store_load_language(ts_wasmstore, lang_name, data,
203                                                       (uint32_t)file_size, &werr);
204
205  xfree(data);
206
207  if (werr.kind > 0) {
208    luaL_error(L, "Failed to load WASM parser %s: (%s) %s", path, wasmerr_to_str(werr.kind),
209               werr.message);
210  }
211
212  if (lang == NULL) {
213    luaL_error(L, "Failed to load parser %s: internal error", path);
214  }
215
216  return lang;
217#endif
218}
219
220static int add_language(lua_State *L, bool is_wasm)
221{
222  const char *path = luaL_checkstring(L, 1);
223  const char *lang_name = luaL_checkstring(L, 2);
224  const char *symbol_name = lang_name;
225
226  if (!is_wasm && lua_gettop(L) >= 3 && !lua_isnil(L, 3)) {
227    symbol_name = luaL_checkstring(L, 3);
228  }
229
230  if (map_has(cstr_t, &langs, lang_name)) {
231    lua_pushboolean(L, true);
232    return 1;
233  }
234
235  const TSLanguage *lang = is_wasm
236                           ? load_language_from_wasm(L, path, lang_name)
237                           : load_language_from_object(L, path, lang_name, symbol_name);
238
239  uint32_t lang_version = ts_language_abi_version(lang);
240  if (lang_version < TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION
241      || lang_version > TREE_SITTER_LANGUAGE_VERSION) {
242    return luaL_error(L,
243                      "ABI version mismatch for %s: supported between %d and %d, found %d",
244                      path,
245                      TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION,
246                      TREE_SITTER_LANGUAGE_VERSION, lang_version);
247  }
248
249  pmap_put(cstr_t)(&langs, xstrdup(lang_name), (TSLanguage *)lang);
250
251  lua_pushboolean(L, true);
252  return 1;
253}
254
255static int tslua_remove_lang(lua_State *L)
256{
257  const char *lang_name = luaL_checkstring(L, 1);
258  bool present = map_has(cstr_t, &langs, lang_name);
259  if (present) {
260    cstr_t key;
261    pmap_del(cstr_t)(&langs, lang_name, &key);
262    xfree((void *)key);
263  }
264  lua_pushboolean(L, present);
265  return 1;
266}
267
268static TSLanguage *lang_check(lua_State *L, int index)
269{
270  const char *lang_name = luaL_checkstring(L, index);
271  TSLanguage *lang = pmap_get(cstr_t)(&langs, lang_name);
272  if (!lang) {
273    luaL_error(L, "no such language: %s", lang_name);
274  }
275  return lang;
276}
277
278static int tslua_inspect_lang(lua_State *L)
279{
280  TSLanguage *lang = lang_check(L, 1);
281
282  lua_createtable(L, 0, 2);  // [retval]
283
284  {  // Symbols
285    uint32_t nsymbols = ts_language_symbol_count(lang);
286    assert(nsymbols < INT_MAX);
287
288    lua_createtable(L, (int)(nsymbols - 1), 1);  // [retval, symbols]
289    for (uint32_t i = 0; i < nsymbols; i++) {
290      TSSymbolType t = ts_language_symbol_type(lang, (TSSymbol)i);
291      if (t == TSSymbolTypeAuxiliary) {
292        // not used by the API
293        continue;
294      }
295      const char *name = ts_language_symbol_name(lang, (TSSymbol)i);
296      bool named = t != TSSymbolTypeAnonymous;
297      lua_pushboolean(L, named);  // [retval, symbols, is_named]
298      if (!named) {
299        char buf[256];
300        snprintf(buf, sizeof(buf), "\"%s\"", name);
301        lua_setfield(L, -2, buf);  // [retval, symbols]
302      } else {
303        lua_setfield(L, -2, name);  // [retval, symbols]
304      }
305    }
306
307    lua_setfield(L, -2, "symbols");  // [retval]
308  }
309
310  {  // Fields
311    uint32_t nfields = ts_language_field_count(lang);
312    lua_createtable(L, (int)nfields, 1);  // [retval, fields]
313    // Field IDs go from 1 to nfields inclusive (extra index 0 maps to NULL)
314    for (uint32_t i = 1; i <= nfields; i++) {
315      lua_pushstring(L, ts_language_field_name_for_id(lang, (TSFieldId)i));
316      lua_rawseti(L, -2, (int)i);  // [retval, fields]
317    }
318
319    lua_setfield(L, -2, "fields");  // [retval]
320  }
321
322  lua_pushboolean(L, ts_language_is_wasm(lang));
323  lua_setfield(L, -2, "_wasm");
324
325  lua_pushinteger(L, ts_language_abi_version(lang));  // [retval, version]
326  lua_setfield(L, -2, "abi_version");
327
328  {  // Metadata
329    const TSLanguageMetadata *meta = ts_language_metadata(lang);
330
331    if (meta != NULL) {
332      lua_createtable(L, 0, 3);
333
334      lua_pushinteger(L, meta->major_version);
335      lua_setfield(L, -2, "major_version");
336      lua_pushinteger(L, meta->minor_version);
337      lua_setfield(L, -2, "minor_version");
338      lua_pushinteger(L, meta->patch_version);
339      lua_setfield(L, -2, "patch_version");
340
341      lua_setfield(L, -2, "metadata");
342    }
343  }
344
345  lua_pushinteger(L, ts_language_state_count(lang));
346  lua_setfield(L, -2, "state_count");
347
348  {  // Supertypes
349    uint32_t nsupertypes;
350    const TSSymbol *supertypes = ts_language_supertypes(lang, &nsupertypes);
351
352    lua_createtable(L, 0, (int)nsupertypes);  // [retval, supertypes]
353    for (uint32_t i = 0; i < nsupertypes; i++) {
354      const TSSymbol supertype = *(supertypes + i);
355
356      uint32_t nsubtypes;
357      const TSSymbol *subtypes = ts_language_subtypes(lang, supertype, &nsubtypes);
358
359      lua_createtable(L, (int)nsubtypes, 0);
360      for (uint32_t j = 1; j <= nsubtypes; j++) {
361        lua_pushstring(L, ts_language_symbol_name(lang, *(subtypes + j)));
362        lua_rawseti(L, -2, (int)j);
363      }
364
365      lua_setfield(L, -2, ts_language_symbol_name(lang, supertype));
366    }
367
368    lua_setfield(L, -2, "supertypes");  // [retval]
369  }
370
371  return 1;
372}
373
374// TSParser
375
376static struct luaL_Reg parser_meta[] = {
377  { "__gc", parser_gc },
378  { "__tostring", parser_tostring },
379  { "parse", parser_parse },
380  { "reset", parser_reset },
381  { "set_included_ranges", parser_set_ranges },
382  { "included_ranges", parser_get_ranges },
383  { "_set_logger", parser_set_logger },
384  { "_logger", parser_get_logger },
385  { NULL, NULL }
386};
387
388static int tslua_push_parser(lua_State *L)
389{
390  TSLanguage *lang = lang_check(L, 1);
391
392  TSParser **parser = lua_newuserdata(L, sizeof(TSParser *));
393  *parser = ts_parser_new();
394
395#ifdef HAVE_WASMTIME
396  if (ts_language_is_wasm(lang)) {
397    assert(wasmengine != NULL);
398    TSWasmError werr = { 0 };
399    TSWasmStore *store = ts_wasm_store_new(wasmengine, &werr);
400    if (werr.kind != TSWasmErrorKindNone) {
401      ts_parser_delete(*parser);
402      return luaL_error(L, "Failed to create WASM store: (%s) %s",
403                        wasmerr_to_str(werr.kind), werr.message);
404    }
405    ts_parser_set_wasm_store(*parser, store);
406  }
407#endif
408
409  if (!ts_parser_set_language(*parser, lang)) {
410    ts_parser_delete(*parser);
411    const char *lang_name = luaL_checkstring(L, 1);
412    return luaL_error(L, "Failed to load language : %s", lang_name);
413  }
414
415  lua_getfield(L, LUA_REGISTRYINDEX, TS_META_PARSER);  // [udata, meta]
416  lua_setmetatable(L, -2);  // [udata]
417  return 1;
418}
419
420static TSParser *parser_check(lua_State *L, int index)
421{
422  TSParser **ud = luaL_checkudata(L, index, TS_META_PARSER);
423  luaL_argcheck(L, *ud != NULL, index, "Parser has been deleted");
424  return *ud;
425}
426
427static void logger_gc(TSLogger logger)
428{
429  if (!logger.log) {
430    return;
431  }
432
433  TSLuaLoggerOpts *opts = (TSLuaLoggerOpts *)logger.payload;
434  luaL_unref(opts->lstate, LUA_REGISTRYINDEX, opts->cb);
435  xfree(opts);
436}
437
438static int parser_gc(lua_State *L)
439{
440  TSParser **ud = luaL_checkudata(L, 1, TS_META_PARSER);
441  if (*ud) {
442    logger_gc(ts_parser_logger(*ud));
443    ts_parser_delete(*ud);
444    *ud = NULL;
445  }
446  return 0;
447}
448
449static int parser_tostring(lua_State *L)
450{
451  lua_pushstring(L, "<parser>");
452  return 1;
453}
454
455static const char *input_cb(void *payload, uint32_t byte_index, TSPoint position,
456                            uint32_t *bytes_read)
457{
458  buf_T *bp = payload;
459#define BUFSIZE 256
460  static char buf[BUFSIZE];
461
462  if ((linenr_T)position.row >= bp->b_ml.ml_line_count) {
463    *bytes_read = 0;
464    return "";
465  }
466  linenr_T lnum = (linenr_T)position.row + 1;
467  char *line = ml_get_buf(bp, lnum);
468  size_t len = (size_t)ml_get_buf_len(bp, lnum);
469  if (position.column > len) {
470    *bytes_read = 0;
471    return "";
472  }
473  size_t tocopy = MIN(len - position.column, BUFSIZE);
474
475  memcpy(buf, line + position.column, tocopy);
476  // Translate embedded \n to NUL
477  memchrsub(buf, '\n', NUL, tocopy);
478  *bytes_read = (uint32_t)tocopy;
479  if (tocopy < BUFSIZE) {
480    // now add the final \n, if it is meant to be present for this buffer. If it didn't fit,
481    // input_cb will be called again on the same line with advanced column.
482    if (lnum != bp->b_ml.ml_line_count || (!bp->b_p_bin && bp->b_p_fixeol)
483        || (lnum != bp->b_no_eol_lnum && bp->b_p_eol)) {
484      buf[tocopy] = '\n';
485      (*bytes_read)++;
486    }
487  }
488  return buf;
489#undef BUFSIZE
490}
491
492static void push_ranges(lua_State *L, const TSRange *ranges, const size_t length,
493                        bool include_bytes)
494{
495  lua_createtable(L, (int)length, 0);
496  for (size_t i = 0; i < length; i++) {
497    lua_createtable(L, include_bytes ? 6 : 4, 0);
498    int j = 1;
499    lua_pushnumber(L, (lua_Number)ranges[i].start_point.row);
500    lua_rawseti(L, -2, j++);
501    lua_pushnumber(L, (lua_Number)ranges[i].start_point.column);
502    lua_rawseti(L, -2, j++);
503    if (include_bytes) {
504      lua_pushnumber(L, (lua_Number)ranges[i].start_byte);
505      lua_rawseti(L, -2, j++);
506    }
507    lua_pushnumber(L, (lua_Number)ranges[i].end_point.row);
508    lua_rawseti(L, -2, j++);
509    lua_pushnumber(L, (lua_Number)ranges[i].end_point.column);
510    lua_rawseti(L, -2, j++);
511    if (include_bytes) {
512      lua_pushnumber(L, (lua_Number)ranges[i].end_byte);
513      lua_rawseti(L, -2, j++);
514    }
515
516    lua_rawseti(L, -2, (int)(i + 1));
517  }
518}
519
520static bool on_parser_progress(TSParseState *state)
521{
522  TSLuaParserCallbackPayload *payload = state->payload;
523  uint64_t parse_time = os_hrtime() - payload->parse_start_time;
524  return parse_time >= payload->timeout_threshold_ns;
525}
526
527TSTree *nts_parser_parse_buf(TSParser *p, const TSTree *old_tree, int bufnr, uint64_t timeout_ns)
528{
529  buf_T *buf = handle_get_buffer(bufnr);
530
531  if (!buf) {
532    abort();
533  }
534
535  TSInput input = (TSInput){ (void *)buf, input_cb, TSInputEncodingUTF8, NULL };
536
537  if (timeout_ns == 0) {
538    return ts_parser_parse(p, old_tree, input);
539  }
540
541  TSLuaParserCallbackPayload payload = (TSLuaParserCallbackPayload){
542    .parse_start_time = os_hrtime(),
543    .timeout_threshold_ns = timeout_ns
544  };
545
546  TSParseOptions parse_options = {
547    .payload = &payload,
548    .progress_callback = on_parser_progress
549  };
550
551  return ts_parser_parse_with_options(p, old_tree, input, parse_options);
552}
553
554static int parser_parse(lua_State *L)
555{
556  TSParser *p = parser_check(L, 1);
557  const TSTree *old_tree = NULL;
558  if (!lua_isnil(L, 2)) {
559    TSLuaTree *ud = luaL_checkudata(L, 2, TS_META_TREE);
560    old_tree = ud ? ud->tree : NULL;
561  }
562
563  TSTree *new_tree = NULL;
564
565  // This switch is necessary because of the behavior of lua_isstring, that
566  // consider numbers as strings...
567  switch (lua_type(L, 3)) {
568  case LUA_TSTRING: {
569    size_t len;
570    const char *str = lua_tolstring(L, 3, &len);
571    new_tree = ts_parser_parse_string(p, old_tree, str, (uint32_t)len);
572    break;
573  }
574  case LUA_TNUMBER: {
575    handle_T bufnr = (handle_T)lua_tointeger(L, 3);
576    buf_T *buf = handle_get_buffer(bufnr);
577
578    if (!buf) {
579      char ebuf[IOSIZE] = { 0 };
580      vim_snprintf(ebuf, IOSIZE, "invalid buffer handle: %d", bufnr);
581      return luaL_argerror(L, 3, ebuf);
582    }
583
584    uint64_t timeout_ns = lua_isnil(L, 5) ? 0 : (uint64_t)lua_tointeger(L, 5);
585    new_tree = nts_parser_parse_buf(p, old_tree, bufnr, timeout_ns);
586    break;
587  }
588  default:
589    return luaL_argerror(L, 3, "expected either string or buffer handle");
590  }
591
592  bool include_bytes = (lua_gettop(L) >= 4) && lua_toboolean(L, 4);
593
594  if (!new_tree) {
595    // Sometimes parsing fails (no language was set, or it was set to one with an incompatible ABI)
596    // In those cases, just return an error.
597    if (!ts_parser_language(p)) {
598      return luaL_error(L, "Language was unset, or has an incompatible ABI.");
599    }
600    return 0;
601  }
602
603  // The new tree will be pushed to the stack, without copy, ownership is now to the lua GC.
604  // Old tree is owned by lua GC since before
605  uint32_t n_ranges = 0;
606  TSRange *changed = old_tree ? ts_tree_get_changed_ranges(old_tree, new_tree, &n_ranges)
607                              : ts_tree_included_ranges(new_tree, &n_ranges);
608
609  push_tree(L, new_tree);  // [tree]
610
611  push_ranges(L, changed, n_ranges, include_bytes);  // [tree, ranges]
612
613  xfree(changed);
614  return 2;
615}
616
617static int parser_reset(lua_State *L)
618{
619  TSParser *p = parser_check(L, 1);
620  ts_parser_reset(p);
621  return 0;
622}
623
624static void range_err(lua_State *L)
625{
626  luaL_error(L, "Ranges can only be made from 6 element long tables or nodes.");
627}
628
629static uint32_t lua_checkuint32(lua_State *L, int index)
630{
631  lua_Number value = luaL_checknumber(L, index);
632  uint32_t converted = (uint32_t)value;
633  if (value < 0 || value > (lua_Number)UINT32_MAX || (lua_Number)converted != value) {
634    luaL_error(L, "Range value out of bounds");
635  }
636  return converted;
637}
638
639// Use the top of the stack (without popping it) to create a TSRange, it can be
640// either a lua table or a TSNode
641static void range_from_lua(lua_State *L, TSRange *range)
642{
643  TSNode node;
644
645  if (lua_istable(L, -1)) {
646    // should be a table of 6 elements
647    if (lua_objlen(L, -1) != 6) {
648      range_err(L);
649    }
650
651    lua_rawgeti(L, -1, 1);  // [ range, start_row]
652    uint32_t start_row = lua_checkuint32(L, -1);
653    lua_pop(L, 1);
654
655    lua_rawgeti(L, -1, 2);  // [ range, start_col]
656    uint32_t start_col = lua_checkuint32(L, -1);
657    lua_pop(L, 1);
658
659    lua_rawgeti(L, -1, 3);  // [ range, start_byte]
660    uint32_t start_byte = lua_checkuint32(L, -1);
661    lua_pop(L, 1);
662
663    lua_rawgeti(L, -1, 4);  // [ range, end_row]
664    uint32_t end_row = lua_checkuint32(L, -1);
665    lua_pop(L, 1);
666
667    lua_rawgeti(L, -1, 5);  // [ range, end_col]
668    uint32_t end_col = lua_checkuint32(L, -1);
669    lua_pop(L, 1);
670
671    lua_rawgeti(L, -1, 6);  // [ range, end_byte]
672    uint32_t end_byte = lua_checkuint32(L, -1);
673    lua_pop(L, 1);  // [ range ]
674
675    *range = (TSRange) {
676      .start_point = (TSPoint) {
677        .row = start_row,
678        .column = start_col
679      },
680      .end_point = (TSPoint) {
681        .row = end_row,
682        .column = end_col
683      },
684      .start_byte = start_byte,
685      .end_byte = end_byte,
686    };
687  } else if (node_check_opt(L, -1, &node)) {
688    *range = (TSRange) {
689      .start_point = ts_node_start_point(node),
690      .end_point = ts_node_end_point(node),
691      .start_byte = ts_node_start_byte(node),
692      .end_byte = ts_node_end_byte(node)
693    };
694  } else {
695    range_err(L);
696  }
697}
698
699static int parser_set_ranges(lua_State *L)
700{
701  if (lua_gettop(L) < 2) {
702    return luaL_error(L, "not enough args to parser:set_included_ranges()");
703  }
704
705  TSParser *p = parser_check(L, 1);
706
707  luaL_argcheck(L, lua_istable(L, 2), 2, "table expected.");
708
709  size_t tbl_len = lua_objlen(L, 2);
710  TSRange *ranges = xmalloc(sizeof(TSRange) * tbl_len);
711
712  // [ parser, ranges ]
713  for (size_t index = 0; index < tbl_len; index++) {
714    lua_rawgeti(L, 2, (int)index + 1);  // [ parser, ranges, range ]
715    range_from_lua(L, ranges + index);
716    lua_pop(L, 1);
717  }
718
719  // This memcpies ranges, thus we can free it afterwards
720  ts_parser_set_included_ranges(p, ranges, (uint32_t)tbl_len);
721  xfree(ranges);
722
723  return 0;
724}
725
726static int parser_get_ranges(lua_State *L)
727{
728  TSParser *p = parser_check(L, 1);
729
730  bool include_bytes = (lua_gettop(L) >= 2) && lua_toboolean(L, 2);
731
732  uint32_t len;
733  const TSRange *ranges = ts_parser_included_ranges(p, &len);
734
735  push_ranges(L, ranges, len, include_bytes);
736  return 1;
737}
738
739static void logger_cb(void *payload, TSLogType logtype, const char *s)
740{
741  TSLuaLoggerOpts *opts = (TSLuaLoggerOpts *)payload;
742  if ((!opts->lex && logtype == TSLogTypeLex)
743      || (!opts->parse && logtype == TSLogTypeParse)) {
744    return;
745  }
746
747  lua_State *lstate = opts->lstate;
748
749  lua_rawgeti(lstate, LUA_REGISTRYINDEX, opts->cb);
750  lua_pushstring(lstate, logtype == TSLogTypeParse ? "parse" : "lex");
751  lua_pushstring(lstate, s);
752  if (lua_pcall(lstate, 2, 0, 0)) {
753    luaL_error(lstate, "treesitter logger callback failed");
754  }
755}
756
757static int parser_set_logger(lua_State *L)
758{
759  TSParser *p = parser_check(L, 1);
760
761  luaL_argcheck(L, lua_isboolean(L, 2), 2, "boolean expected");
762  luaL_argcheck(L, lua_isboolean(L, 3), 3, "boolean expected");
763  luaL_argcheck(L, lua_isfunction(L, 4), 4, "function expected");
764
765  TSLuaLoggerOpts *opts = xmalloc(sizeof(TSLuaLoggerOpts));
766  lua_pushvalue(L, 4);
767  LuaRef ref = luaL_ref(L, LUA_REGISTRYINDEX);
768
769  *opts = (TSLuaLoggerOpts){
770    .lex = lua_toboolean(L, 2),
771    .parse = lua_toboolean(L, 3),
772    .cb = ref,
773    .lstate = L
774  };
775
776  TSLogger logger = {
777    .payload = (void *)opts,
778    .log = logger_cb
779  };
780
781  ts_parser_set_logger(p, logger);
782  return 0;
783}
784
785static int parser_get_logger(lua_State *L)
786{
787  TSParser *p = parser_check(L, 1);
788  TSLogger logger = ts_parser_logger(p);
789  if (logger.log) {
790    TSLuaLoggerOpts *opts = (TSLuaLoggerOpts *)logger.payload;
791    lua_rawgeti(L, LUA_REGISTRYINDEX, opts->cb);
792  } else {
793    lua_pushnil(L);
794  }
795
796  return 1;
797}
798
799// TSTree
800
801static struct luaL_Reg tree_meta[] = {
802  { "__gc", tree_gc },
803  { "__tostring", tree_tostring },
804  { "root", tree_root },
805  { "edit", tree_edit },
806  { "included_ranges", tree_get_ranges },
807  { "copy", tree_copy },
808  { NULL, NULL }
809};
810
811/// Push tree interface on to the lua stack.
812///
813/// The tree is not copied. Ownership of the tree is transferred from C to
814/// Lua. If needed use ts_tree_copy() in the caller.
815static void push_tree(lua_State *L, const TSTree *tree)
816{
817  if (tree == NULL) {
818    lua_pushnil(L);
819    return;
820  }
821
822  TSLuaTree *ud = lua_newuserdata(L, sizeof(TSLuaTree));  // [udata]
823  ud->tree = tree;
824  lua_getfield(L, LUA_REGISTRYINDEX, TS_META_TREE);  // [udata, meta]
825  lua_setmetatable(L, -2);  // [udata]
826}
827
828static int tree_copy(lua_State *L)
829{
830  TSLuaTree *ud = luaL_checkudata(L, 1, TS_META_TREE);
831  TSTree *copy = ts_tree_copy(ud->tree);
832  push_tree(L, copy);  // [tree]
833
834  return 1;
835}
836
837static int tree_edit(lua_State *L)
838{
839  if (lua_gettop(L) < 10) {
840    lua_pushstring(L, "not enough args to tree:edit()");
841    return lua_error(L);
842  }
843
844  TSLuaTree *ud = luaL_checkudata(L, 1, TS_META_TREE);
845
846  uint32_t start_byte = (uint32_t)luaL_checkint(L, 2);
847  uint32_t old_end_byte = (uint32_t)luaL_checkint(L, 3);
848  uint32_t new_end_byte = (uint32_t)luaL_checkint(L, 4);
849  TSPoint start_point = { (uint32_t)luaL_checkint(L, 5), (uint32_t)luaL_checkint(L, 6) };
850  TSPoint old_end_point = { (uint32_t)luaL_checkint(L, 7), (uint32_t)luaL_checkint(L, 8) };
851  TSPoint new_end_point = { (uint32_t)luaL_checkint(L, 9), (uint32_t)luaL_checkint(L, 10) };
852
853  TSInputEdit edit = { start_byte, old_end_byte, new_end_byte,
854                       start_point, old_end_point, new_end_point };
855
856  TSTree *new_tree = ts_tree_copy(ud->tree);
857  ts_tree_edit(new_tree, &edit);
858
859  push_tree(L, new_tree);  // [tree]
860
861  return 1;
862}
863
864static int tree_get_ranges(lua_State *L)
865{
866  TSLuaTree *ud = luaL_checkudata(L, 1, TS_META_TREE);
867
868  bool include_bytes = (lua_gettop(L) >= 2) && lua_toboolean(L, 2);
869
870  uint32_t len;
871  TSRange *ranges = ts_tree_included_ranges(ud->tree, &len);
872
873  push_ranges(L, ranges, len, include_bytes);
874
875  xfree(ranges);
876  return 1;
877}
878
879static int tree_gc(lua_State *L)
880{
881  TSLuaTree *ud = luaL_checkudata(L, 1, TS_META_TREE);
882
883  // SAFETY: we can cast the const away because the tree is only garbage collected after all of its
884  // TSNode's, TSQuerCurors, etc., are unreachable (each contains a reference to the TSLuaTree)
885  TSTree *tree = (TSTree *)ud->tree;
886
887  ts_tree_delete(tree);
888  return 0;
889}
890
891static int tree_tostring(lua_State *L)
892{
893  lua_pushstring(L, "<tree>");
894  return 1;
895}
896
897static int tree_root(lua_State *L)
898{
899  TSLuaTree *ud = luaL_checkudata(L, 1, TS_META_TREE);
900
901  TSNode root = ts_tree_root_node(ud->tree);
902
903  TSNode *node_ud = lua_newuserdata(L, sizeof(TSNode));  // [node]
904  *node_ud = root;
905  lua_getfield(L, LUA_REGISTRYINDEX, TS_META_NODE);  // [node, meta]
906  lua_setmetatable(L, -2);  // [node]
907
908  // To prevent the tree from being garbage collected, create a reference to it
909  // in the fenv which will be passed to userdata nodes of the tree.
910  // Note: environments (fenvs) associated with userdata have no meaning in Lua
911  // and are only used to associate a table.
912  lua_createtable(L, 1, 0);  // [node, reftable]
913  lua_pushvalue(L, 1);  // [node, reftable, tree]
914  lua_rawseti(L, -2, 1);  // [node, reftable]
915  lua_setfenv(L, -2);  // [node]
916
917  return 1;
918}
919
920// TSNode
921static struct luaL_Reg node_meta[] = {
922  { "__tostring", node_tostring },
923  { "__eq", node_eq },
924  { "__len", node_child_count },
925  { "id", node_id },
926  { "range", node_range },
927  { "start", node_start },
928  { "end_", node_end },
929  { "type", node_type },
930  { "symbol", node_symbol },
931  { "field", node_field },
932  { "named", node_named },
933  { "missing", node_missing },
934  { "extra", node_extra },
935  { "has_changes", node_has_changes },
936  { "has_error", node_has_error },
937  { "sexpr", node_sexpr },
938  { "child_count", node_child_count },
939  { "named_child_count", node_named_child_count },
940  { "child", node_child },
941  { "named_child", node_named_child },
942  { "descendant_for_range", node_descendant_for_range },
943  { "named_descendant_for_range", node_named_descendant_for_range },
944  { "parent", node_parent },
945  { "__has_ancestor", __has_ancestor },
946  { "child_with_descendant", node_child_with_descendant },
947  { "iter_children", node_iter_children },
948  { "next_sibling", node_next_sibling },
949  { "prev_sibling", node_prev_sibling },
950  { "next_named_sibling", node_next_named_sibling },
951  { "prev_named_sibling", node_prev_named_sibling },
952  { "named_children", node_named_children },
953  { "root", node_root },
954  { "tree", node_tree },
955  { "byte_length", node_byte_length },
956  { "equal", node_equal },
957
958  { NULL, NULL }
959};
960
961/// Push node interface on to the Lua stack
962///
963/// Stack at `uindex` must have a value with a fenv with a reference to node's
964/// tree. This value is not popped. Can only be called inside a cfunction with
965/// the tslua environment.
966static void push_node(lua_State *L, TSNode node, int uindex)
967{
968  assert(uindex > 0 || uindex < -LUA_MINSTACK);
969  if (ts_node_is_null(node)) {
970    lua_pushnil(L);  // [nil]
971    return;
972  }
973
974  TSNode *ud = lua_newuserdata(L, sizeof(TSNode));  // [udata]
975  *ud = node;
976  lua_getfield(L, LUA_REGISTRYINDEX, TS_META_NODE);  // [udata, meta]
977  lua_setmetatable(L, -2);  // [udata]
978
979  // Copy the fenv to keep alive a reference to the node's tree.
980  lua_getfenv(L, uindex);  // [udata, reftable]
981  lua_setfenv(L, -2);  // [udata]
982}
983
984static bool node_check_opt(lua_State *L, int index, TSNode *res)
985{
986  TSNode *ud = luaL_checkudata(L, index, TS_META_NODE);
987  if (ud) {
988    *res = *ud;
989    return true;
990  }
991  return false;
992}
993
994static TSNode node_check(lua_State *L, int index)
995{
996  TSNode *ud = luaL_checkudata(L, index, TS_META_NODE);
997  return *ud;
998}
999
1000static int node_tostring(lua_State *L)
1001{
1002  TSNode node = node_check(L, 1);
1003  lua_pushstring(L, "<node ");
1004  lua_pushstring(L, ts_node_type(node));
1005  lua_pushstring(L, ">");
1006  lua_concat(L, 3);
1007  return 1;
1008}
1009
1010static int node_eq(lua_State *L)
1011{
1012  TSNode node = node_check(L, 1);
1013  TSNode node2 = node_check(L, 2);
1014  lua_pushboolean(L, ts_node_eq(node, node2));
1015  return 1;
1016}
1017
1018static int node_id(lua_State *L)
1019{
1020  TSNode node = node_check(L, 1);
1021  lua_pushlstring(L, (const char *)&node.id, sizeof node.id);
1022  return 1;
1023}
1024
1025static int node_range(lua_State *L)
1026{
1027  TSNode node = node_check(L, 1);
1028
1029  bool include_bytes = (lua_gettop(L) >= 2) && lua_toboolean(L, 2);
1030
1031  TSPoint start = ts_node_start_point(node);
1032  TSPoint end = ts_node_end_point(node);
1033
1034  if (include_bytes) {
1035    lua_pushinteger(L, start.row);
1036    lua_pushinteger(L, start.column);
1037    lua_pushinteger(L, ts_node_start_byte(node));
1038    lua_pushinteger(L, end.row);
1039    lua_pushinteger(L, end.column);
1040    lua_pushinteger(L, ts_node_end_byte(node));
1041    return 6;
1042  }
1043
1044  lua_pushinteger(L, start.row);
1045  lua_pushinteger(L, start.column);
1046  lua_pushinteger(L, end.row);
1047  lua_pushinteger(L, end.column);
1048  return 4;
1049}
1050
1051static int node_start(lua_State *L)
1052{
1053  TSNode node = node_check(L, 1);
1054  TSPoint start = ts_node_start_point(node);
1055  uint32_t start_byte = ts_node_start_byte(node);
1056  lua_pushinteger(L, start.row);
1057  lua_pushinteger(L, start.column);
1058  lua_pushinteger(L, start_byte);
1059  return 3;
1060}
1061
1062static int node_end(lua_State *L)
1063{
1064  TSNode node = node_check(L, 1);
1065  TSPoint end = ts_node_end_point(node);
1066  uint32_t end_byte = ts_node_end_byte(node);
1067  lua_pushinteger(L, end.row);
1068  lua_pushinteger(L, end.column);
1069  lua_pushinteger(L, end_byte);
1070  return 3;
1071}
1072
1073static int node_child_count(lua_State *L)
1074{
1075  TSNode node = node_check(L, 1);
1076  uint32_t count = ts_node_child_count(node);
1077  lua_pushinteger(L, count);
1078  return 1;
1079}
1080
1081static int node_named_child_count(lua_State *L)
1082{
1083  TSNode node = node_check(L, 1);
1084  uint32_t count = ts_node_named_child_count(node);
1085  lua_pushinteger(L, count);
1086  return 1;
1087}
1088
1089static int node_type(lua_State *L)
1090{
1091  TSNode node = node_check(L, 1);
1092  lua_pushstring(L, ts_node_type(node));
1093  return 1;
1094}
1095
1096static int node_symbol(lua_State *L)
1097{
1098  TSNode node = node_check(L, 1);
1099  TSSymbol symbol = ts_node_symbol(node);
1100  lua_pushinteger(L, symbol);
1101  return 1;
1102}
1103
1104static int node_field(lua_State *L)
1105{
1106  TSNode node = node_check(L, 1);
1107  uint32_t count = ts_node_child_count(node);
1108  int curr_index = 0;
1109
1110  size_t name_len;
1111  const char *field_name = luaL_checklstring(L, 2, &name_len);
1112
1113  lua_newtable(L);
1114
1115  for (uint32_t i = 0; i < count; i++) {
1116    const char *child_field_name = ts_node_field_name_for_child(node, i);
1117    if (strequal(field_name, child_field_name)) {
1118      TSNode child = ts_node_child(node, i);
1119      push_node(L, child, 1);
1120      lua_rawseti(L, -2, ++curr_index);
1121    }
1122  }
1123
1124  return 1;
1125}
1126
1127static int node_named(lua_State *L)
1128{
1129  TSNode node = node_check(L, 1);
1130  lua_pushboolean(L, ts_node_is_named(node));
1131  return 1;
1132}
1133
1134static int node_sexpr(lua_State *L)
1135{
1136  TSNode node = node_check(L, 1);
1137  char *allocated = ts_node_string(node);
1138  lua_pushstring(L, allocated);
1139  xfree(allocated);
1140  return 1;
1141}
1142
1143static int node_missing(lua_State *L)
1144{
1145  TSNode node = node_check(L, 1);
1146  lua_pushboolean(L, ts_node_is_missing(node));
1147  return 1;
1148}
1149
1150static int node_extra(lua_State *L)
1151{
1152  TSNode node = node_check(L, 1);
1153  lua_pushboolean(L, ts_node_is_extra(node));
1154  return 1;
1155}
1156
1157static int node_has_changes(lua_State *L)
1158{
1159  TSNode node = node_check(L, 1);
1160  lua_pushboolean(L, ts_node_has_changes(node));
1161  return 1;
1162}
1163
1164static int node_has_error(lua_State *L)
1165{
1166  TSNode node = node_check(L, 1);
1167  lua_pushboolean(L, ts_node_has_error(node));
1168  return 1;
1169}
1170
1171static int node_child(lua_State *L)
1172{
1173  TSNode node = node_check(L, 1);
1174  uint32_t num = (uint32_t)lua_tointeger(L, 2);
1175  TSNode child = ts_node_child(node, num);
1176
1177  push_node(L, child, 1);
1178  return 1;
1179}
1180
1181static int node_named_child(lua_State *L)
1182{
1183  TSNode node = node_check(L, 1);
1184  uint32_t num = (uint32_t)lua_tointeger(L, 2);
1185  TSNode child = ts_node_named_child(node, num);
1186
1187  push_node(L, child, 1);
1188  return 1;
1189}
1190
1191static int node_descendant_for_range(lua_State *L)
1192{
1193  TSNode node = node_check(L, 1);
1194  TSPoint start = { (uint32_t)lua_tointeger(L, 2),
1195                    (uint32_t)lua_tointeger(L, 3) };
1196  TSPoint end = { (uint32_t)lua_tointeger(L, 4),
1197                  (uint32_t)lua_tointeger(L, 5) };
1198  TSNode child = ts_node_descendant_for_point_range(node, start, end);
1199
1200  push_node(L, child, 1);
1201  return 1;
1202}
1203
1204static int node_named_descendant_for_range(lua_State *L)
1205{
1206  TSNode node = node_check(L, 1);
1207  TSPoint start = { (uint32_t)lua_tointeger(L, 2),
1208                    (uint32_t)lua_tointeger(L, 3) };
1209  TSPoint end = { (uint32_t)lua_tointeger(L, 4),
1210                  (uint32_t)lua_tointeger(L, 5) };
1211  TSNode child = ts_node_named_descendant_for_point_range(node, start, end);
1212
1213  push_node(L, child, 1);
1214  return 1;
1215}
1216
1217static int node_next_child(lua_State *L)
1218{
1219  uint32_t *child_index = lua_touserdata(L, lua_upvalueindex(1));
1220  TSNode source = node_check(L, lua_upvalueindex(2));
1221
1222  if (*child_index >= ts_node_child_count(source)) {
1223    return 0;
1224  }
1225
1226  TSNode child = ts_node_child(source, *child_index);
1227  push_node(L, child, lua_upvalueindex(2));
1228
1229  const char *field = ts_node_field_name_for_child(source, *child_index);
1230  if (field != NULL) {
1231    lua_pushstring(L, field);
1232  } else {
1233    lua_pushnil(L);
1234  }  // [node, field_name_or_nil]
1235
1236  (*child_index)++;
1237
1238  return 2;
1239}
1240
1241static int node_iter_children(lua_State *L)
1242{
1243  node_check(L, 1);
1244  uint32_t *child_index = lua_newuserdata(L, sizeof(uint32_t));  // [source_node,..., udata]
1245  *child_index = 0;
1246
1247  lua_pushvalue(L, 1);  // [source_node, ..., udata, source_node]
1248  lua_pushcclosure(L, node_next_child, 2);
1249
1250  return 1;
1251}
1252
1253static int node_parent(lua_State *L)
1254{
1255  TSNode node = node_check(L, 1);
1256  TSNode parent = ts_node_parent(node);
1257  push_node(L, parent, 1);
1258  return 1;
1259}
1260
1261static int __has_ancestor(lua_State *L)
1262{
1263  TSNode descendant = node_check(L, 1);
1264  if (lua_type(L, 2) != LUA_TTABLE) {
1265    lua_pushboolean(L, false);
1266    return 1;
1267  }
1268  int const pred_len = (int)lua_objlen(L, 2);
1269
1270  TSNode node = ts_tree_root_node(descendant.tree);
1271  while (node.id != descendant.id && !ts_node_is_null(node)) {
1272    char const *node_type = ts_node_type(node);
1273    size_t node_type_len = strlen(node_type);
1274
1275    for (int i = 3; i <= pred_len; i++) {
1276      lua_rawgeti(L, 2, i);
1277      if (lua_type(L, -1) == LUA_TSTRING) {
1278        size_t check_len;
1279        char const *check_str = lua_tolstring(L, -1, &check_len);
1280        if (node_type_len == check_len && memcmp(node_type, check_str, check_len) == 0) {
1281          lua_pushboolean(L, true);
1282          return 1;
1283        }
1284      }
1285      lua_pop(L, 1);
1286    }
1287
1288    node = ts_node_child_with_descendant(node, descendant);
1289  }
1290
1291  lua_pushboolean(L, false);
1292  return 1;
1293}
1294
1295static int node_child_with_descendant(lua_State *L)
1296{
1297  TSNode node = node_check(L, 1);
1298  TSNode descendant = node_check(L, 2);
1299  TSNode child = ts_node_child_with_descendant(node, descendant);
1300  push_node(L, child, 1);
1301  return 1;
1302}
1303
1304static int node_next_sibling(lua_State *L)
1305{
1306  TSNode node = node_check(L, 1);
1307  TSNode sibling = ts_node_next_sibling(node);
1308  push_node(L, sibling, 1);
1309  return 1;
1310}
1311
1312static int node_prev_sibling(lua_State *L)
1313{
1314  TSNode node = node_check(L, 1);
1315  TSNode sibling = ts_node_prev_sibling(node);
1316  push_node(L, sibling, 1);
1317  return 1;
1318}
1319
1320static int node_next_named_sibling(lua_State *L)
1321{
1322  TSNode node = node_check(L, 1);
1323  TSNode sibling = ts_node_next_named_sibling(node);
1324  push_node(L, sibling, 1);
1325  return 1;
1326}
1327
1328static int node_prev_named_sibling(lua_State *L)
1329{
1330  TSNode node = node_check(L, 1);
1331  TSNode sibling = ts_node_prev_named_sibling(node);
1332  push_node(L, sibling, 1);
1333  return 1;
1334}
1335
1336static int node_named_children(lua_State *L)
1337{
1338  TSNode source = node_check(L, 1);
1339
1340  lua_newtable(L);
1341  int curr_index = 0;
1342
1343  uint32_t n = ts_node_child_count(source);
1344  for (uint32_t i = 0; i < n; i++) {
1345    TSNode child = ts_node_child(source, i);
1346    if (ts_node_is_named(child)) {
1347      push_node(L, child, 1);
1348      lua_rawseti(L, -2, ++curr_index);
1349    }
1350  }
1351
1352  return 1;
1353}
1354
1355static int node_root(lua_State *L)
1356{
1357  TSNode node = node_check(L, 1);
1358  TSNode root = ts_tree_root_node(node.tree);
1359  push_node(L, root, 1);
1360  return 1;
1361}
1362
1363static int node_tree(lua_State *L)
1364{
1365  node_check(L, 1);
1366
1367  // Get the tree from the node fenv. We cannot use `push_tree(node.tree)` here because that would
1368  // cause a double free.
1369  lua_getfenv(L, 1);  // [node, reftable]
1370  lua_rawgeti(L, 2, 1);  // [node, reftable, tree]
1371
1372  return 1;
1373}
1374
1375static int node_byte_length(lua_State *L)
1376{
1377  TSNode node = node_check(L, 1);
1378  uint32_t start_byte = ts_node_start_byte(node);
1379  uint32_t end_byte = ts_node_end_byte(node);
1380  lua_pushinteger(L, end_byte - start_byte);
1381  return 1;
1382}
1383
1384static int node_equal(lua_State *L)
1385{
1386  TSNode node1 = node_check(L, 1);
1387  TSNode node2 = node_check(L, 2);
1388  lua_pushboolean(L, ts_node_eq(node1, node2));
1389  return 1;
1390}
1391
1392// TSQueryCursor
1393
1394static struct luaL_Reg querycursor_meta[] = {
1395  { "remove_match", querycursor_remove_match },
1396  { "next_capture", querycursor_next_capture },
1397  { "next_match", querycursor_next_match },
1398  { "__gc", querycursor_gc },
1399  { NULL, NULL }
1400};
1401
1402static int tslua_push_querycursor(lua_State *L)
1403{
1404  TSNode node = node_check(L, 1);
1405
1406  TSQuery *query = query_check(L, 2);
1407  TSQueryCursor *cursor = ts_query_cursor_new();
1408
1409  if (lua_gettop(L) >= 3 && !lua_isnil(L, 3)) {
1410    luaL_argcheck(L, lua_istable(L, 3), 3, "table expected");
1411  }
1412
1413  lua_getfield(L, 3, "start_row");
1414  uint32_t start_row = (uint32_t)luaL_checkinteger(L, -1);
1415  lua_pop(L, 1);
1416
1417  lua_getfield(L, 3, "start_col");
1418  uint32_t start_col = (uint32_t)luaL_checkinteger(L, -1);
1419  lua_pop(L, 1);
1420
1421  lua_getfield(L, 3, "end_row");
1422  uint32_t end_row = (uint32_t)luaL_checkinteger(L, -1);
1423  lua_pop(L, 1);
1424
1425  lua_getfield(L, 3, "end_col");
1426  uint32_t end_col = (uint32_t)luaL_checkinteger(L, -1);
1427  lua_pop(L, 1);
1428
1429  ts_query_cursor_set_point_range(cursor, (TSPoint){ start_row, start_col },
1430                                  (TSPoint){ end_row, end_col });
1431
1432  lua_getfield(L, 3, "max_start_depth");
1433  if (!lua_isnil(L, -1)) {
1434    uint32_t max_start_depth = (uint32_t)luaL_checkinteger(L, -1);
1435    ts_query_cursor_set_max_start_depth(cursor, max_start_depth);
1436  }
1437  lua_pop(L, 1);
1438
1439  lua_getfield(L, 3, "match_limit");
1440  if (!lua_isnil(L, -1)) {
1441    uint32_t match_limit = (uint32_t)luaL_checkinteger(L, -1);
1442    ts_query_cursor_set_match_limit(cursor, match_limit);
1443  }
1444  lua_pop(L, 1);
1445
1446  ts_query_cursor_exec(cursor, query, node);
1447
1448  TSQueryCursor **ud = lua_newuserdata(L, sizeof(*ud));  // [node, query, ..., udata]
1449  *ud = cursor;
1450  lua_getfield(L, LUA_REGISTRYINDEX, TS_META_QUERYCURSOR);  // [node, query, ..., udata, meta]
1451  lua_setmetatable(L, -2);  // [node, query, ..., udata]
1452
1453  // Copy the fenv which contains the nodes tree.
1454  lua_getfenv(L, 1);  // [udata, reftable]
1455  lua_setfenv(L, -2);  // [udata]
1456
1457  return 1;
1458}
1459
1460static int querycursor_remove_match(lua_State *L)
1461{
1462  TSQueryCursor *cursor = querycursor_check(L, 1);
1463  uint32_t match_id = (uint32_t)luaL_checkinteger(L, 2);
1464  ts_query_cursor_remove_match(cursor, match_id);
1465  return 0;
1466}
1467
1468static int querycursor_next_capture(lua_State *L)
1469{
1470  TSQueryCursor *cursor = querycursor_check(L, 1);
1471  TSQueryMatch match;
1472  uint32_t capture_index;
1473  if (!ts_query_cursor_next_capture(cursor, &match, &capture_index)) {
1474    return 0;
1475  }
1476
1477  TSQueryCapture capture = match.captures[capture_index];
1478
1479  // Handle capture quantifiers here
1480  lua_pushinteger(L, capture.index + 1);  // [index]
1481  push_node(L, capture.node, 1);  // [index, node]
1482  push_querymatch(L, &match, 1);
1483
1484  return 3;
1485}
1486
1487static int querycursor_next_match(lua_State *L)
1488{
1489  TSQueryCursor *cursor = querycursor_check(L, 1);
1490
1491  TSQueryMatch match;
1492  if (!ts_query_cursor_next_match(cursor, &match)) {
1493    return 0;
1494  }
1495
1496  push_querymatch(L, &match, 1);
1497
1498  return 1;
1499}
1500
1501static TSQueryCursor *querycursor_check(lua_State *L, int index)
1502{
1503  TSQueryCursor **ud = luaL_checkudata(L, index, TS_META_QUERYCURSOR);
1504  luaL_argcheck(L, *ud, index, "TSQueryCursor expected");
1505  return *ud;
1506}
1507
1508static int querycursor_gc(lua_State *L)
1509{
1510  TSQueryCursor *cursor = querycursor_check(L, 1);
1511  ts_query_cursor_delete(cursor);
1512  return 0;
1513}
1514
1515// TSQueryMatch
1516
1517static struct luaL_Reg querymatch_meta[] = {
1518  { "info", querymatch_info },
1519  { "captures", querymatch_captures },
1520  { NULL, NULL }
1521};
1522
1523static void push_querymatch(lua_State *L, TSQueryMatch *match, int uindex)
1524{
1525  TSQueryMatch *ud = lua_newuserdata(L, sizeof(TSQueryMatch));  // [udata]
1526  *ud = *match;
1527  lua_getfield(L, LUA_REGISTRYINDEX, TS_META_QUERYMATCH);  // [udata, meta]
1528  lua_setmetatable(L, -2);  // [udata]
1529
1530  // Copy the fenv which contains the nodes tree.
1531  lua_getfenv(L, uindex);  // [udata, reftable]
1532  lua_setfenv(L, -2);  // [udata]
1533}
1534
1535static int querymatch_info(lua_State *L)
1536{
1537  TSQueryMatch *match = luaL_checkudata(L, 1, TS_META_QUERYMATCH);
1538  lua_pushinteger(L, match->id);
1539  lua_pushinteger(L, match->pattern_index + 1);
1540  return 2;
1541}
1542
1543static int querymatch_captures(lua_State *L)
1544{
1545  TSQueryMatch *match = luaL_checkudata(L, 1, TS_META_QUERYMATCH);
1546  lua_newtable(L);  // [match, nodes, captures]
1547  for (size_t i = 0; i < match->capture_count; i++) {
1548    TSQueryCapture capture = match->captures[i];
1549    int index = (int)capture.index + 1;
1550
1551    lua_rawgeti(L, -1, index);  // [match, node, captures]
1552    if (lua_isnil(L, -1)) {  // [match, node, captures, nil]
1553      lua_pop(L, 1);  // [match, node, captures]
1554      lua_newtable(L);  // [match, node, captures, nodes]
1555    }
1556    push_node(L, capture.node, 1);  // [match, node, captures, nodes, node]
1557    lua_rawseti(L, -2, (int)lua_objlen(L, -2) + 1);  // [match, node, captures, nodes]
1558    lua_rawseti(L, -2, index);  // [match, node, captures]
1559  }
1560  return 1;
1561}
1562
1563// TSQuery
1564
1565static struct luaL_Reg query_meta[] = {
1566  { "__gc", query_gc },
1567  { "__tostring", query_tostring },
1568  { "inspect", query_inspect },
1569  { "disable_capture", query_disable_capture },
1570  { "disable_pattern", query_disable_pattern },
1571  { NULL, NULL }
1572};
1573
1574static int tslua_parse_query(lua_State *L)
1575{
1576  if (lua_gettop(L) < 2 || !lua_isstring(L, 1) || !lua_isstring(L, 2)) {
1577    return luaL_error(L, "string expected");
1578  }
1579
1580  TSLanguage *lang = lang_check(L, 1);
1581
1582  size_t len;
1583  const char *src = lua_tolstring(L, 2, &len);
1584
1585  tslua_query_parse_count++;
1586  uint32_t error_offset;
1587  TSQueryError error_type;
1588  TSQuery *query = ts_query_new(lang, src, (uint32_t)len, &error_offset, &error_type);
1589
1590  if (!query) {
1591    const CharBuf err = { (char[IOSIZE]){ 0 }, IOSIZE };
1592    query_err_string(src, (int)error_offset, error_type, err);
1593    return luaL_error(L, "%s", err.data);
1594  }
1595
1596  TSQuery **ud = lua_newuserdata(L, sizeof(TSQuery *));  // [udata]
1597  *ud = query;
1598  lua_getfield(L, LUA_REGISTRYINDEX, TS_META_QUERY);  // [udata, meta]
1599  lua_setmetatable(L, -2);  // [udata]
1600  return 1;
1601}
1602
1603static const char *query_err_to_string(TSQueryError error_type)
1604{
1605  switch (error_type) {
1606  case TSQueryErrorSyntax:
1607    return "Invalid syntax:\n";
1608  case TSQueryErrorNodeType:
1609    return "Invalid node type ";
1610  case TSQueryErrorField:
1611    return "Invalid field name ";
1612  case TSQueryErrorCapture:
1613    return "Invalid capture name ";
1614  case TSQueryErrorStructure:
1615    return "Impossible pattern:\n";
1616  default:
1617    return "error";
1618  }
1619}
1620
1621static void query_err_string(const char *src, int error_offset, TSQueryError error_type,
1622                             CharBuf err)
1623{
1624  int line_start = 0;
1625  int row = 0;
1626  const char *error_line = NULL;
1627  int error_line_len = 0;
1628
1629  const char *end_str;
1630  do {
1631    const char *src_tmp = src + line_start;
1632    end_str = strchr(src_tmp, '\n');
1633    int line_length = end_str != NULL ? (int)(end_str - src_tmp) : (int)strlen(src_tmp);
1634    int line_end = line_start + line_length;
1635    if (line_end > error_offset) {
1636      error_line = src_tmp;
1637      error_line_len = line_length;
1638      break;
1639    }
1640    line_start = line_end + 1;
1641    row++;
1642  } while (end_str != NULL);
1643
1644  int column = error_offset - line_start;
1645
1646  const char *type_msg = query_err_to_string(error_type);
1647  snprintf(err.data, err.size, "Query error at %d:%d. %s", row + 1, column + 1, type_msg);
1648  size_t offset = strlen(err.data);
1649  err.size -= offset;
1650  err.data += offset;
1651
1652  // Error types that report names
1653  if (error_type == TSQueryErrorNodeType
1654      || error_type == TSQueryErrorField
1655      || error_type == TSQueryErrorCapture) {
1656    const char *suffix = src + error_offset;
1657    bool is_anonymous = error_type == TSQueryErrorNodeType && suffix[-1] == '"';
1658    int suffix_len = 0;
1659    char c = suffix[suffix_len];
1660    if (is_anonymous) {
1661      int backslashes = 0;
1662      // Stop when we hit an unescaped double quote
1663      while (c != '"' || backslashes % 2 != 0) {
1664        if (c == '\\') {
1665          backslashes += 1;
1666        } else {
1667          backslashes = 0;
1668        }
1669        c = suffix[++suffix_len];
1670      }
1671    } else {
1672      // Stop when we hit the end of the identifier
1673      while (isalnum(c) || c == '_' || c == '-' || c == '.') {
1674        c = suffix[++suffix_len];
1675      }
1676    }
1677    snprintf(err.data, err.size, "\"%.*s\":\n", suffix_len, suffix);
1678    offset = strlen(err.data);
1679    err.size -= offset;
1680    err.data += offset;
1681  }
1682
1683  if (!error_line) {
1684    snprintf(err.data, err.size, "Unexpected EOF\n");
1685    return;
1686  }
1687
1688  snprintf(err.data, err.size, "%.*s\n%*s^\n", error_line_len, error_line, column, "");
1689}
1690
1691static TSQuery *query_check(lua_State *L, int index)
1692{
1693  TSQuery **ud = luaL_checkudata(L, index, TS_META_QUERY);
1694  luaL_argcheck(L, *ud, index, "TSQuery expected");
1695  return *ud;
1696}
1697
1698static int query_gc(lua_State *L)
1699{
1700  TSQuery *query = query_check(L, 1);
1701  ts_query_delete(query);
1702  return 0;
1703}
1704
1705static int query_tostring(lua_State *L)
1706{
1707  lua_pushstring(L, "<query>");
1708  return 1;
1709}
1710
1711static int query_inspect(lua_State *L)
1712{
1713  TSQuery *query = query_check(L, 1);
1714
1715  // TSQueryInfo
1716  lua_createtable(L, 0, 2);  // [retval]
1717
1718  uint32_t n_pat = ts_query_pattern_count(query);
1719  lua_createtable(L, (int)n_pat, 1);  // [retval, patterns]
1720  for (size_t i = 0; i < n_pat; i++) {
1721    uint32_t len;
1722    const TSQueryPredicateStep *step = ts_query_predicates_for_pattern(query, (uint32_t)i, &len);
1723    if (len == 0) {
1724      continue;
1725    }
1726    lua_createtable(L, (int)len/4, 1);  // [retval, patterns, pat]
1727    lua_createtable(L, 3, 0);  // [retval, patterns, pat, pred]
1728    int nextpred = 1;
1729    int nextitem = 1;
1730    for (size_t k = 0; k < len; k++) {
1731      if (step[k].type == TSQueryPredicateStepTypeDone) {
1732        lua_rawseti(L, -2, nextpred++);  // [retval, patterns, pat]
1733        lua_createtable(L, 3, 0);  // [retval, patterns, pat, pred]
1734        nextitem = 1;
1735        continue;
1736      }
1737
1738      if (step[k].type == TSQueryPredicateStepTypeString) {
1739        uint32_t strlen;
1740        const char *str = ts_query_string_value_for_id(query, step[k].value_id,
1741                                                       &strlen);
1742        lua_pushlstring(L, str, strlen);  // [retval, patterns, pat, pred, item]
1743      } else if (step[k].type == TSQueryPredicateStepTypeCapture) {
1744        lua_pushinteger(L, step[k].value_id + 1);  // [..., pat, pred, item]
1745      } else {
1746        abort();
1747      }
1748      lua_rawseti(L, -2, nextitem++);  // [retval, patterns, pat, pred]
1749    }
1750    // last predicate should have ended with TypeDone
1751    lua_pop(L, 1);  // [retval, patterns, pat]
1752    lua_rawseti(L, -2, (int)i + 1);  // [retval, patterns]
1753  }
1754  lua_setfield(L, -2, "patterns");  // [retval]
1755
1756  uint32_t n_captures = ts_query_capture_count(query);
1757  lua_createtable(L, (int)n_captures, 0);  // [retval, captures]
1758  for (size_t i = 0; i < n_captures; i++) {
1759    uint32_t strlen;
1760    const char *str = ts_query_capture_name_for_id(query, (uint32_t)i, &strlen);
1761    lua_pushlstring(L, str, strlen);  // [retval, captures, capture]
1762    lua_rawseti(L, -2, (int)i + 1);
1763  }
1764  lua_setfield(L, -2, "captures");  // [retval]
1765
1766  return 1;
1767}
1768
1769static int query_disable_capture(lua_State *L)
1770{
1771  TSQuery *query = query_check(L, 1);
1772  size_t name_len;
1773  const char *name = luaL_checklstring(L, 2, &name_len);
1774  ts_query_disable_capture(query, name, (uint32_t)name_len);
1775  return 0;
1776}
1777
1778static int query_disable_pattern(lua_State *L)
1779{
1780  TSQuery *query = query_check(L, 1);
1781  const uint32_t pattern_index = (uint32_t)luaL_checkinteger(L, 2);
1782  ts_query_disable_pattern(query, pattern_index - 1);
1783  return 0;
1784}
1785
1786// Library init
1787
1788static void build_meta(lua_State *L, const char *tname, const luaL_Reg *meta)
1789{
1790  if (luaL_newmetatable(L, tname)) {  // [meta]
1791    luaL_register(L, NULL, meta);
1792
1793    lua_pushvalue(L, -1);  // [meta, meta]
1794    lua_setfield(L, -2, "__index");  // [meta]
1795  }
1796  lua_pop(L, 1);  // [] (don't use it now)
1797}
1798
1799/// Init the tslua library.
1800///
1801/// All global state is stored in the registry of the lua_State.
1802static void tslua_init(lua_State *L)
1803{
1804  // type metatables
1805  build_meta(L, TS_META_PARSER, parser_meta);
1806  build_meta(L, TS_META_TREE, tree_meta);
1807  build_meta(L, TS_META_NODE, node_meta);
1808  build_meta(L, TS_META_QUERY, query_meta);
1809  build_meta(L, TS_META_QUERYCURSOR, querycursor_meta);
1810  build_meta(L, TS_META_QUERYMATCH, querymatch_meta);
1811
1812  ts_set_allocator(xmalloc, xcalloc, xrealloc, xfree);
1813}
1814
1815static int tslua_get_language_version(lua_State *L)
1816{
1817  lua_pushnumber(L, TREE_SITTER_LANGUAGE_VERSION);
1818  return 1;
1819}
1820
1821static int tslua_get_minimum_language_version(lua_State *L)
1822{
1823  lua_pushnumber(L, TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION);
1824  return 1;
1825}
1826
1827void nlua_treesitter_free(void)
1828{
1829#ifdef HAVE_WASMTIME
1830  if (wasmengine != NULL) {
1831    wasm_engine_delete(wasmengine);
1832  }
1833  if (ts_wasmstore != NULL) {
1834    ts_wasm_store_delete(ts_wasmstore);
1835  }
1836#endif
1837}
1838
1839void nlua_treesitter_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
1840{
1841  tslua_init(lstate);
1842
1843  lua_pushcfunction(lstate, tslua_push_parser);
1844  lua_setfield(lstate, -2, "_create_ts_parser");
1845
1846  lua_pushcfunction(lstate, tslua_push_querycursor);
1847  lua_setfield(lstate, -2, "_create_ts_querycursor");
1848
1849  lua_pushcfunction(lstate, tslua_add_language_from_object);
1850  lua_setfield(lstate, -2, "_ts_add_language_from_object");
1851
1852#ifdef HAVE_WASMTIME
1853  lua_pushcfunction(lstate, tslua_add_language_from_wasm);
1854  lua_setfield(lstate, -2, "_ts_add_language_from_wasm");
1855#endif
1856
1857  lua_pushcfunction(lstate, tslua_has_language);
1858  lua_setfield(lstate, -2, "_ts_has_language");
1859
1860  lua_pushcfunction(lstate, tslua_remove_lang);
1861  lua_setfield(lstate, -2, "_ts_remove_language");
1862
1863  lua_pushcfunction(lstate, tslua_inspect_lang);
1864  lua_setfield(lstate, -2, "_ts_inspect_language");
1865
1866  lua_pushcfunction(lstate, tslua_parse_query);
1867  lua_setfield(lstate, -2, "_ts_parse_query");
1868
1869  lua_pushcfunction(lstate, tslua_get_language_version);
1870  lua_setfield(lstate, -2, "_ts_get_language_version");
1871
1872  lua_pushcfunction(lstate, tslua_get_minimum_language_version);
1873  lua_setfield(lstate, -2, "_ts_get_minimum_language_version");
1874}