robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1#include <assert.h> 2#include <limits.h> 3#include <stdarg.h> 4#include <stdbool.h> 5#include <stddef.h> 6#include <stdint.h> 7#include <stdio.h> 8#include <stdlib.h> 9#include <string.h> 10 11#include "klib/kvec.h" 12#include "nvim/api/private/converter.h" 13#include "nvim/api/private/defs.h" 14#include "nvim/api/private/helpers.h" 15#include "nvim/api/private/validate.h" 16#include "nvim/ascii_defs.h" 17#include "nvim/buffer_defs.h" 18#include "nvim/eval/typval.h" 19#include "nvim/eval/vars.h" 20#include "nvim/ex_eval.h" 21#include "nvim/garray_defs.h" 22#include "nvim/globals.h" 23#include "nvim/highlight_group.h" 24#include "nvim/lua/executor.h" 25#include "nvim/map_defs.h" 26#include "nvim/mark.h" 27#include "nvim/memline.h" 28#include "nvim/memory.h" 29#include "nvim/memory_defs.h" 30#include "nvim/message.h" 31#include "nvim/msgpack_rpc/unpacker.h" 32#include "nvim/pos_defs.h" 33#include "nvim/runtime.h" 34#include "nvim/types_defs.h" 35 36#include "api/private/api_metadata.generated.h" 37#include "api/private/helpers.c.generated.h" // IWYU pragma: keep 38 39/// Start block that may cause Vimscript exceptions while evaluating another code 40/// 41/// Used just in case caller is supposed to be operating when other Vimscript code 42/// is being processed and that “other Vimscript code” must not be affected. 43/// 44/// @warning Avoid calling directly; use TRY_WRAP instead. 45/// 46/// @param[out] tstate Location where try state should be saved. 47void try_enter (TryState * const tstate ) 48{ 49// TODO(ZyX-I): Check whether try_enter()/try_leave() may use 50// enter_cleanup()/leave_cleanup(). Or 51// save_dbg_stuff()/restore_dbg_stuff(). 52* tstate = (TryState ) { 53 .current_exception = current_exception , 54 .msg_list = (const msglist_T * const * )msg_list , 55 .private_msg_list = NULL , 56 .got_int = got_int , 57 .did_throw = did_throw , 58 .need_rethrow = need_rethrow , 59 .did_emsg = did_emsg , 60 }; 61// `msg_list` controls the collection of abort-causing non-exception errors, 62// which would otherwise be ignored. This pattern is from do_cmdline(). 63msg_list = & tstate -> private_msg_list ; 64current_exception = NULL ; 65got_int = false; 66did_throw = false; 67need_rethrow = false; 68did_emsg = false; 69trylevel ++ ; 70} 71 72/// Ends a `try_enter` block; sets error message if any. 73/// 74/// @warning Avoid calling directly; use TRY_WRAP instead. 75/// 76/// @param[out] err Pointer to the stack-allocated error object 77void try_leave (const TryState * const tstate ,Error * const err ) 78FUNC_ATTR_NONNULL_ALL 79{ 80// Note: all globals manipulated here should be saved/restored in 81// try_enter/try_leave. 82assert (trylevel > 0 ); 83trylevel -- ; 84 85// Set by emsg(), affects aborting(). See also enter_cleanup(). 86did_emsg = false; 87force_abort = false; 88 89if (got_int ) { 90if (did_throw ) { 91// If we got an interrupt, discard the current exception 92discard_current_exception (); 93 } 94 95api_set_error (err ,kErrorTypeException ,"Keyboard interrupt" ); 96got_int = false; 97 }else if (msg_list != NULL && * msg_list != NULL ) { 98bool should_free ; 99char * msg = get_exception_string (* msg_list , 100ET_ERROR , 101NULL , 102& should_free ); 103api_set_error (err ,kErrorTypeException ,"%s" ,msg ); 104free_global_msglist (); 105 106if (should_free ) { 107xfree (msg ); 108 } 109 }else if (did_throw || need_rethrow ) { 110if (* current_exception -> throw_name != NUL ) { 111if (current_exception -> throw_lnum != 0 ) { 112api_set_error (err ,kErrorTypeException ,"%s, line %" PRIdLINENR ": %s" , 113current_exception -> throw_name ,current_exception -> throw_lnum , 114current_exception -> value ); 115 }else { 116api_set_error (err ,kErrorTypeException ,"%s: %s" , 117current_exception -> throw_name ,current_exception -> value ); 118 } 119 }else { 120api_set_error (err ,kErrorTypeException ,"%s" ,current_exception -> value ); 121 } 122discard_current_exception (); 123 } 124 125// Restore the exception context. 126msg_list = (msglist_T ** )tstate -> msg_list ; 127current_exception = tstate -> current_exception ; 128got_int = tstate -> got_int ; 129did_throw = tstate -> did_throw ; 130need_rethrow = tstate -> need_rethrow ; 131did_emsg = tstate -> did_emsg ; 132} 133 134/// Recursively expands a vimscript value in a dict 135/// 136/// @param dict The vimscript dict 137/// @param key The key 138/// @param[out] err Details of an error that may have occurred 139Object dict_get_value (dict_T * dict ,String key ,Arena * arena ,Error * err ) 140{ 141dictitem_T * const di = tv_dict_find (dict ,key .data , (ptrdiff_t )key .size ); 142 143VALIDATE (di != NULL ,"Key not found: %s" ,key .data , { 144return (Object )OBJECT_INIT ; 145 }); 146 147return vim_to_object (& di -> di_tv ,arena , true); 148} 149 150dictitem_T * dict_check_writable (dict_T * dict ,String key ,bool del ,Error * err ) 151{ 152dictitem_T * di = tv_dict_find (dict ,key .data , (ptrdiff_t )key .size ); 153 154if (di != NULL ) { 155if (di -> di_flags & DI_FLAGS_RO ) { 156api_set_error (err ,kErrorTypeException ,"Key is read-only: %s" ,key .data ); 157 }else if (di -> di_flags & DI_FLAGS_LOCK ) { 158api_set_error (err ,kErrorTypeException ,"Key is locked: %s" ,key .data ); 159 }else if (del && (di -> di_flags & DI_FLAGS_FIX )) { 160api_set_error (err ,kErrorTypeException ,"Key is fixed: %s" ,key .data ); 161 } 162 }else if (dict -> dv_lock ) { 163api_set_error (err ,kErrorTypeException ,"Dict is locked" ); 164 }else if (key .size == 0 ) { 165api_set_error (err ,kErrorTypeValidation ,"Key name is empty" ); 166 }else if (key .size > INT_MAX ) { 167api_set_error (err ,kErrorTypeValidation ,"Key name is too long" ); 168 } 169 170return di ; 171} 172 173/// Set a value in a scope dict. Objects are recursively expanded into their 174/// vimscript equivalents. 175/// 176/// @param dict The vimscript dict 177/// @param key The key 178/// @param value The new value 179/// @param del Delete key in place of setting it. Argument `value` is ignored in 180/// this case. 181/// @param retval If true the old value will be converted and returned. 182/// @param[out] err Details of an error that may have occurred 183/// @return The old value if `retval` is true and the key was present, else NIL 184Object dict_set_var (dict_T * dict ,String key ,Object value ,bool del ,bool retval ,Arena * arena , 185Error * err ) 186{ 187Object rv = OBJECT_INIT ; 188dictitem_T * di = dict_check_writable (dict ,key ,del ,err ); 189 190if (ERROR_SET (err )) { 191return rv ; 192 } 193 194bool watched = tv_dict_is_watched (dict ); 195 196if (del ) { 197// Delete the key 198if (di == NULL ) { 199// Doesn't exist, fail 200api_set_error (err ,kErrorTypeValidation ,"Key not found: %s" ,key .data ); 201 }else { 202// Notify watchers 203if (watched ) { 204tv_dict_watcher_notify (dict ,key .data ,NULL ,& di -> di_tv ); 205 } 206// Return the old value 207if (retval ) { 208rv = vim_to_object (& di -> di_tv ,arena , false); 209 } 210// Delete the entry 211tv_dict_item_remove (dict ,di ); 212 } 213 }else { 214// Update the key 215typval_T tv ; 216 217// Convert the object to a vimscript type in the temporary variable 218object_to_vim (value ,& tv ,err ); 219 220typval_T oldtv = TV_INITIAL_VALUE ; 221 222if (di == NULL ) { 223// Need to create an entry 224di = tv_dict_item_alloc_len (key .data ,key .size ); 225tv_dict_add (dict ,di ); 226 }else { 227// Return the old value 228if (retval ) { 229rv = vim_to_object (& di -> di_tv ,arena , false); 230 } 231bool type_error = false; 232if (dict == get_vimvar_dict () 233&& !before_set_vvar (key .data ,di ,& tv , true,watched ,& type_error )) { 234tv_clear (& tv ); 235if (type_error ) { 236api_set_error (err ,kErrorTypeValidation , 237"Setting v:%s to value with wrong type" ,key .data ); 238 } 239return rv ; 240 } 241if (watched ) { 242tv_copy (& di -> di_tv ,& oldtv ); 243 } 244tv_clear (& di -> di_tv ); 245 } 246 247// Update the value 248tv_copy (& tv ,& di -> di_tv ); 249 250// Notify watchers 251if (watched ) { 252tv_dict_watcher_notify (dict ,key .data ,& tv ,& oldtv ); 253tv_clear (& oldtv ); 254 } 255 256// Clear the temporary variable 257tv_clear (& tv ); 258 } 259 260return rv ; 261} 262 263buf_T * find_buffer_by_handle (Buffer buffer ,Error * err ) 264{ 265if (buffer == 0 ) { 266return curbuf ; 267 } 268 269buf_T * rv = handle_get_buffer (buffer ); 270 271VALIDATE_INT (rv ,"buffer id" ,buffer , { 272return NULL ; 273 }); 274 275return rv ; 276} 277 278win_T * find_window_by_handle (Window window ,Error * err ) 279{ 280if (window == 0 ) { 281return curwin ; 282 } 283 284win_T * rv = handle_get_window (window ); 285 286VALIDATE_INT (rv ,"window id" ,window , { 287return NULL ; 288 }); 289 290return rv ; 291} 292 293tabpage_T * find_tab_by_handle (Tabpage tabpage ,Error * err ) 294{ 295if (tabpage == 0 ) { 296return curtab ; 297 } 298 299tabpage_T * rv = handle_get_tabpage (tabpage ); 300 301VALIDATE_INT (rv ,"tabpage id" ,tabpage , { 302return NULL ; 303 }); 304 305return rv ; 306} 307 308/// Allocates a String consisting of a single char. Does not support multibyte 309/// characters. The resulting string is also NUL-terminated, to facilitate 310/// interoperating with code using C strings. 311/// 312/// @param char the char to convert 313/// @return the resulting String, if the input char was NUL, an 314/// empty String is returned 315String cchar_to_string (char c ) 316{ 317char buf []= {c ,NUL }; 318return (String ){ 319 .data = xmemdupz (buf ,1 ), 320 .size = (c != NUL ) ?1 :0 321 }; 322} 323 324/// Copies a C string into a String (binary safe string, characters + length). 325/// The resulting string is also NUL-terminated, to facilitate interoperating 326/// with code using C strings. 327/// 328/// @param str the C string to copy 329/// @return the resulting String, if the input string was NULL, an 330/// empty String is returned 331String cstr_to_string (const char * str ) 332{ 333if (str == NULL ) { 334return (String )STRING_INIT ; 335 } 336 337size_t len = strlen (str ); 338return (String ){ 339 .data = xmemdupz (str ,len ), 340 .size = len , 341 }; 342} 343 344/// Copies a String to an allocated, NUL-terminated C string. 345/// 346/// @param str the String to copy 347/// @return the resulting C string 348char * string_to_cstr (String str ) 349FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT 350{ 351return xstrndup (str .data ,str .size ); 352} 353 354/// Copies buffer to an allocated String. 355/// The resulting string is also NUL-terminated, to facilitate interoperating 356/// with code using C strings. 357/// 358/// @param buf the buffer to copy 359/// @param size length of the buffer 360/// @return the resulting String, if the input string was NULL, an 361/// empty String is returned 362String cbuf_to_string (const char * buf ,size_t size ) 363FUNC_ATTR_NONNULL_ALL 364{ 365return (String ){ 366 .data = xmemdupz (buf ,size ), 367 .size = size 368 }; 369} 370 371String cstrn_to_string (const char * str ,size_t maxsize ) 372FUNC_ATTR_NONNULL_ALL 373{ 374return cbuf_to_string (str ,strnlen (str ,maxsize )); 375} 376 377String cstrn_as_string (char * str ,size_t maxsize ) 378FUNC_ATTR_NONNULL_ALL 379{ 380return cbuf_as_string (str ,strnlen (str ,maxsize )); 381} 382 383/// Creates a String using the given C string. Unlike 384/// cstr_to_string this function DOES NOT copy the C string. 385/// 386/// @param str the C string to use 387/// @return The resulting String, or an empty String if 388/// str was NULL 389String cstr_as_string (const char * str )FUNC_ATTR_PURE 390{ 391if (str == NULL ) { 392return (String )STRING_INIT ; 393 } 394return (String ){ .data = (char * )str , .size = strlen (str ) }; 395} 396 397/// Return the owned memory of a ga as a String 398/// 399/// Reinitializes the ga to a valid empty state. 400String ga_take_string (garray_T * ga ) 401{ 402String str = { .data = (char * )ga -> ga_data , .size = (size_t )ga -> ga_len }; 403ga -> ga_data = NULL ; 404ga -> ga_len = 0 ; 405ga -> ga_maxlen = 0 ; 406return str ; 407} 408 409/// Creates "readfile()-style" ArrayOf(String) from a binary string. 410/// 411/// - Lines break at \n (NL/LF/line-feed). 412/// - NUL bytes are replaced with NL. 413/// - If the last byte is a linebreak an extra empty list item is added. 414/// 415/// @param input Binary string 416/// @param crlf Also break lines at CR and CRLF. 417/// @return [allocated] String array 418Array string_to_array (const String input ,bool crlf ,Arena * arena ) 419{ 420ArrayBuilder ret = ARRAY_DICT_INIT ; 421kvi_init (ret ); 422for (size_t i = 0 ;i < input .size ;i ++ ) { 423const char * start = input .data + i ; 424const char * end = start ; 425size_t line_len = 0 ; 426for (;line_len < input .size - i ;line_len ++ ) { 427end = start + line_len ; 428if (* end == NL || (crlf && * end == CAR )) { 429break ; 430 } 431 } 432i += line_len ; 433if (crlf && * end == CAR && i + 1 < input .size && * (end + 1 )== NL ) { 434i += 1 ;// Advance past CRLF. 435 } 436String s = CBUF_TO_ARENA_STR (arena ,start ,line_len ); 437memchrsub (s .data ,NUL ,NL ,line_len ); 438kvi_push (ret ,STRING_OBJ (s )); 439// If line ends at end-of-buffer, add empty final item. 440// This is "readfile()-style", see also ":help channel-lines". 441if (i + 1 == input .size && (* end == NL || (crlf && * end == CAR ))) { 442kvi_push (ret ,STRING_OBJ (CBUF_TO_ARENA_STR (arena ,"" ,0 ))); 443 } 444 } 445 446return arena_take_arraybuilder (arena ,& ret ); 447} 448 449/// Normalizes 0-based indexes to buffer line numbers. 450int64_t normalize_index (buf_T * buf ,int64_t index ,bool end_exclusive ,bool * oob ) 451{ 452assert (buf -> b_ml .ml_line_count > 0 ); 453int64_t max_index = buf -> b_ml .ml_line_count + (int )end_exclusive - 1 ; 454// A negative index counts from the bottom. 455index = index < 0 ?max_index + index + 1 :index ; 456 457// Check for oob and clamp. 458if (index > max_index ) { 459* oob = true; 460index = max_index ; 461 }else if (index < 0 ) { 462* oob = true; 463index = 0 ; 464 } 465// Convert the index to a 1-based line number. 466index ++ ; 467return index ; 468} 469 470/// Returns a substring of a buffer line 471/// 472/// @param buf Buffer id 473/// @param lnum Line number (1-based) 474/// @param start_col Starting byte offset into line (0-based) 475/// @param end_col Ending byte offset into line (0-based, exclusive) 476/// @param err Error object 477/// @return The text between start_col and end_col on line lnum of buffer buf 478String buf_get_text (buf_T * buf ,int64_t lnum ,int64_t start_col ,int64_t end_col ,Error * err ) 479{ 480String rv = STRING_INIT ; 481 482VALIDATE_RANGE ((lnum < MAXLNUM ),"line index" , { 483return rv ; 484 }); 485 486char * bufstr = ml_get_buf (buf , (linenr_T )lnum ); 487colnr_T line_length = ml_get_buf_len (buf , (linenr_T )lnum ); 488 489start_col = start_col < 0 ?line_length + start_col + 1 :start_col ; 490end_col = end_col < 0 ?line_length + end_col + 1 :end_col ; 491 492start_col = MIN (MAX (0 ,start_col ),line_length ); 493end_col = MIN (MAX (0 ,end_col ),line_length ); 494 495if (start_col > end_col ) { 496api_set_error (err ,kErrorTypeValidation ,"start_col must be less than or equal to end_col" ); 497return rv ; 498 } 499 500return cbuf_as_string (bufstr + start_col , (size_t )(end_col - start_col )); 501} 502 503void api_free_string (String value ) 504{ 505xfree (value .data ); 506} 507 508Array arena_array (Arena * arena ,size_t max_size ) 509{ 510Array arr = ARRAY_DICT_INIT ; 511kv_fixsize_arena (arena ,arr ,max_size ); 512return arr ; 513} 514 515Dict arena_dict (Arena * arena ,size_t max_size ) 516{ 517Dict dict = ARRAY_DICT_INIT ; 518kv_fixsize_arena (arena ,dict ,max_size ); 519return dict ; 520} 521 522String arena_string (Arena * arena ,String str ) 523{ 524if (str .size ) { 525return cbuf_as_string (arena_memdupz (arena ,str .data ,str .size ),str .size ); 526 }else { 527return (String ){ .data = arena ?"" :xstrdup ("" ), .size = 0 }; 528 } 529} 530 531Array arena_take_arraybuilder (Arena * arena ,ArrayBuilder * arr ) 532{ 533Array ret = arena_array (arena ,kv_size (* arr )); 534ret .size = kv_size (* arr ); 535memcpy (ret .items ,arr -> items ,sizeof (ret .items [0 ])* ret .size ); 536kvi_destroy (* arr ); 537return ret ; 538} 539 540void api_free_object (Object value ) 541{ 542switch (value .type ) { 543case kObjectTypeUnset : 544case kObjectTypeNil : 545case kObjectTypeBoolean : 546case kObjectTypeInteger : 547case kObjectTypeFloat : 548case kObjectTypeBuffer : 549case kObjectTypeWindow : 550case kObjectTypeTabpage : 551break ; 552 553case kObjectTypeString : 554api_free_string (value .data .string ); 555break ; 556 557case kObjectTypeArray : 558api_free_array (value .data .array ); 559break ; 560 561case kObjectTypeDict : 562api_free_dict (value .data .dict ); 563break ; 564 565case kObjectTypeLuaRef : 566api_free_luaref (value .data .luaref ); 567break ; 568 } 569} 570 571void api_free_array (Array value ) 572{ 573for (size_t i = 0 ;i < value .size ;i ++ ) { 574api_free_object (value .items [i ]); 575 } 576 577xfree (value .items ); 578} 579 580void api_free_dict (Dict value ) 581{ 582for (size_t i = 0 ;i < value .size ;i ++ ) { 583api_free_string (value .items [i ].key ); 584api_free_object (value .items [i ].value ); 585 } 586 587xfree (value .items ); 588} 589 590void api_clear_error (Error * value ) 591FUNC_ATTR_NONNULL_ALL 592{ 593if (!ERROR_SET (value )) { 594return ; 595 } 596xfree (value -> msg ); 597value -> msg = NULL ; 598value -> type = kErrorTypeNone ; 599} 600 601// initialized once, never freed 602static ArenaMem mem_for_metadata = NULL ; 603 604/// @returns a shared value. caller must not modify it! 605Object api_metadata (void ) 606{ 607static Object metadata = OBJECT_INIT ; 608 609if (metadata .type == kObjectTypeNil ) { 610Arena arena = ARENA_EMPTY ; 611Error err = ERROR_INIT ; 612metadata = unpack ((char * )packed_api_metadata ,sizeof (packed_api_metadata ),& arena ,& err ); 613if (ERROR_SET (& err )|| metadata .type != kObjectTypeDict ) { 614abort (); 615 } 616mem_for_metadata = arena_finish (& arena ); 617 } 618 619return metadata ; 620} 621 622String api_metadata_raw (void ) 623{ 624return cbuf_as_string ((char * )packed_api_metadata ,sizeof (packed_api_metadata )); 625} 626 627// all the copy_[object] functions allow arena=NULL, 628// then global allocations are used, and the resulting object 629// should be freed with an api_free_[object] function 630 631String copy_string (String str ,Arena * arena ) 632{ 633if (str .data != NULL ) { 634return (String ){ .data = arena_memdupz (arena ,str .data ,str .size ), .size = str .size }; 635 }else { 636return (String )STRING_INIT ; 637 } 638} 639 640Array copy_array (Array array ,Arena * arena ) 641{ 642Array rv = arena_array (arena ,array .size ); 643for (size_t i = 0 ;i < array .size ;i ++ ) { 644ADD (rv ,copy_object (array .items [i ],arena )); 645 } 646return rv ; 647} 648 649Dict copy_dict (Dict dict ,Arena * arena ) 650{ 651Dict rv = arena_dict (arena ,dict .size ); 652for (size_t i = 0 ;i < dict .size ;i ++ ) { 653KeyValuePair item = dict .items [i ]; 654PUT_C (rv ,copy_string (item .key ,arena ).data ,copy_object (item .value ,arena )); 655 } 656return rv ; 657} 658 659/// Creates a deep clone of an object 660Object copy_object (Object obj ,Arena * arena ) 661{ 662switch (obj .type ) { 663case kObjectTypeUnset : 664case kObjectTypeBuffer : 665case kObjectTypeTabpage : 666case kObjectTypeWindow : 667case kObjectTypeNil : 668case kObjectTypeBoolean : 669case kObjectTypeInteger : 670case kObjectTypeFloat : 671return obj ; 672 673case kObjectTypeString : 674return STRING_OBJ (copy_string (obj .data .string ,arena )); 675 676case kObjectTypeArray : 677return ARRAY_OBJ (copy_array (obj .data .array ,arena )); 678 679case kObjectTypeDict : 680return DICT_OBJ (copy_dict (obj .data .dict ,arena )); 681 682case kObjectTypeLuaRef : 683return LUAREF_OBJ (api_new_luaref (obj .data .luaref )); 684 } 685UNREACHABLE ; 686} 687 688void api_set_error (Error * err ,ErrorType errType ,const char * format , ...) 689FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PRINTF (3 ,4 ) 690{ 691assert (kErrorTypeNone != errType ); 692va_list args1 ; 693va_list args2 ; 694va_start (args1 ,format ); 695va_copy (args2 ,args1 ); 696int len = vsnprintf (NULL ,0 ,format ,args1 ); 697va_end (args1 ); 698assert (len >=0 ); 699// Limit error message to 1 MB. 700size_t bufsize = MIN ((size_t )len + 1 ,1024 * 1024 ); 701err -> msg = xmalloc (bufsize ); 702vsnprintf (err -> msg ,bufsize ,format ,args2 ); 703va_end (args2 ); 704 705err -> type = errType ; 706} 707 708/// Force obj to bool. 709/// If it fails, returns false and sets err 710/// @param obj The object to coerce to a boolean 711/// @param what The name of the object, used for error message 712/// @param nil_value What to return if the type is nil. 713/// @param err Set if there was an error in converting to a bool 714bool api_object_to_bool (Object obj ,const char * what ,bool nil_value ,Error * err ) 715{ 716if (obj .type == kObjectTypeBoolean ) { 717return obj .data .boolean ; 718 }else if (obj .type == kObjectTypeInteger ) { 719return obj .data .integer ;// C semantics: non-zero int is true 720 }else if (obj .type == kObjectTypeNil ) { 721return nil_value ;// caller decides what NIL (missing retval in Lua) means 722 }else { 723VALIDATE_EXP (false,what ,"boolean" ,NULL , {}); 724return false; 725 } 726} 727 728int object_to_hl_id (Object obj ,const char * what ,Error * err ) 729{ 730if (obj .type == kObjectTypeString ) { 731String str = obj .data .string ; 732return str .size ?syn_check_group (str .data ,str .size ) :0 ; 733 }else if (obj .type == kObjectTypeInteger ) { 734int id = (int )obj .data .integer ; 735return (1 <=id && id <=highlight_num_groups ()) ?id :0 ; 736 }else { 737VALIDATE_S (false,"hl_group" ,what , {}); 738return 0 ; 739 } 740} 741 742char * api_typename (ObjectType t ) 743{ 744switch (t ) { 745case kObjectTypeUnset : 746return "unset" ; 747case kObjectTypeNil : 748return "nil" ; 749case kObjectTypeBoolean : 750return "Boolean" ; 751case kObjectTypeInteger : 752return "Integer" ; 753case kObjectTypeFloat : 754return "Float" ; 755case kObjectTypeString : 756return "String" ; 757case kObjectTypeArray : 758return "Array" ; 759case kObjectTypeDict : 760return "Dict" ; 761case kObjectTypeLuaRef : 762return "Function" ; 763case kObjectTypeBuffer : 764return "Buffer" ; 765case kObjectTypeWindow : 766return "Window" ; 767case kObjectTypeTabpage : 768return "Tabpage" ; 769 } 770UNREACHABLE ; 771} 772 773HlMessage parse_hl_msg (ArrayOf (Tuple (String ,* HLGroupID ))chunks ,bool is_err ,Error * err ) 774{ 775HlMessage hl_msg = KV_INITIAL_VALUE ; 776for (size_t i = 0 ;i < chunks .size ;i ++ ) { 777VALIDATE_T ("chunk" ,kObjectTypeArray ,chunks .items [i ].type , { 778 gotofree_exit ; 779 }); 780Tuple (String ,* HLGroupID )chunk = chunks .items [i ].data .array ; 781VALIDATE ((chunk .size > 0 && chunk .size <=2 && chunk .items [0 ].type == kObjectTypeString ), 782"%s" ,"Invalid chunk: expected Array with 1 or 2 Strings" , { 783 gotofree_exit ; 784 }); 785 786String str = copy_string (chunk .items [0 ].data .string ,NULL ); 787 788int hl_id = 789chunk .size == 2 ?object_to_hl_id (chunk .items [1 ],"text highlight" ,err ) 790 :is_err ?HLF_E 791 :0 ; 792kv_push (hl_msg , ((HlMessageChunk ){ .text = str , .hl_id = hl_id })); 793 } 794 795return hl_msg ; 796 797free_exit : 798hl_msg_free (hl_msg ); 799return (HlMessage )KV_INITIAL_VALUE ; 800} 801 802// see also nlua_pop_keydict for the lua specific implementation 803bool api_dict_to_keydict (void * retval ,FieldHashfn hashy ,Dict dict ,Error * err ) 804{ 805for (size_t i = 0 ;i < dict .size ;i ++ ) { 806String k = dict .items [i ].key ; 807const KeySetLink * field = hashy (k .data ,k .size ); 808if (!field ) { 809api_set_error (err ,kErrorTypeValidation ,"Invalid key: '%.*s'" , (int )k .size ,k .data ); 810return false; 811 } 812 813if (field -> opt_index >=0 ) { 814OptKeySet * ks = (OptKeySet * )retval ; 815ks -> is_set_ |= (1ULL <<field -> opt_index ); 816 } 817 818char * mem = ((char * )retval + field -> ptr_off ); 819Object * value = & dict .items [i ].value ; 820 821if (field -> type == kObjectTypeNil ) { 822* (Object * )mem = * value ; 823 }else if (field -> type == kObjectTypeInteger ) { 824if (field -> is_hlgroup ) { 825int hl_id = 0 ; 826if (value -> type != kObjectTypeNil ) { 827hl_id = object_to_hl_id (* value ,k .data ,err ); 828if (ERROR_SET (err )) { 829return false; 830 } 831 } 832* (Integer * )mem = hl_id ; 833 }else { 834VALIDATE_T (field -> str ,kObjectTypeInteger ,value -> type , { 835return false; 836 }); 837 838* (Integer * )mem = value -> data .integer ; 839 } 840 }else if (field -> type == kObjectTypeFloat ) { 841Float * val = (Float * )mem ; 842if (value -> type == kObjectTypeInteger ) { 843* val = (Float )value -> data .integer ; 844 }else { 845VALIDATE_T (field -> str ,kObjectTypeFloat ,value -> type , { 846return false; 847 }); 848* val = value -> data .floating ; 849 } 850 }else if (field -> type == kObjectTypeBoolean ) { 851// caller should check HAS_KEY to override the nil behavior, or GET_BOOL_OR_TRUE 852// to directly use true when nil 853* (Boolean * )mem = api_object_to_bool (* value ,field -> str , false,err ); 854if (ERROR_SET (err )) { 855return false; 856 } 857 }else if (field -> type == kObjectTypeString ) { 858VALIDATE_T (field -> str ,kObjectTypeString ,value -> type , { 859return false; 860 }); 861* (String * )mem = value -> data .string ; 862 }else if (field -> type == kObjectTypeArray ) { 863VALIDATE_T (field -> str ,kObjectTypeArray ,value -> type , { 864return false; 865 }); 866* (Array * )mem = value -> data .array ; 867 }else if (field -> type == kObjectTypeDict ) { 868Dict * val = (Dict * )mem ; 869// allow empty array as empty dict for lua (directly or via lua-client RPC) 870if (value -> type == kObjectTypeArray && value -> data .array .size == 0 ) { 871* val = (Dict )ARRAY_DICT_INIT ; 872 }else if (value -> type == kObjectTypeDict ) { 873* val = value -> data .dict ; 874 }else { 875api_err_exp (err ,field -> str ,api_typename ((ObjectType )field -> type ), 876api_typename (value -> type )); 877return false; 878 } 879 }else if (field -> type == kObjectTypeBuffer || field -> type == kObjectTypeWindow 880|| field -> type == kObjectTypeTabpage ) { 881if (value -> type == kObjectTypeInteger || value -> type == (ObjectType )field -> type ) { 882* (handle_T * )mem = (handle_T )value -> data .integer ; 883 }else { 884api_err_exp (err ,field -> str ,api_typename ((ObjectType )field -> type ), 885api_typename (value -> type )); 886return false; 887 } 888 }else if (field -> type == kObjectTypeLuaRef ) { 889api_set_error (err ,kErrorTypeValidation ,"Invalid key: '%.*s' is only allowed from Lua" , 890 (int )k .size ,k .data ); 891return false; 892 }else { 893abort (); 894 } 895 } 896 897return true; 898} 899 900Dict api_keydict_to_dict (void * value ,KeySetLink * table ,size_t max_size ,Arena * arena ) 901{ 902Dict rv = arena_dict (arena ,max_size ); 903for (size_t i = 0 ;table [i ].str ;i ++ ) { 904KeySetLink * field = & table [i ]; 905bool is_set = true; 906if (field -> opt_index >=0 ) { 907OptKeySet * ks = (OptKeySet * )value ; 908is_set = ks -> is_set_ & (1ULL <<field -> opt_index ); 909 } 910 911if (!is_set ) { 912continue ; 913 } 914 915char * mem = ((char * )value + field -> ptr_off ); 916Object val = NIL ; 917 918if (field -> type == kObjectTypeNil ) { 919val = * (Object * )mem ; 920 }else if (field -> type == kObjectTypeInteger ) { 921val = INTEGER_OBJ (* (Integer * )mem ); 922 }else if (field -> type == kObjectTypeFloat ) { 923val = FLOAT_OBJ (* (Float * )mem ); 924 }else if (field -> type == kObjectTypeBoolean ) { 925val = BOOLEAN_OBJ (* (Boolean * )mem ); 926 }else if (field -> type == kObjectTypeString ) { 927val = STRING_OBJ (* (String * )mem ); 928 }else if (field -> type == kObjectTypeArray ) { 929val = ARRAY_OBJ (* (Array * )mem ); 930 }else if (field -> type == kObjectTypeDict ) { 931val = DICT_OBJ (* (Dict * )mem ); 932 }else if (field -> type == kObjectTypeBuffer || field -> type == kObjectTypeWindow 933|| field -> type == kObjectTypeTabpage ) { 934val .data .integer = * (handle_T * )mem ; 935val .type = (ObjectType )field -> type ; 936 }else if (field -> type == kObjectTypeLuaRef ) { 937// do nothing 938 }else { 939abort (); 940 } 941 942PUT_C (rv ,field -> str ,val ); 943 } 944 945return rv ; 946} 947 948void api_luarefs_free_object (Object value ) 949{ 950// TODO(bfredl): this is more complicated than it needs to be. 951// we should be able to lock down more specifically where luarefs can be 952switch (value .type ) { 953case kObjectTypeLuaRef : 954api_free_luaref (value .data .luaref ); 955break ; 956 957case kObjectTypeArray : 958api_luarefs_free_array (value .data .array ); 959break ; 960 961case kObjectTypeDict : 962api_luarefs_free_dict (value .data .dict ); 963break ; 964 965default : 966break ; 967 } 968} 969 970void api_luarefs_free_keydict (void * dict ,KeySetLink * table ) 971{ 972for (size_t i = 0 ;table [i ].str ;i ++ ) { 973char * mem = ((char * )dict + table [i ].ptr_off ); 974if (table [i ].type == kObjectTypeNil ) { 975api_luarefs_free_object (* (Object * )mem ); 976 }else if (table [i ].type == kObjectTypeLuaRef ) { 977api_free_luaref (* (LuaRef * )mem ); 978 }else if (table [i ].type == kObjectTypeDict ) { 979api_luarefs_free_dict (* (Dict * )mem ); 980 } 981 } 982} 983 984void api_luarefs_free_array (Array value ) 985{ 986for (size_t i = 0 ;i < value .size ;i ++ ) { 987api_luarefs_free_object (value .items [i ]); 988 } 989} 990 991void api_luarefs_free_dict (Dict value ) 992{ 993for (size_t i = 0 ;i < value .size ;i ++ ) { 994api_luarefs_free_object (value .items [i ].value ); 995 } 996} 997 998/// Set a named mark 999/// buffer and mark name must be validated already 1000/// @param buffer Buffer to set the mark on 1001/// @param name Mark name 1002/// @param line Line number 1003/// @param col Column/row number 1004/// @return true if the mark was set, else false 1005bool set_mark (buf_T * buf ,String name ,Integer line ,Integer col ,Error * err ) 1006{ 1007buf = buf == NULL ?curbuf :buf ; 1008// If line == 0 the marks is being deleted 1009bool res = false; 1010bool deleting = false; 1011if (line == 0 ) { 1012col = 0 ; 1013deleting = true; 1014 }else { 1015VALIDATE_RANGE (!(col > MAXCOL ),"column" , { 1016return res ; 1017 }); 1018VALIDATE_RANGE (!(line < 1 || line > buf -> b_ml .ml_line_count ),"line" , { 1019return res ; 1020 }); 1021 } 1022assert (INT32_MIN <=line && line <=INT32_MAX ); 1023pos_T pos = { (linenr_T )line , (int )col ,0 }; 1024res = setmark_pos (* name .data ,& pos ,buf -> handle ,NULL ); 1025if (!res ) { 1026if (deleting ) { 1027api_set_error (err ,kErrorTypeException , 1028"Failed to delete named mark: %c" ,* name .data ); 1029 }else { 1030api_set_error (err ,kErrorTypeException , 1031"Failed to set named mark: %c" ,* name .data ); 1032 } 1033 } 1034return res ; 1035} 1036 1037/// Get default statusline highlight for window 1038const char * get_default_stl_hl (win_T * wp ,bool use_winbar ,int stc_hl_id ) 1039{ 1040if (wp == NULL ) { 1041return "TabLineFill" ; 1042 }else if (use_winbar ) { 1043return (wp == curwin ) ?"WinBar" :"WinBarNC" ; 1044 }else if (stc_hl_id > 0 ) { 1045return syn_id2name (stc_hl_id ); 1046 }else { 1047return (wp == curwin ) ?"StatusLine" :"StatusLineNC" ; 1048 } 1049} 1050 1051/// Sets sctx for API calls. 1052/// 1053/// @param channel_id api client id to determine if it's a internal or RPC call. 1054/// 1055/// @return previous value of current_sctx. To be used later for restoring sctx. 1056sctx_T api_set_sctx (uint64_t channel_id ) 1057{ 1058sctx_T old_current_sctx = current_sctx ; 1059// The script context is already properly set when calling an API from Vimscript. 1060if (channel_id != VIML_INTERNAL_CALL ) { 1061current_sctx .sc_lnum = 0 ; 1062if (channel_id == LUA_INTERNAL_CALL ) { 1063// When the current script is a Lua script, don't override sc_sid. 1064if (!script_is_lua (current_sctx .sc_sid )) { 1065current_sctx .sc_sid = SID_LUA ; 1066 } 1067 }else { 1068current_sctx .sc_sid = SID_API_CLIENT ; 1069current_sctx .sc_chan = channel_id ; 1070 } 1071 } 1072return old_current_sctx ; 1073}