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