robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1#include <assert.h> 2#include <lauxlib.h> 3#include <stdbool.h> 4#include <stddef.h> 5#include <stdio.h> 6#include <stdlib.h> 7#include <string.h> 8#include <uv.h> 9 10#include "nvim/ascii_defs.h" 11#include "nvim/assert_defs.h" 12#include "nvim/buffer_defs.h" 13#include "nvim/charset.h" 14#include "nvim/errors.h" 15#include "nvim/eval.h" 16#include "nvim/eval/encode.h" 17#include "nvim/eval/executor.h" 18#include "nvim/eval/gc.h" 19#include "nvim/eval/typval.h" 20#include "nvim/eval/typval_defs.h" 21#include "nvim/eval/typval_encode.h" 22#include "nvim/eval/userfunc.h" 23#include "nvim/eval/vars.h" 24#include "nvim/garray.h" 25#include "nvim/garray_defs.h" 26#include "nvim/gettext_defs.h" 27#include "nvim/globals.h" 28#include "nvim/hashtab.h" 29#include "nvim/hashtab_defs.h" 30#include "nvim/lib/queue_defs.h" 31#include "nvim/lua/executor.h" 32#include "nvim/macros_defs.h" 33#include "nvim/mbyte.h" 34#include "nvim/mbyte_defs.h" 35#include "nvim/memory.h" 36#include "nvim/memory_defs.h" 37#include "nvim/message.h" 38#include "nvim/os/input.h" 39#include "nvim/pos_defs.h" 40#include "nvim/strings.h" 41#include "nvim/types_defs.h" 42#include "nvim/vim_defs.h" 43 44/// struct storing information about current sort 45typedef struct { 46int item_compare_ic ; 47bool item_compare_lc ; 48bool item_compare_numeric ; 49bool item_compare_numbers ; 50bool item_compare_float ; 51const char * item_compare_func ; 52partial_T * item_compare_partial ; 53dict_T * item_compare_selfdict ; 54bool item_compare_func_err ; 55bool item_compare_keys_ready ;///< ptrs[].key is precomputed 56}sortinfo_T ; 57 58/// Structure representing one list item, used for sort array. 59typedef struct { 60listitem_T * item ;///< Sorted list item. 61int idx ;///< Sorted list item index. 62/// Sort key precomputed once per item for the numeric compare modes. 63/// Only valid when sortinfo->item_compare_keys_ready is set (the sort() 64/// path); uniq() passes a bare listitem_T pointer and must not read this. 65union { 66varnumber_T inum ;///< for "N" 67double fnum ;///< for "n" and "f" 68 }key ; 69}ListSortItem ; 70 71typedef int (* ListSorter )(const void * ,const void * ); 72 73/// Type for tv_dict2list() function 74typedef enum { 75kDict2ListKeys ,///< List dictionary keys. 76kDict2ListValues ,///< List dictionary values. 77kDict2ListItems ,///< List dictionary contents: [keys, values]. 78}DictListType ; 79 80#include "eval/typval.c.generated.h" 81 82static const char e_variable_nested_too_deep_for_unlock [] 83= N_ ("E743: Variable nested too deep for (un)lock" ); 84static const char e_using_invalid_value_as_string [] 85= N_ ("E908: Using an invalid value as a String" ); 86static const char e_string_required_for_argument_nr [] 87= N_ ("E1174: String required for argument %d" ); 88static const char e_non_empty_string_required_for_argument_nr [] 89= N_ ("E1175: Non-empty string required for argument %d" ); 90static const char e_dict_required_for_argument_nr [] 91= N_ ("E1206: Dictionary required for argument %d" ); 92static const char e_number_required_for_argument_nr [] 93= N_ ("E1210: Number required for argument %d" ); 94static const char e_list_required_for_argument_nr [] 95= N_ ("E1211: List required for argument %d" ); 96static const char e_bool_required_for_argument_nr [] 97= N_ ("E1212: Bool required for argument %d" ); 98static const char e_float_or_number_required_for_argument_nr [] 99= N_ ("E1219: Float or Number required for argument %d" ); 100static const char e_string_or_number_required_for_argument_nr [] 101= N_ ("E1220: String or Number required for argument %d" ); 102static const char e_string_or_list_required_for_argument_nr [] 103= N_ ("E1222: String or List required for argument %d" ); 104static const char e_list_dict_blob_or_string_required_for_argument_nr [] 105= N_ ("E1225: List, Dictionary, Blob or String required for argument %d" ); 106static const char e_list_or_blob_required_for_argument_nr [] 107= N_ ("E1226: List or Blob required for argument %d" ); 108static const char e_blob_required_for_argument_nr [] 109= N_ ("E1238: Blob required for argument %d" ); 110static const char e_string_list_or_blob_required_for_argument_nr [] 111= N_ ("E1252: String, List or Blob required for argument %d" ); 112static const char e_string_or_function_required_for_argument_nr [] 113= N_ ("E1256: String or function required for argument %d" ); 114static const char e_non_null_dict_required_for_argument_nr [] 115= N_ ("E1297: Non-NULL Dictionary required for argument %d" ); 116 117bool tv_in_free_unref_items = false; 118 119// TODO(ZyX-I): Remove DICT_MAXNEST, make users be non-recursive instead 120 121#define DICT_MAXNEST 100 122 123const char * const tv_empty_string = "" ; 124 125// Lists: 126// List item: 127 128/// Allocate a list item 129/// 130/// @warning Allocated item is not initialized, do not forget to initialize it 131/// and specifically set lv_lock. 132/// 133/// @return [allocated] new list item. 134static listitem_T * tv_list_item_alloc (void ) 135FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC 136{ 137return xmalloc (sizeof (listitem_T )); 138} 139 140/// Remove a list item from a List and free it 141/// 142/// Also clears the value. 143/// 144/// @param[out] l List to remove item from. 145/// @param[in,out] item Item to remove. 146/// 147/// @return Pointer to the list item just after removed one, NULL if removed 148/// item was the last one. 149listitem_T * tv_list_item_remove (list_T * const l ,listitem_T * const item ) 150FUNC_ATTR_NONNULL_ALL 151{ 152listitem_T * const next_item = TV_LIST_ITEM_NEXT (l ,item ); 153tv_list_drop_items (l ,item ,item ); 154tv_clear (TV_LIST_ITEM_TV (item )); 155xfree (item ); 156return next_item ; 157} 158 159// List watchers: 160 161/// Add a watcher to a list 162/// 163/// @param[out] l List to add watcher to. 164/// @param[in] lw Watcher to add. 165void tv_list_watch_add (list_T * const l ,listwatch_T * const lw ) 166FUNC_ATTR_NONNULL_ALL 167{ 168lw -> lw_next = l -> lv_watch ; 169l -> lv_watch = lw ; 170} 171 172/// Remove a watcher from a list 173/// 174/// Does not give a warning if watcher was not found. 175/// 176/// @param[out] l List to remove watcher from. 177/// @param[in] lwrem Watcher to remove. 178void tv_list_watch_remove (list_T * const l ,listwatch_T * const lwrem ) 179FUNC_ATTR_NONNULL_ALL 180{ 181listwatch_T ** lwp = & l -> lv_watch ; 182for (listwatch_T * lw = l -> lv_watch ;lw != NULL ;lw = lw -> lw_next ) { 183if (lw == lwrem ) { 184* lwp = lw -> lw_next ; 185break ; 186 } 187lwp = & lw -> lw_next ; 188 } 189} 190 191/// Advance watchers to the next item 192/// 193/// Used just before removing an item from a list. 194/// 195/// @param[out] l List from which item is removed. 196/// @param[in] item List item being removed. 197static void tv_list_watch_fix (list_T * const l ,const listitem_T * const item ) 198FUNC_ATTR_NONNULL_ALL 199{ 200for (listwatch_T * lw = l -> lv_watch ;lw != NULL ;lw = lw -> lw_next ) { 201if (lw -> lw_item == item ) { 202lw -> lw_item = item -> li_next ; 203 } 204 } 205} 206 207// Alloc/free: 208 209/// Allocate an empty list 210/// 211/// Caller should take care of the reference count. 212/// 213/// @param[in] len Expected number of items to be populated before list 214/// becomes accessible from Vimscript. It is still valid to 215/// underpopulate a list, value only controls how many elements 216/// will be allocated in advance. Currently does nothing. 217/// @see ListLenSpecials. 218/// 219/// @return [allocated] new list. 220list_T * tv_list_alloc (const ptrdiff_t len ) 221FUNC_ATTR_NONNULL_RET 222{ 223list_T * const list = xcalloc (1 ,sizeof (list_T )); 224 225// Prepend the list to the list of lists for garbage collection. 226if (gc_first_list != NULL ) { 227gc_first_list -> lv_used_prev = list ; 228 } 229list -> lv_used_prev = NULL ; 230list -> lv_used_next = gc_first_list ; 231gc_first_list = list ; 232list -> lua_table_ref = LUA_NOREF ; 233return list ; 234} 235 236/// Initialize a static list with 10 items 237/// 238/// @param[out] sl Static list to initialize. 239void tv_list_init_static10 (staticList10_T * const sl ) 240FUNC_ATTR_NONNULL_ALL 241{ 242#define SL_SIZE ARRAY_SIZE(sl->sl_items) 243list_T * const l = & sl -> sl_list ; 244 245CLEAR_POINTER (sl ); 246l -> lv_first = & sl -> sl_items [0 ]; 247l -> lv_last = & sl -> sl_items [SL_SIZE - 1 ]; 248l -> lv_refcount = DO_NOT_FREE_CNT ; 249tv_list_set_lock (l ,VAR_FIXED ); 250sl -> sl_list .lv_len = 10 ; 251 252sl -> sl_items [0 ].li_prev = NULL ; 253sl -> sl_items [0 ].li_next = & sl -> sl_items [1 ]; 254sl -> sl_items [SL_SIZE - 1 ].li_prev = & sl -> sl_items [SL_SIZE - 2 ]; 255sl -> sl_items [SL_SIZE - 1 ].li_next = NULL ; 256 257for (size_t i = 1 ;i < SL_SIZE - 1 ;i ++ ) { 258listitem_T * const li = & sl -> sl_items [i ]; 259li -> li_prev = li - 1 ; 260li -> li_next = li + 1 ; 261 } 262#undef SL_SIZE 263} 264 265/// Initialize static list with undefined number of elements 266/// 267/// @param[out] l List to initialize. 268void tv_list_init_static (list_T * const l ) 269FUNC_ATTR_NONNULL_ALL 270{ 271CLEAR_POINTER (l ); 272l -> lv_refcount = DO_NOT_FREE_CNT ; 273} 274 275/// Free items contained in a list 276/// 277/// @param[in,out] l List to clear. 278void tv_list_free_contents (list_T * const l ) 279FUNC_ATTR_NONNULL_ALL 280{ 281for (listitem_T * item = l -> lv_first ;item != NULL ;item = l -> lv_first ) { 282// Remove the item before deleting it. 283l -> lv_first = item -> li_next ; 284tv_clear (& item -> li_tv ); 285xfree (item ); 286 } 287l -> lv_len = 0 ; 288l -> lv_idx_item = NULL ; 289l -> lv_last = NULL ; 290assert (l -> lv_watch == NULL ); 291} 292 293/// Free a list itself, ignoring items it contains 294/// 295/// Ignores the reference count. 296/// 297/// @param[in,out] l List to free. 298void tv_list_free_list (list_T * const l ) 299FUNC_ATTR_NONNULL_ALL 300{ 301// Remove the list from the list of lists for garbage collection. 302if (l -> lv_used_prev == NULL ) { 303gc_first_list = l -> lv_used_next ; 304 }else { 305l -> lv_used_prev -> lv_used_next = l -> lv_used_next ; 306 } 307if (l -> lv_used_next != NULL ) { 308l -> lv_used_next -> lv_used_prev = l -> lv_used_prev ; 309 } 310 311NLUA_CLEAR_REF (l -> lua_table_ref ); 312xfree (l ); 313} 314 315/// Free a list, including all items it points to 316/// 317/// Ignores the reference count. Does not do anything if 318/// tv_in_free_unref_items is true. 319/// 320/// @param[in,out] l List to free. 321void tv_list_free (list_T * const l ) 322FUNC_ATTR_NONNULL_ALL 323{ 324if (tv_in_free_unref_items ) { 325return ; 326 } 327 328tv_list_free_contents (l ); 329tv_list_free_list (l ); 330} 331 332/// Unreference a list 333/// 334/// Decrements the reference count and frees when it becomes zero or less. 335/// 336/// @param[in,out] l List to unreference. 337void tv_list_unref (list_T * const l ) 338{ 339if (l != NULL && -- l -> lv_refcount <=0 ) { 340tv_list_free (l ); 341 } 342} 343 344// Add/remove: 345 346/// Remove items "item" to "item2" from list "l" 347/// 348/// @warning Does not free the listitem or the value! 349/// 350/// @param[out] l List to remove from. 351/// @param[in] item First item to remove. 352/// @param[in] item2 Last item to remove. 353void tv_list_drop_items (list_T * const l ,listitem_T * const item ,listitem_T * const item2 ) 354FUNC_ATTR_NONNULL_ALL 355{ 356// Notify watchers. 357for (listitem_T * ip = item ;ip != item2 -> li_next ;ip = ip -> li_next ) { 358l -> lv_len -- ; 359tv_list_watch_fix (l ,ip ); 360 } 361 362if (item2 -> li_next == NULL ) { 363l -> lv_last = item -> li_prev ; 364 }else { 365item2 -> li_next -> li_prev = item -> li_prev ; 366 } 367if (item -> li_prev == NULL ) { 368l -> lv_first = item2 -> li_next ; 369 }else { 370item -> li_prev -> li_next = item2 -> li_next ; 371 } 372l -> lv_idx_item = NULL ; 373} 374 375/// Like tv_list_drop_items, but also frees all removed items 376void tv_list_remove_items (list_T * const l ,listitem_T * const item ,listitem_T * const item2 ) 377FUNC_ATTR_NONNULL_ALL 378{ 379tv_list_drop_items (l ,item ,item2 ); 380for (listitem_T * li = item ;;) { 381tv_clear (TV_LIST_ITEM_TV (li )); 382listitem_T * const nli = li -> li_next ; 383xfree (li ); 384if (li == item2 ) { 385break ; 386 } 387li = nli ; 388 } 389} 390 391/// Move items "item" to "item2" from list "l" to the end of the list "tgt_l" 392/// 393/// @param[out] l List to move from. 394/// @param[in] item First item to move. 395/// @param[in] item2 Last item to move. 396/// @param[out] tgt_l List to move to. 397/// @param[in] cnt Number of items moved. 398void tv_list_move_items (list_T * const l ,listitem_T * const item ,listitem_T * const item2 , 399list_T * const tgt_l ,const int cnt ) 400FUNC_ATTR_NONNULL_ALL 401{ 402tv_list_drop_items (l ,item ,item2 ); 403item -> li_prev = tgt_l -> lv_last ; 404item2 -> li_next = NULL ; 405if (tgt_l -> lv_last == NULL ) { 406tgt_l -> lv_first = item ; 407 }else { 408tgt_l -> lv_last -> li_next = item ; 409 } 410tgt_l -> lv_last = item2 ; 411tgt_l -> lv_len += cnt ; 412} 413 414/// Insert list item 415/// 416/// @param[out] l List to insert to. 417/// @param[in,out] ni Item to insert. 418/// @param[in] item Item to insert before. If NULL, inserts at the end of the 419/// list. 420void tv_list_insert (list_T * const l ,listitem_T * const ni ,listitem_T * const item ) 421FUNC_ATTR_NONNULL_ARG (1 ,2 ) 422{ 423if (item == NULL ) { 424// Append new item at end of list. 425tv_list_append (l ,ni ); 426 }else { 427// Insert new item before existing item. 428ni -> li_prev = item -> li_prev ; 429ni -> li_next = item ; 430if (item -> li_prev == NULL ) { 431l -> lv_first = ni ; 432l -> lv_idx ++ ; 433 }else { 434item -> li_prev -> li_next = ni ; 435l -> lv_idx_item = NULL ; 436 } 437item -> li_prev = ni ; 438l -> lv_len ++ ; 439 } 440} 441 442/// Insert Vimscript value into a list 443/// 444/// @param[out] l List to insert to. 445/// @param[in,out] tv Value to insert. Is copied (@see tv_copy()) to an 446/// allocated listitem_T and inserted. 447/// @param[in] item Item to insert before. If NULL, inserts at the end of the 448/// list. 449void tv_list_insert_tv (list_T * const l ,typval_T * const tv ,listitem_T * const item ) 450{ 451listitem_T * const ni = tv_list_item_alloc (); 452 453tv_copy (tv ,& ni -> li_tv ); 454tv_list_insert (l ,ni ,item ); 455} 456 457/// Append item to the end of list 458/// 459/// @param[out] l List to append to. 460/// @param[in,out] item Item to append. 461void tv_list_append (list_T * const l ,listitem_T * const item ) 462FUNC_ATTR_NONNULL_ALL 463{ 464if (l -> lv_last == NULL ) { 465// empty list 466l -> lv_first = item ; 467l -> lv_last = item ; 468item -> li_prev = NULL ; 469 }else { 470l -> lv_last -> li_next = item ; 471item -> li_prev = l -> lv_last ; 472l -> lv_last = item ; 473 } 474l -> lv_len ++ ; 475item -> li_next = NULL ; 476} 477 478/// Append Vimscript value to the end of list 479/// 480/// @param[out] l List to append to. 481/// @param[in,out] tv Value to append. Is copied (@see tv_copy()) to an 482/// allocated listitem_T. 483void tv_list_append_tv (list_T * const l ,typval_T * const tv ) 484FUNC_ATTR_NONNULL_ALL 485{ 486listitem_T * const li = tv_list_item_alloc (); 487tv_copy (tv ,TV_LIST_ITEM_TV (li )); 488tv_list_append (l ,li ); 489} 490 491/// Like tv_list_append_tv(), but tv is moved to a list 492/// 493/// This means that it is no longer valid to use contents of the typval_T after 494/// function exits. A pointer is returned to the allocated typval which can be used 495typval_T * tv_list_append_owned_tv (list_T * const l ,typval_T tv ) 496FUNC_ATTR_NONNULL_ALL 497{ 498listitem_T * const li = tv_list_item_alloc (); 499* TV_LIST_ITEM_TV (li )= tv ; 500tv_list_append (l ,li ); 501return TV_LIST_ITEM_TV (li ); 502} 503 504/// Append a list to a list as one item 505/// 506/// @param[out] l List to append to. 507/// @param[in,out] itemlist List to append. Reference count is increased. 508void tv_list_append_list (list_T * const l ,list_T * const itemlist ) 509FUNC_ATTR_NONNULL_ARG (1 ) 510{ 511tv_list_append_owned_tv (l , (typval_T ) { 512 .v_type = VAR_LIST , 513 .v_lock = VAR_UNLOCKED , 514 .vval .v_list = itemlist , 515 }); 516tv_list_ref (itemlist ); 517} 518 519/// Append a dictionary to a list 520/// 521/// @param[out] l List to append to. 522/// @param[in,out] dict Dictionary to append. Reference count is increased. 523void tv_list_append_dict (list_T * const l ,dict_T * const dict ) 524FUNC_ATTR_NONNULL_ARG (1 ) 525{ 526tv_list_append_owned_tv (l , (typval_T ) { 527 .v_type = VAR_DICT , 528 .v_lock = VAR_UNLOCKED , 529 .vval .v_dict = dict , 530 }); 531if (dict != NULL ) { 532dict -> dv_refcount ++ ; 533 } 534} 535 536/// Make a copy of "str" and append it as an item to list "l" 537/// 538/// @param[out] l List to append to. 539/// @param[in] str String to append. 540/// @param[in] len Length of the appended string. May be -1, in this 541/// case string is considered to be usual zero-terminated 542/// string or NULL “empty” string. 543void tv_list_append_string (list_T * const l ,const char * const str ,const ssize_t len ) 544FUNC_ATTR_NONNULL_ARG (1 ) 545{ 546tv_list_append_owned_tv (l , (typval_T ) { 547 .v_type = VAR_STRING , 548 .v_lock = VAR_UNLOCKED , 549 .vval .v_string = (str == NULL 550 ?NULL 551 : (len >=0 552 ?xmemdupz (str , (size_t )len ) 553 :xstrdup (str ))), 554 }); 555} 556 557/// Append given string to the list 558/// 559/// Unlike list_append_string this function does not copy the string. 560/// 561/// @param[out] l List to append to. 562/// @param[in] str String to append. 563void tv_list_append_allocated_string (list_T * const l ,char * const str ) 564FUNC_ATTR_NONNULL_ARG (1 ) 565{ 566tv_list_append_owned_tv (l , (typval_T ) { 567 .v_type = VAR_STRING , 568 .v_lock = VAR_UNLOCKED , 569 .vval .v_string = str , 570 }); 571} 572 573/// Append number to the list 574/// 575/// @param[out] l List to append to. 576/// @param[in] n Number to append. Will be recorded in the allocated 577/// listitem_T. 578void tv_list_append_number (list_T * const l ,const varnumber_T n ) 579{ 580tv_list_append_owned_tv (l , (typval_T ) { 581 .v_type = VAR_NUMBER , 582 .v_lock = VAR_UNLOCKED , 583 .vval .v_number = n , 584 }); 585} 586 587// Operations on the whole list: 588 589/// Make a copy of list 590/// 591/// @param[in] conv If non-NULL, then all internal strings will be converted. 592/// Only used when `deep` is true. 593/// @param[in] orig Original list to copy. 594/// @param[in] deep If false, then shallow copy will be done. 595/// @param[in] copyID See var_item_copy(). 596/// 597/// @return Copied list. May be NULL in case original list is NULL or some 598/// failure happens. The refcount of the new list is set to 1. 599list_T * tv_list_copy (const vimconv_T * const conv ,list_T * const orig ,const bool deep , 600const int copyID ) 601FUNC_ATTR_WARN_UNUSED_RESULT 602{ 603if (orig == NULL ) { 604return NULL ; 605 } 606 607list_T * copy = tv_list_alloc (tv_list_len (orig )); 608tv_list_ref (copy ); 609if (copyID != 0 ) { 610// Do this before adding the items, because one of the items may 611// refer back to this list. 612orig -> lv_copyID = copyID ; 613orig -> lv_copylist = copy ; 614 } 615TV_LIST_ITER (orig ,item , { 616if (got_int ) { 617break ; 618 } 619listitem_T * const ni = tv_list_item_alloc (); 620if (deep ) { 621if (var_item_copy (conv ,TV_LIST_ITEM_TV (item ),TV_LIST_ITEM_TV (ni ), 622deep ,copyID )== FAIL ) { 623xfree (ni ); 624 gototv_list_copy_error ; 625 } 626 }else { 627tv_copy (TV_LIST_ITEM_TV (item ),TV_LIST_ITEM_TV (ni )); 628 } 629tv_list_append (copy ,ni ); 630 }); 631 632return copy ; 633 634tv_list_copy_error : 635tv_list_unref (copy ); 636return NULL ; 637} 638 639/// Get the list item in "l" with index "n1". "n1" is adjusted if needed. 640/// Return NULL if there is no such item. 641listitem_T * tv_list_check_range_index_one (list_T * const l ,int * const n1 ,const bool quiet ) 642{ 643listitem_T * li = tv_list_find_index (l ,n1 ); 644if (li != NULL ) { 645return li ; 646 } 647 648if (!quiet ) { 649semsg (_ (e_list_index_out_of_range_nr ), (int64_t )(* n1 )); 650 } 651return NULL ; 652} 653 654/// Check that "n2" can be used as the second index in a range of list "l". 655/// If "n1" or "n2" is negative it is changed to the positive index. 656/// "li1" is the item for item "n1". 657/// Return OK or FAIL. 658int tv_list_check_range_index_two (list_T * const l ,int * const n1 ,const listitem_T * const li1 , 659int * const n2 ,const bool quiet ) 660{ 661if (* n2 < 0 ) { 662listitem_T * ni = tv_list_find (l ,* n2 ); 663if (ni == NULL ) { 664if (!quiet ) { 665semsg (_ (e_list_index_out_of_range_nr ), (int64_t )(* n2 )); 666 } 667return FAIL ; 668 } 669* n2 = tv_list_idx_of_item (l ,ni ); 670 } 671 672// Check that n2 isn't before n1. 673if (* n1 < 0 ) { 674* n1 = tv_list_idx_of_item (l ,li1 ); 675 } 676if (* n2 < * n1 ) { 677if (!quiet ) { 678semsg (_ (e_list_index_out_of_range_nr ), (int64_t )(* n2 )); 679 } 680return FAIL ; 681 } 682return OK ; 683} 684 685/// Assign values from list "src" into a range of "dest". 686/// "idx1_arg" is the index of the first item in "dest" to be replaced. 687/// "idx2" is the index of last item to be replaced, but when "empty_idx2" is 688/// true then replace all items after "idx1". 689/// "op" is the operator, normally "=" but can be "+=" and the like. 690/// "varname" is used for error messages. 691/// Returns OK or FAIL. 692int tv_list_assign_range (list_T * const dest ,list_T * const src ,const int idx1_arg ,const int idx2 , 693const bool empty_idx2 ,const char * const op ,const char * const varname ) 694{ 695int idx1 = idx1_arg ; 696listitem_T * const first_li = tv_list_find_index (dest ,& idx1 ); 697listitem_T * src_li ; 698 699// Check whether any of the list items is locked before making any changes. 700int idx = idx1 ; 701listitem_T * dest_li = first_li ; 702for (src_li = tv_list_first (src );src_li != NULL && dest_li != NULL ;) { 703if (value_check_lock (TV_LIST_ITEM_TV (dest_li )-> v_lock ,varname ,TV_CSTRING )) { 704return FAIL ; 705 } 706src_li = TV_LIST_ITEM_NEXT (src ,src_li ); 707if (src_li == NULL || (!empty_idx2 && idx2 == idx )) { 708break ; 709 } 710dest_li = TV_LIST_ITEM_NEXT (dest ,dest_li ); 711idx ++ ; 712 } 713 714// Assign the List values to the list items. 715idx = idx1 ; 716dest_li = first_li ; 717for (src_li = tv_list_first (src );src_li != NULL ;) { 718assert (dest_li != NULL ); 719if (op != NULL && * op != '=' ) { 720eexe_mod_op (TV_LIST_ITEM_TV (dest_li ),TV_LIST_ITEM_TV (src_li ),op ); 721 }else { 722tv_clear (TV_LIST_ITEM_TV (dest_li )); 723tv_copy (TV_LIST_ITEM_TV (src_li ),TV_LIST_ITEM_TV (dest_li )); 724 } 725src_li = TV_LIST_ITEM_NEXT (src ,src_li ); 726if (src_li == NULL || (!empty_idx2 && idx2 == idx )) { 727break ; 728 } 729if (TV_LIST_ITEM_NEXT (dest ,dest_li )== NULL ) { 730// Need to add an empty item. 731tv_list_append_number (dest ,0 ); 732// "dest_li" may have become invalid after append, don’t use it. 733dest_li = tv_list_last (dest );// Valid again. 734 }else { 735dest_li = TV_LIST_ITEM_NEXT (dest ,dest_li ); 736 } 737idx ++ ; 738 } 739if (src_li != NULL ) { 740emsg (_ ("E710: List value has more items than target" )); 741return FAIL ; 742 } 743if (empty_idx2 744 ? (dest_li != NULL && TV_LIST_ITEM_NEXT (dest ,dest_li )!= NULL ) 745 :idx != idx2 ) { 746emsg (_ ("E711: List value has not enough items" )); 747return FAIL ; 748 } 749return OK ; 750} 751 752/// Flatten up to "maxitems" in "list", starting at "first" to depth "maxdepth". 753/// When "first" is NULL use the first item. 754/// Does nothing if "maxdepth" is 0. 755/// 756/// @param[in,out] list List to flatten 757/// @param[in] maxdepth Maximum depth that will be flattened 758/// 759/// @return OK or FAIL 760void tv_list_flatten (list_T * list ,listitem_T * first ,int64_t maxitems ,int64_t maxdepth ) 761FUNC_ATTR_NONNULL_ARG (1 ) 762{ 763listitem_T * item ; 764int done = 0 ; 765if (maxdepth == 0 ) { 766return ; 767 } 768 769if (first == NULL ) { 770item = list -> lv_first ; 771 }else { 772item = first ; 773 } 774 775while (item != NULL && done < maxitems ) { 776listitem_T * next = item -> li_next ; 777 778fast_breakcheck (); 779if (got_int ) { 780return ; 781 } 782if (item -> li_tv .v_type == VAR_LIST ) { 783list_T * itemlist = item -> li_tv .vval .v_list ; 784 785tv_list_drop_items (list ,item ,item ); 786tv_list_extend (list ,itemlist ,next ); 787 788if (maxdepth > 0 ) { 789tv_list_flatten (list , 790item -> li_prev == NULL ?list -> lv_first :item -> li_prev -> li_next , 791itemlist -> lv_len ,maxdepth - 1 ); 792 } 793tv_clear (& item -> li_tv ); 794xfree (item ); 795 } 796 797done ++ ; 798item = next ; 799 } 800} 801 802/// "items(blob)" function 803/// Converts a Blob into a List of [index, byte] pairs. 804/// Caller must have already checked that argvars[0] is a Blob. 805/// A null blob behaves like an empty blob. 806static void tv_blob2items (typval_T * argvars ,typval_T * rettv ) 807{ 808blob_T * blob = argvars [0 ].vval .v_blob ; 809 810tv_list_alloc_ret (rettv ,tv_blob_len (blob )); 811 812for (int i = 0 ;i < tv_blob_len (blob );i ++ ) { 813list_T * l2 = tv_list_alloc (2 ); 814tv_list_append_list (rettv -> vval .v_list ,l2 ); 815tv_list_append_number (l2 ,i ); 816tv_list_append_number (l2 ,tv_blob_get (blob ,i )); 817 } 818} 819 820/// "items(dict)" function 821static void tv_dict2items (typval_T * argvars ,typval_T * rettv ) 822{ 823tv_dict2list (argvars ,rettv ,kDict2ListItems ); 824} 825 826/// "items(list)" function 827/// Caller must have already checked that argvars[0] is a List. 828static void tv_list2items (typval_T * argvars ,typval_T * rettv ) 829{ 830list_T * l = argvars [0 ].vval .v_list ; 831 832tv_list_alloc_ret (rettv ,tv_list_len (l )); 833if (l == NULL ) { 834return ;// null list behaves like an empty list 835 } 836 837varnumber_T idx = 0 ; 838TV_LIST_ITER (l ,li , { 839list_T * l2 = tv_list_alloc (2 ); 840tv_list_append_list (rettv -> vval .v_list ,l2 ); 841tv_list_append_number (l2 ,idx ); 842tv_list_append_tv (l2 ,TV_LIST_ITEM_TV (li )); 843idx ++ ; 844 }); 845} 846 847/// "items(string)" function 848/// Caller must have already checked that argvars[0] is a String. 849static void tv_string2items (typval_T * argvars ,typval_T * rettv ) 850{ 851const char * p = argvars [0 ].vval .v_string ; 852 853tv_list_alloc_ret (rettv ,kListLenMayKnow ); 854if (p == NULL ) { 855return ;// null string behaves like an empty string 856 } 857 858for (varnumber_T idx = 0 ;* p != NUL ;idx ++ ) { 859int len = utfc_ptr2len (p ); 860if (len == 0 ) { 861break ; 862 } 863list_T * l2 = tv_list_alloc (2 ); 864tv_list_append_list (rettv -> vval .v_list ,l2 ); 865tv_list_append_number (l2 ,idx ); 866tv_list_append_string (l2 ,p ,len ); 867p += len ; 868 } 869} 870 871/// Extend first list with the second 872/// 873/// @param[out] l1 List to extend. 874/// @param[in] l2 List to extend with. 875/// @param[in] bef If not NULL, extends before this item. 876void tv_list_extend (list_T * const l1 ,list_T * const l2 ,listitem_T * const bef ) 877FUNC_ATTR_NONNULL_ARG (1 ) 878{ 879int todo = tv_list_len (l2 ); 880 881// NULL list is equivalent to an empty list: nothing to do. 882if (todo == 0 ) { 883return ; 884 } 885 886listitem_T * const befbef = (bef == NULL ?NULL :bef -> li_prev ); 887listitem_T * const saved_next = (befbef == NULL ?NULL :befbef -> li_next ); 888// We also quit the loop when we have inserted the original item count of 889// the list, avoid a hang when we extend a list with itself. 890for (listitem_T * item = tv_list_first (l2 ) 891 ;item != NULL && todo -- 892 ;item = (item == befbef ?saved_next :item -> li_next )) { 893tv_list_insert_tv (l1 ,TV_LIST_ITEM_TV (item ),bef ); 894 } 895} 896 897/// Concatenate lists into a new list 898/// 899/// @param[in] l1 First list. 900/// @param[in] l2 Second list. 901/// @param[out] ret_tv Location where new list is saved. 902/// 903/// @return OK or FAIL. 904int tv_list_concat (list_T * const l1 ,list_T * const l2 ,typval_T * const tv ) 905FUNC_ATTR_WARN_UNUSED_RESULT 906{ 907list_T * l ; 908 909tv -> v_type = VAR_LIST ; 910tv -> v_lock = VAR_UNLOCKED ; 911if (l1 == NULL && l2 == NULL ) { 912l = NULL ; 913 }else if (l1 == NULL ) { 914l = tv_list_copy (NULL ,l2 , false,0 ); 915 }else { 916l = tv_list_copy (NULL ,l1 , false,0 ); 917if (l != NULL && l2 != NULL ) { 918tv_list_extend (l ,l2 ,NULL ); 919 } 920 } 921if (l == NULL && !(l1 == NULL && l2 == NULL )) { 922return FAIL ; 923 } 924 925tv -> vval .v_list = l ; 926return OK ; 927} 928 929static list_T * tv_list_slice (list_T * ol ,varnumber_T n1 ,varnumber_T n2 ) 930{ 931list_T * l = tv_list_alloc (n2 - n1 + 1 ); 932listitem_T * item = tv_list_find (ol , (int )n1 ); 933for (;n1 <=n2 ;n1 ++ ) { 934tv_list_append_tv (l ,TV_LIST_ITEM_TV (item )); 935item = TV_LIST_ITEM_NEXT (ol ,item ); 936 } 937return l ; 938} 939 940int tv_list_slice_or_index (list_T * list ,bool range ,varnumber_T n1_arg ,varnumber_T n2_arg , 941bool exclusive ,typval_T * rettv ,bool verbose ) 942{ 943int len = tv_list_len (rettv -> vval .v_list ); 944varnumber_T n1 = n1_arg ; 945varnumber_T n2 = n2_arg ; 946 947if (n1 < 0 ) { 948n1 = len + n1 ; 949 } 950if (n1 < 0 || n1 >=len ) { 951// For a range we allow invalid values and return an empty list. 952// A list index out of range is an error. 953if (!range ) { 954if (verbose ) { 955semsg (_ (e_list_index_out_of_range_nr ), (int64_t )n1_arg ); 956 } 957return FAIL ; 958 } 959n1 = len ; 960 } 961if (range ) { 962if (n2 < 0 ) { 963n2 = len + n2 ; 964 }else if (n2 >=len ) { 965n2 = len - (exclusive ?0 :1 ); 966 } 967if (exclusive ) { 968n2 -- ; 969 } 970if (n2 < 0 || n2 + 1 < n1 ) { 971n2 = -1 ; 972 } 973list_T * l = tv_list_slice (rettv -> vval .v_list ,n1 ,n2 ); 974tv_clear (rettv ); 975tv_list_set_ret (rettv ,l ); 976 }else { 977// copy the item to "var1" to avoid that freeing the list makes it 978// invalid. 979typval_T var1 ; 980tv_copy (TV_LIST_ITEM_TV (tv_list_find (rettv -> vval .v_list , (int )n1 )),& var1 ); 981tv_clear (rettv ); 982* rettv = var1 ; 983 } 984return OK ; 985} 986 987typedef struct { 988String s ; 989char * tofree ; 990}Join ; 991 992/// Join list into a string, helper function 993/// 994/// @param[out] gap Garray where result will be saved. 995/// @param[in] l List to join. 996/// @param[in] sep Used separator. 997/// @param[in] join_gap Garray to keep each list item string. 998/// 999/// @return OK in case of success, FAIL otherwise. 1000static int list_join_inner (garray_T * const gap ,list_T * const l ,const char * const sep , 1001garray_T * const join_gap ) 1002FUNC_ATTR_NONNULL_ALL 1003{ 1004size_t sumlen = 0 ; 1005bool first = true; 1006 1007// Stringify each item in the list. 1008TV_LIST_ITER (l ,item , { 1009if (got_int ) { 1010break ; 1011 } 1012String s ; 1013s .data = encode_tv2echo (TV_LIST_ITEM_TV (item ),& s .size ); 1014if (s .data == NULL ) { 1015return FAIL ; 1016 } 1017 1018sumlen += s .size ; 1019 1020Join * const p = GA_APPEND_VIA_PTR (Join ,join_gap ); 1021p -> s = s ; 1022p -> tofree = s .data ; 1023 1024line_breakcheck (); 1025 }); 1026 1027// Allocate result buffer with its total size, avoid re-allocation and 1028// multiple copy operations. Add 2 for a tailing ']' and NUL. 1029size_t seplen = strlen (sep ); 1030if (join_gap -> ga_len >=2 ) { 1031sumlen += seplen * (size_t )(join_gap -> ga_len - 1 ); 1032 } 1033ga_grow (gap , (int )sumlen + 2 ); 1034 1035for (int i = 0 ;i < join_gap -> ga_len && !got_int ;i ++ ) { 1036if (first ) { 1037first = false; 1038 }else { 1039ga_concat_len (gap ,sep ,seplen ); 1040 } 1041const Join * const p = ((const Join * )join_gap -> ga_data )+ i ; 1042 1043if (p -> s .data != NULL ) { 1044ga_concat_len (gap ,p -> s .data ,p -> s .size ); 1045 } 1046line_breakcheck (); 1047 } 1048 1049return OK ; 1050} 1051 1052/// Join list into a string using given separator 1053/// 1054/// @param[out] gap Garray where the joined list will be saved. 1055/// @param[in] l List. 1056/// @param[in] sep Separator. 1057/// 1058/// @return OK in case of success, FAIL otherwise. 1059int tv_list_join (garray_T * const gap ,list_T * const l ,const char * const sep ) 1060FUNC_ATTR_NONNULL_ARG (1 ) 1061{ 1062if (!tv_list_len (l )) { 1063return OK ; 1064 } 1065 1066garray_T join_ga ; 1067int retval ; 1068 1069ga_init (& join_ga , (int )sizeof (Join ),tv_list_len (l )); 1070retval = list_join_inner (gap ,l ,sep ,& join_ga ); 1071 1072#define FREE_JOIN_TOFREE (join ) xfree((join)->tofree) 1073GA_DEEP_CLEAR (& join_ga ,Join ,FREE_JOIN_TOFREE ); 1074#undef FREE_JOIN_TOFREE 1075 1076return retval ; 1077} 1078 1079/// "join()" function 1080void f_join (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1081{ 1082if (argvars [0 ].v_type != VAR_LIST ) { 1083emsg (_ (e_listreq )); 1084return ; 1085 } 1086const char * const sep = (argvars [1 ].v_type == VAR_UNKNOWN 1087 ?" " 1088 :tv_get_string_chk (& argvars [1 ])); 1089 1090rettv -> v_type = VAR_STRING ; 1091 1092if (sep != NULL ) { 1093garray_T ga ; 1094ga_init (& ga , (int )sizeof (char ),80 ); 1095tv_list_join (& ga ,argvars [0 ].vval .v_list ,sep ); 1096ga_append (& ga ,NUL ); 1097rettv -> vval .v_string = ga .ga_data ; 1098 }else { 1099rettv -> vval .v_string = NULL ; 1100 } 1101} 1102 1103/// "list2str()" function 1104void f_list2str (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1105{ 1106garray_T ga ; 1107 1108rettv -> v_type = VAR_STRING ; 1109rettv -> vval .v_string = NULL ; 1110if (argvars [0 ].v_type != VAR_LIST ) { 1111emsg (_ (e_invarg )); 1112return ; 1113 } 1114 1115list_T * const l = argvars [0 ].vval .v_list ; 1116if (l == NULL ) { 1117return ;// empty list results in empty string 1118 } 1119 1120ga_init (& ga ,1 ,80 ); 1121char buf [MB_MAXBYTES + 1 ]; 1122 1123TV_LIST_ITER_CONST (l ,li , { 1124const varnumber_T n = tv_get_number (TV_LIST_ITEM_TV (li )); 1125const size_t buflen = (size_t )utf_char2bytes ((int )n ,buf ); 1126buf [buflen ]= NUL ; 1127ga_concat_len (& ga ,buf ,buflen ); 1128 }); 1129ga_append (& ga ,NUL ); 1130 1131rettv -> vval .v_string = ga .ga_data ; 1132} 1133 1134/// "remove({list})" function 1135void tv_list_remove (typval_T * argvars ,typval_T * rettv ,const char * arg_errmsg ) 1136{ 1137list_T * l ; 1138bool error = false; 1139 1140if (value_check_lock (tv_list_locked ((l = argvars [0 ].vval .v_list )), 1141arg_errmsg ,TV_TRANSLATE )) { 1142return ; 1143 } 1144 1145int64_t idx = tv_get_number_chk (& argvars [1 ],& error ); 1146 1147listitem_T * item ; 1148 1149if (error ) { 1150// Type error: do nothing, errmsg already given. 1151 }else if ((item = tv_list_find (l , (int )idx ))== NULL ) { 1152semsg (_ (e_list_index_out_of_range_nr ),idx ); 1153 }else { 1154if (argvars [2 ].v_type == VAR_UNKNOWN ) { 1155// Remove one item, return its value. 1156tv_list_drop_items (l ,item ,item ); 1157* rettv = * TV_LIST_ITEM_TV (item ); 1158xfree (item ); 1159 }else { 1160listitem_T * item2 ; 1161// Remove range of items, return list with values. 1162int64_t end = tv_get_number_chk (& argvars [2 ],& error ); 1163if (error ) { 1164// Type error: do nothing. 1165 }else if ((item2 = tv_list_find (l , (int )end ))== NULL ) { 1166semsg (_ (e_list_index_out_of_range_nr ),end ); 1167 }else { 1168int cnt = 0 ; 1169 1170listitem_T * li ; 1171for (li = item ;li != NULL ;li = TV_LIST_ITEM_NEXT (l ,li )) { 1172cnt ++ ; 1173if (li == item2 ) { 1174break ; 1175 } 1176 } 1177if (li == NULL ) {// Didn't find "item2" after "item". 1178emsg (_ (e_invrange )); 1179 }else { 1180tv_list_move_items (l ,item ,item2 ,tv_list_alloc_ret (rettv ,cnt ), 1181cnt ); 1182 } 1183 } 1184 } 1185 } 1186} 1187 1188static sortinfo_T * sortinfo = NULL ; 1189 1190#define ITEM_COMPARE_FAIL 999 1191 1192/// Compare functions for f_sort() and f_uniq() below. 1193static int item_compare (const void * s1 ,const void * s2 ,bool keep_zero ) 1194{ 1195ListSortItem * const si1 = (ListSortItem * )s1 ; 1196ListSortItem * const si2 = (ListSortItem * )s2 ; 1197 1198typval_T * const tv1 = TV_LIST_ITEM_TV (si1 -> item ); 1199typval_T * const tv2 = TV_LIST_ITEM_TV (si2 -> item ); 1200 1201int res ; 1202 1203if (sortinfo -> item_compare_numbers ) { 1204const varnumber_T v1 = sortinfo -> item_compare_keys_ready 1205 ?si1 -> key .inum :tv_get_number (tv1 ); 1206const varnumber_T v2 = sortinfo -> item_compare_keys_ready 1207 ?si2 -> key .inum :tv_get_number (tv2 ); 1208 1209res = v1 == v2 ?0 :v1 > v2 ?1 :-1 ; 1210 gotoitem_compare_end ; 1211 } 1212 1213if (sortinfo -> item_compare_float ) { 1214const float_T v1 = sortinfo -> item_compare_keys_ready 1215 ?si1 -> key .fnum :tv_get_float (tv1 ); 1216const float_T v2 = sortinfo -> item_compare_keys_ready 1217 ?si2 -> key .fnum :tv_get_float (tv2 ); 1218 1219res = v1 == v2 ?0 :v1 > v2 ?1 :-1 ; 1220 gotoitem_compare_end ; 1221 } 1222 1223if (sortinfo -> item_compare_numeric && sortinfo -> item_compare_keys_ready ) { 1224double n1 = si1 -> key .fnum ; 1225double n2 = si2 -> key .fnum ; 1226 1227res = n1 == n2 ?0 :n1 > n2 ?1 :-1 ; 1228if (res == 0 && !keep_zero ) { 1229res = si1 -> idx > si2 -> idx ?1 :-1 ; 1230 } 1231return res ; 1232 } 1233 1234char * tofree1 = NULL ; 1235char * tofree2 = NULL ; 1236char * p1 ; 1237char * p2 ; 1238 1239// encode_tv2string() puts quotes around a string and allocates memory. Don't 1240// do that for string variables. Use a single quote when comparing with 1241// a non-string to do what the docs promise. 1242if (tv1 -> v_type == VAR_STRING ) { 1243if (tv2 -> v_type != VAR_STRING || sortinfo -> item_compare_numeric ) { 1244p1 = "'" ; 1245 }else { 1246p1 = tv1 -> vval .v_string ; 1247 } 1248 }else { 1249tofree1 = p1 = encode_tv2string (tv1 ,NULL ); 1250 } 1251if (tv2 -> v_type == VAR_STRING ) { 1252if (tv1 -> v_type != VAR_STRING || sortinfo -> item_compare_numeric ) { 1253p2 = "'" ; 1254 }else { 1255p2 = tv2 -> vval .v_string ; 1256 } 1257 }else { 1258tofree2 = p2 = encode_tv2string (tv2 ,NULL ); 1259 } 1260if (p1 == NULL ) { 1261p1 = "" ; 1262 } 1263if (p2 == NULL ) { 1264p2 = "" ; 1265 } 1266if (!sortinfo -> item_compare_numeric ) { 1267if (sortinfo -> item_compare_lc ) { 1268res = strcoll (p1 ,p2 ); 1269 }else { 1270res = sortinfo -> item_compare_ic ?STRICMP (p1 ,p2 ) :strcmp (p1 ,p2 ); 1271 } 1272 }else { 1273double n1 = strtod (p1 ,& p1 ); 1274double n2 = strtod (p2 ,& p2 ); 1275res = n1 == n2 ?0 :n1 > n2 ?1 :-1 ; 1276 } 1277 1278xfree (tofree1 ); 1279xfree (tofree2 ); 1280 1281item_compare_end : 1282// When the result would be zero, compare the item indexes. Makes the 1283// sort stable. 1284if (res == 0 && !keep_zero ) { 1285// WARNING: When using uniq si1 and si2 are actually listitem_T **, no 1286// indexes are there. 1287res = si1 -> idx > si2 -> idx ?1 :-1 ; 1288 } 1289return res ; 1290} 1291 1292static int item_compare_keeping_zero (const void * s1 ,const void * s2 ) 1293{ 1294return item_compare (s1 ,s2 , true); 1295} 1296 1297static int item_compare_not_keeping_zero (const void * s1 ,const void * s2 ) 1298{ 1299return item_compare (s1 ,s2 , false); 1300} 1301 1302static int item_compare2 (const void * s1 ,const void * s2 ,bool keep_zero ) 1303{ 1304typval_T rettv ; 1305typval_T argv [3 ]; 1306const char * func_name ; 1307partial_T * partial = sortinfo -> item_compare_partial ; 1308 1309// shortcut after failure in previous call; compare all items equal 1310if (sortinfo -> item_compare_func_err ) { 1311return 0 ; 1312 } 1313 1314ListSortItem * si1 = (ListSortItem * )s1 ; 1315ListSortItem * si2 = (ListSortItem * )s2 ; 1316 1317if (partial == NULL ) { 1318func_name = sortinfo -> item_compare_func ; 1319 }else { 1320func_name = partial_name (partial ); 1321 } 1322 1323// Copy the values. This is needed to be able to set v_lock to VAR_FIXED 1324// in the copy without changing the original list items. 1325tv_copy (TV_LIST_ITEM_TV (si1 -> item ),& argv [0 ]); 1326tv_copy (TV_LIST_ITEM_TV (si2 -> item ),& argv [1 ]); 1327 1328rettv .v_type = VAR_UNKNOWN ;// tv_clear() uses this 1329funcexe_T funcexe = FUNCEXE_INIT ; 1330funcexe .fe_evaluate = true; 1331funcexe .fe_partial = partial ; 1332funcexe .fe_selfdict = sortinfo -> item_compare_selfdict ; 1333int res = call_func (func_name ,-1 ,& rettv ,2 ,argv ,& funcexe ); 1334tv_clear (& argv [0 ]); 1335tv_clear (& argv [1 ]); 1336 1337if (res == FAIL ) { 1338// XXX: ITEM_COMPARE_FAIL is unused 1339res = ITEM_COMPARE_FAIL ; 1340sortinfo -> item_compare_func_err = true; 1341 }else { 1342varnumber_T n = tv_get_number_chk (& rettv ,& sortinfo -> item_compare_func_err ); 1343res = (n > 0 ) ?1 : (n < 0 ) ?-1 :0 ; 1344 } 1345if (sortinfo -> item_compare_func_err ) { 1346res = ITEM_COMPARE_FAIL ;// return value has wrong type 1347 } 1348tv_clear (& rettv ); 1349 1350// When the result would be zero, compare the pointers themselves. Makes 1351// the sort stable. 1352if (res == 0 && !keep_zero ) { 1353// WARNING: When using uniq si1 and si2 are actually listitem_T **, no 1354// indexes are there. 1355res = si1 -> idx > si2 -> idx ?1 :-1 ; 1356 } 1357 1358return res ; 1359} 1360 1361static int item_compare2_keeping_zero (const void * s1 ,const void * s2 ) 1362{ 1363return item_compare2 (s1 ,s2 , true); 1364} 1365 1366static int item_compare2_not_keeping_zero (const void * s1 ,const void * s2 ) 1367{ 1368return item_compare2 (s1 ,s2 , false); 1369} 1370 1371/// Precompute the numeric sort key of each item. Only for the builtin numeric 1372/// compare modes; each key is computed exactly as item_compare() would have. 1373static void sort_compute_keys (ListSortItem * ptrs ,int len ,sortinfo_T * info ) 1374{ 1375if (info -> item_compare_numbers ) { 1376for (int i = 0 ;i < len ;i ++ ) { 1377ptrs [i ].key .inum = tv_get_number (& ptrs [i ].item -> li_tv ); 1378 } 1379 }else if (info -> item_compare_float ) { 1380for (int i = 0 ;i < len ;i ++ ) { 1381ptrs [i ].key .fnum = tv_get_float (& ptrs [i ].item -> li_tv ); 1382 } 1383 }else {// info->item_compare_numeric 1384for (int i = 0 ;i < len ;i ++ ) { 1385typval_T * tv = & ptrs [i ].item -> li_tv ; 1386 1387// A string is compared as a single quote in numeric mode, which 1388// strtod() reads as 0. 1389if (tv -> v_type == VAR_STRING ) { 1390ptrs [i ].key .fnum = 0.0 ; 1391 }else { 1392char * p = encode_tv2string (tv ,NULL ); 1393ptrs [i ].key .fnum = p == NULL ?0.0 :strtod (p ,NULL ); 1394xfree (p ); 1395 } 1396 } 1397 } 1398info -> item_compare_keys_ready = true; 1399} 1400 1401/// sort() List "l" 1402static void do_sort (list_T * l ,sortinfo_T * info ) 1403{ 1404const int len = tv_list_len (l ); 1405 1406// Make an array with each entry pointing to an item in the List. 1407ListSortItem * ptrs = xmalloc ((size_t )((unsigned )len * sizeof (ListSortItem ))); 1408 1409// f_sort(): ptrs will be the list to sort 1410int i = 0 ; 1411TV_LIST_ITER (l ,li , { 1412ptrs [i ].item = li ; 1413ptrs [i ].idx = i ; 1414i ++ ; 1415 }); 1416 1417info -> item_compare_func_err = false; 1418info -> item_compare_keys_ready = false; 1419 1420if (info -> item_compare_func == NULL && info -> item_compare_partial == NULL 1421&& (info -> item_compare_numbers || info -> item_compare_float 1422|| info -> item_compare_numeric )) { 1423sort_compute_keys (ptrs ,len ,info ); 1424 } 1425ListSorter item_compare_func = ((info -> item_compare_func == NULL 1426&& info -> item_compare_partial == NULL ) 1427 ?item_compare_not_keeping_zero 1428 :item_compare2_not_keeping_zero ); 1429 1430// Sort the array with item pointers. 1431qsort (ptrs , (size_t )len ,sizeof (ListSortItem ),item_compare_func ); 1432if (!info -> item_compare_func_err ) { 1433// Clear the list and append the items in the sorted order. 1434l -> lv_first = NULL ; 1435l -> lv_last = NULL ; 1436l -> lv_idx_item = NULL ; 1437l -> lv_len = 0 ; 1438for (i = 0 ;i < len ;i ++ ) { 1439tv_list_append (l ,ptrs [i ].item ); 1440 } 1441 } 1442if (info -> item_compare_func_err ) { 1443emsg (_ ("E702: Sort compare function failed" )); 1444 } 1445 1446xfree (ptrs ); 1447} 1448 1449/// uniq() List "l" 1450static void do_uniq (list_T * l ,sortinfo_T * info ) 1451{ 1452const int len = tv_list_len (l ); 1453 1454// Make an array with each entry pointing to an item in the List. 1455ListSortItem * ptrs = xmalloc ((size_t )((unsigned )len * sizeof (ListSortItem ))); 1456 1457// f_uniq(): ptrs will be a stack of items to remove. 1458 1459info -> item_compare_func_err = false; 1460ListSorter item_compare_func = ((info -> item_compare_func == NULL 1461&& info -> item_compare_partial == NULL ) 1462 ?item_compare_keeping_zero 1463 :item_compare2_keeping_zero ); 1464 1465for (listitem_T * li = TV_LIST_ITEM_NEXT (l ,tv_list_first (l ));li != NULL ;) { 1466listitem_T * const prev_li = TV_LIST_ITEM_PREV (l ,li ); 1467if (item_compare_func (& prev_li ,& li )== 0 ) { 1468li = tv_list_item_remove (l ,li ); 1469 }else { 1470li = TV_LIST_ITEM_NEXT (l ,li ); 1471 } 1472if (info -> item_compare_func_err ) { 1473emsg (_ ("E882: Uniq compare function failed" )); 1474break ; 1475 } 1476 } 1477 1478xfree (ptrs ); 1479} 1480 1481/// Parse the optional arguments to sort() and uniq() and return the values in "info". 1482static int parse_sort_uniq_args (typval_T * argvars ,sortinfo_T * info ) 1483{ 1484info -> item_compare_ic = false; 1485info -> item_compare_lc = false; 1486info -> item_compare_numeric = false; 1487info -> item_compare_numbers = false; 1488info -> item_compare_float = false; 1489info -> item_compare_func = NULL ; 1490info -> item_compare_partial = NULL ; 1491info -> item_compare_selfdict = NULL ; 1492info -> item_compare_keys_ready = false; 1493 1494if (argvars [1 ].v_type == VAR_UNKNOWN ) { 1495return OK ; 1496 } 1497 1498// optional second argument: {func} 1499if (argvars [1 ].v_type == VAR_FUNC ) { 1500info -> item_compare_func = argvars [1 ].vval .v_string ; 1501 }else if (argvars [1 ].v_type == VAR_PARTIAL ) { 1502info -> item_compare_partial = argvars [1 ].vval .v_partial ; 1503 }else { 1504bool error = false; 1505int nr = (int )tv_get_number_chk (& argvars [1 ],& error ); 1506if (error ) { 1507return FAIL ;// type error; errmsg already given 1508 } 1509if (nr == 1 ) { 1510info -> item_compare_ic = true; 1511 }else if (argvars [1 ].v_type != VAR_NUMBER ) { 1512info -> item_compare_func = tv_get_string (& argvars [1 ]); 1513 }else if (nr != 0 ) { 1514emsg (_ (e_invarg )); 1515return FAIL ; 1516 } 1517if (info -> item_compare_func != NULL ) { 1518if (* info -> item_compare_func == NUL ) { 1519// empty string means default sort 1520info -> item_compare_func = NULL ; 1521 }else if (strcmp (info -> item_compare_func ,"n" )== 0 ) { 1522info -> item_compare_func = NULL ; 1523info -> item_compare_numeric = true; 1524 }else if (strcmp (info -> item_compare_func ,"N" )== 0 ) { 1525info -> item_compare_func = NULL ; 1526info -> item_compare_numbers = true; 1527 }else if (strcmp (info -> item_compare_func ,"f" )== 0 ) { 1528info -> item_compare_func = NULL ; 1529info -> item_compare_float = true; 1530 }else if (strcmp (info -> item_compare_func ,"i" )== 0 ) { 1531info -> item_compare_func = NULL ; 1532info -> item_compare_ic = true; 1533 }else if (strcmp (info -> item_compare_func ,"l" )== 0 ) { 1534info -> item_compare_func = NULL ; 1535info -> item_compare_lc = true; 1536 } 1537 } 1538 } 1539 1540if (argvars [2 ].v_type != VAR_UNKNOWN ) { 1541// optional third argument: {dict} 1542if (tv_check_for_dict_arg (argvars ,2 )== FAIL ) { 1543return FAIL ; 1544 } 1545info -> item_compare_selfdict = argvars [2 ].vval .v_dict ; 1546 } 1547 1548return OK ; 1549} 1550 1551/// "sort()" or "uniq()" function 1552static void do_sort_uniq (typval_T * argvars ,typval_T * rettv ,bool sort ) 1553{ 1554if (argvars [0 ].v_type != VAR_LIST ) { 1555semsg (_ (e_listarg ),sort ?"sort()" :"uniq()" ); 1556return ; 1557 } 1558 1559// Pointer to current info struct used in compare function. Save and restore 1560// the current one for nested calls. 1561sortinfo_T info ; 1562sortinfo_T * old_sortinfo = sortinfo ; 1563sortinfo = & info ; 1564 1565const char * const arg_errmsg = (sort ?N_ ("sort() argument" ) :N_ ("uniq() argument" )); 1566list_T * const l = argvars [0 ].vval .v_list ; 1567if (value_check_lock (tv_list_locked (l ),arg_errmsg ,TV_TRANSLATE )) { 1568 gototheend ; 1569 } 1570tv_list_set_ret (rettv ,l ); 1571 1572const int len = tv_list_len (l ); 1573if (len <=1 ) { 1574 gototheend ;// short list sorts pretty quickly 1575 } 1576if (parse_sort_uniq_args (argvars ,& info )== FAIL ) { 1577 gototheend ; 1578 } 1579 1580if (sort ) { 1581do_sort (l ,& info ); 1582 }else { 1583do_uniq (l ,& info ); 1584 } 1585 1586theend : 1587sortinfo = old_sortinfo ; 1588} 1589 1590/// "sort({list})" function 1591void f_sort (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1592{ 1593do_sort_uniq (argvars ,rettv , true); 1594} 1595 1596/// "uniq({list})" function 1597void f_uniq (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 1598{ 1599do_sort_uniq (argvars ,rettv , false); 1600} 1601 1602/// Check whether two lists are equal 1603/// 1604/// @param[in] l1 First list to compare. 1605/// @param[in] l2 Second list to compare. 1606/// @param[in] ic True if case is to be ignored. 1607/// 1608/// @return True if lists are equal, false otherwise. 1609bool tv_list_equal (list_T * const l1 ,list_T * const l2 ,const bool ic ) 1610FUNC_ATTR_WARN_UNUSED_RESULT 1611{ 1612if (l1 == l2 ) { 1613return true; 1614 } 1615if (tv_list_len (l1 )!= tv_list_len (l2 )) { 1616return false; 1617 } 1618if (tv_list_len (l1 )== 0 ) { 1619// empty and NULL list are considered equal 1620return true; 1621 } 1622if (l1 == NULL || l2 == NULL ) { 1623return false; 1624 } 1625 1626listitem_T * item1 = tv_list_first (l1 ); 1627listitem_T * item2 = tv_list_first (l2 ); 1628for (;item1 != NULL && item2 != NULL 1629 ; (item1 = TV_LIST_ITEM_NEXT (l1 ,item1 ), 1630item2 = TV_LIST_ITEM_NEXT (l2 ,item2 ))) { 1631if (!tv_equal (TV_LIST_ITEM_TV (item1 ),TV_LIST_ITEM_TV (item2 ),ic )) { 1632return false; 1633 } 1634 } 1635assert (item1 == NULL && item2 == NULL ); 1636return true; 1637} 1638 1639/// Reverse list in-place 1640/// 1641/// @param[in,out] l List to reverse. 1642void tv_list_reverse (list_T * const l ) 1643{ 1644if (tv_list_len (l ) <=1 ) { 1645return ; 1646 } 1647#define SWAP (a ,b ) \ 1648 do { \ 1649 tmp = (a); \ 1650 (a) = (b); \ 1651 (b) = tmp; \ 1652 } while (0) 1653listitem_T * tmp ; 1654 1655SWAP (l -> lv_first ,l -> lv_last ); 1656for (listitem_T * li = l -> lv_first ;li != NULL ;li = li -> li_next ) { 1657SWAP (li -> li_next ,li -> li_prev ); 1658 } 1659#undef SWAP 1660 1661l -> lv_idx = l -> lv_len - l -> lv_idx - 1 ; 1662} 1663 1664// Indexing/searching: 1665 1666/// Locate item with a given index in a list and return it 1667/// 1668/// @param[in] l List to index. 1669/// @param[in] n Index. Negative index is counted from the end, -1 is the last 1670/// item. 1671/// 1672/// @return Item at the given index or NULL if `n` is out of range. 1673listitem_T * tv_list_find (list_T * const l ,int n ) 1674FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1675{ 1676STATIC_ASSERT (sizeof (n )== sizeof (l -> lv_idx ), 1677"n and lv_idx sizes do not match" ); 1678if (l == NULL ) { 1679return NULL ; 1680 } 1681 1682n = tv_list_uidx (l ,n ); 1683if (n == -1 ) { 1684return NULL ; 1685 } 1686 1687int idx ; 1688listitem_T * item ; 1689 1690// When there is a cached index may start search from there. 1691if (l -> lv_idx_item != NULL ) { 1692if (n < l -> lv_idx /2 ) { 1693// Closest to the start of the list. 1694item = l -> lv_first ; 1695idx = 0 ; 1696 }else if (n > (l -> lv_idx + l -> lv_len ) /2 ) { 1697// Closest to the end of the list. 1698item = l -> lv_last ; 1699idx = l -> lv_len - 1 ; 1700 }else { 1701// Closest to the cached index. 1702item = l -> lv_idx_item ; 1703idx = l -> lv_idx ; 1704 } 1705 }else { 1706if (n < l -> lv_len /2 ) { 1707// Closest to the start of the list. 1708item = l -> lv_first ; 1709idx = 0 ; 1710 }else { 1711// Closest to the end of the list. 1712item = l -> lv_last ; 1713idx = l -> lv_len - 1 ; 1714 } 1715 } 1716 1717while (n > idx ) { 1718// Search forward. 1719item = item -> li_next ; 1720idx ++ ; 1721 } 1722while (n < idx ) { 1723// Search backward. 1724item = item -> li_prev ; 1725idx -- ; 1726 } 1727 1728assert (idx == n ); 1729// Cache the used index. 1730l -> lv_idx = idx ; 1731l -> lv_idx_item = item ; 1732 1733return item ; 1734} 1735 1736/// Get list item l[n] as a number 1737/// 1738/// @param[in] l List to index. 1739/// @param[in] n Index in a list. 1740/// @param[out] ret_error Location where 1 will be saved if index was not 1741/// found. May be NULL. If everything is OK, 1742/// `*ret_error` is not touched. 1743/// 1744/// @return Integer value at the given index or -1. 1745varnumber_T tv_list_find_nr (list_T * const l ,const int n ,bool * const ret_error ) 1746FUNC_ATTR_WARN_UNUSED_RESULT 1747{ 1748const listitem_T * const li = tv_list_find (l ,n ); 1749if (li == NULL ) { 1750if (ret_error != NULL ) { 1751* ret_error = true; 1752 } 1753return -1 ; 1754 } 1755return tv_get_number_chk (TV_LIST_ITEM_TV (li ),ret_error ); 1756} 1757 1758/// Get list item l[n] as a string 1759/// 1760/// @param[in] l List to index. 1761/// @param[in] n Index in a list. 1762/// 1763/// @return List item string value or NULL in case of error. 1764const char * tv_list_find_str (list_T * const l ,const int n ) 1765FUNC_ATTR_WARN_UNUSED_RESULT 1766{ 1767const listitem_T * const li = tv_list_find (l ,n ); 1768if (li == NULL ) { 1769semsg (_ (e_list_index_out_of_range_nr ), (int64_t )n ); 1770return NULL ; 1771 } 1772return tv_get_string (TV_LIST_ITEM_TV (li )); 1773} 1774 1775/// Like tv_list_find() but when a negative index is used that is not found use 1776/// zero and set "idx" to zero. Used for first index of a range. 1777static listitem_T * tv_list_find_index (list_T * const l ,int * const idx ) 1778FUNC_ATTR_WARN_UNUSED_RESULT 1779{ 1780listitem_T * li = tv_list_find (l ,* idx ); 1781if (li != NULL ) { 1782return li ; 1783 } 1784 1785if (* idx < 0 ) { 1786* idx = 0 ; 1787li = tv_list_find (l ,* idx ); 1788 } 1789return li ; 1790} 1791 1792/// Locate item in a list and return its index 1793/// 1794/// @param[in] l List to search. 1795/// @param[in] item Item to search for. 1796/// 1797/// @return Index of an item or -1 if item is not in the list. 1798int tv_list_idx_of_item (const list_T * const l ,const listitem_T * const item ) 1799FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 1800{ 1801if (l == NULL ) { 1802return -1 ; 1803 } 1804int idx = 0 ; 1805TV_LIST_ITER_CONST (l ,li , { 1806if (li == item ) { 1807return idx ; 1808 } 1809idx ++ ; 1810 }); 1811return -1 ; 1812} 1813 1814// Dictionaries: 1815// Dictionary watchers: 1816 1817/// Perform all necessary cleanup for a `DictWatcher` instance 1818/// 1819/// @param watcher Watcher to free. 1820static void tv_dict_watcher_free (DictWatcher * watcher ) 1821FUNC_ATTR_NONNULL_ALL 1822{ 1823callback_free (& watcher -> callback ); 1824xfree (watcher -> key_pattern ); 1825xfree (watcher ); 1826} 1827 1828/// Add watcher to a dictionary 1829/// 1830/// @param[in] dict Dictionary to add watcher to. 1831/// @param[in] key_pattern Pattern to watch for. 1832/// @param[in] key_pattern_len Key pattern length. 1833/// @param callback Function to be called on events. 1834void tv_dict_watcher_add (dict_T * const dict ,const char * const key_pattern , 1835const size_t key_pattern_len ,Callback callback ) 1836FUNC_ATTR_NONNULL_ARG (2 ) 1837{ 1838if (dict == NULL ) { 1839return ; 1840 } 1841DictWatcher * const watcher = xmalloc (sizeof (DictWatcher )); 1842watcher -> key_pattern = xmemdupz (key_pattern ,key_pattern_len ); 1843watcher -> key_pattern_len = key_pattern_len ; 1844watcher -> callback = callback ; 1845watcher -> busy = false; 1846watcher -> needs_free = false; 1847QUEUE_INSERT_TAIL (& dict -> watchers ,& watcher -> node ); 1848} 1849 1850/// Check whether two callbacks are equal 1851/// 1852/// @param[in] cb1 First callback to check. 1853/// @param[in] cb2 Second callback to check. 1854/// 1855/// @return True if they are equal, false otherwise. 1856bool tv_callback_equal (const Callback * cb1 ,const Callback * cb2 ) 1857FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 1858{ 1859if (cb1 -> type != cb2 -> type ) { 1860return false; 1861 } 1862switch (cb1 -> type ) { 1863case kCallbackFuncref : 1864return strequal (cb1 -> data .funcref ,cb2 -> data .funcref ); 1865case kCallbackPartial : 1866// FIXME: this is inconsistent with tv_equal but is needed for precision 1867// maybe change dictwatcheradd to return a watcher id instead? 1868return cb1 -> data .partial == cb2 -> data .partial ; 1869case kCallbackLua : 1870return cb1 -> data .luaref == cb2 -> data .luaref ; 1871case kCallbackExpr : 1872return strequal (cb1 -> data .expr ,cb2 -> data .expr ); 1873case kCallbackNone : 1874return true; 1875 } 1876abort (); 1877return false; 1878} 1879 1880/// Unref/free callback 1881void callback_free (Callback * callback ) 1882FUNC_ATTR_NONNULL_ALL 1883{ 1884switch (callback -> type ) { 1885case kCallbackFuncref : 1886func_unref (callback -> data .funcref ); 1887xfree (callback -> data .funcref ); 1888break ; 1889case kCallbackPartial : 1890partial_unref (callback -> data .partial ); 1891break ; 1892case kCallbackLua : 1893NLUA_CLEAR_REF (callback -> data .luaref ); 1894break ; 1895case kCallbackExpr : 1896xfree (callback -> data .expr ); 1897break ; 1898case kCallbackNone : 1899break ; 1900 } 1901callback -> type = kCallbackNone ; 1902callback -> data .funcref = NULL ; 1903} 1904 1905/// Copy a callback into a typval_T. 1906void callback_put (Callback * cb ,typval_T * tv ) 1907FUNC_ATTR_NONNULL_ALL 1908{ 1909switch (cb -> type ) { 1910case kCallbackPartial : 1911tv -> v_type = VAR_PARTIAL ; 1912tv -> vval .v_partial = cb -> data .partial ; 1913cb -> data .partial -> pt_refcount ++ ; 1914break ; 1915case kCallbackFuncref : 1916tv -> v_type = VAR_FUNC ; 1917tv -> vval .v_string = xstrdup (cb -> data .funcref ); 1918func_ref (cb -> data .funcref ); 1919break ; 1920case kCallbackLua : 1921// TODO(tjdevries): Unified Callback. 1922// At this point this isn't possible, but it'd be nice to put 1923// these handled more neatly in one place. 1924// So instead, we just do the default and put nil 1925default : 1926tv -> v_type = VAR_SPECIAL ; 1927tv -> vval .v_special = kSpecialVarNull ; 1928break ; 1929 } 1930} 1931 1932// Copy callback from "src" to "dest", incrementing the refcounts. 1933void callback_copy (Callback * dest ,Callback * src ) 1934FUNC_ATTR_NONNULL_ALL 1935{ 1936dest -> type = src -> type ; 1937switch (src -> type ) { 1938case kCallbackPartial : 1939dest -> data .partial = src -> data .partial ; 1940dest -> data .partial -> pt_refcount ++ ; 1941break ; 1942case kCallbackFuncref : 1943dest -> data .funcref = xstrdup (src -> data .funcref ); 1944func_ref (src -> data .funcref ); 1945break ; 1946case kCallbackLua : 1947dest -> data .luaref = api_new_luaref (src -> data .luaref ); 1948break ; 1949case kCallbackExpr : 1950dest -> data .expr = xstrdup (src -> data .expr ); 1951break ; 1952default : 1953dest -> data .funcref = NULL ; 1954break ; 1955 } 1956} 1957 1958/// Generate a string description of a callback 1959char * callback_to_string (Callback * cb ,Arena * arena ) 1960{ 1961if (cb -> type == kCallbackLua ) { 1962return nlua_funcref_str (cb -> data .luaref ,arena , true); 1963 } 1964 1965const size_t msglen = 100 ; 1966char * msg = xmallocz (msglen ); 1967 1968switch (cb -> type ) { 1969case kCallbackFuncref : 1970// TODO(tjdevries): Is this enough space for this? 1971snprintf (msg ,msglen ,"<vim function: %s>" ,cb -> data .funcref ); 1972break ; 1973case kCallbackPartial : 1974snprintf (msg ,msglen ,"<vim partial: %s>" ,cb -> data .partial -> pt_name ); 1975break ; 1976default : 1977* msg = NUL ; 1978break ; 1979 } 1980return msg ; 1981} 1982 1983/// Remove watcher from a dictionary 1984/// 1985/// @param dict Dictionary to remove watcher from. 1986/// @param[in] key_pattern Pattern to remove watcher for. 1987/// @param[in] key_pattern_len Pattern length. 1988/// @param callback Callback to remove watcher for. 1989/// 1990/// @return True on success, false if relevant watcher was not found. 1991bool tv_dict_watcher_remove (dict_T * const dict ,const char * const key_pattern , 1992const size_t key_pattern_len ,Callback callback ) 1993FUNC_ATTR_NONNULL_ARG (2 ) 1994{ 1995if (dict == NULL ) { 1996return false; 1997 } 1998 1999QUEUE * w = NULL ; 2000DictWatcher * watcher = NULL ; 2001bool matched = false; 2002bool queue_is_busy = false; 2003QUEUE_FOREACH (w ,& dict -> watchers , { 2004watcher = tv_dict_watcher_node_data (w ); 2005if (watcher -> busy ) { 2006queue_is_busy = true; 2007 } 2008if (tv_callback_equal (& watcher -> callback ,& callback ) 2009&& watcher -> key_pattern_len == key_pattern_len 2010&& memcmp (watcher -> key_pattern ,key_pattern ,key_pattern_len )== 0 ) { 2011matched = true; 2012break ; 2013 } 2014 }) 2015 2016if (!matched ) { 2017return false; 2018 } 2019 2020if (queue_is_busy ) { 2021watcher -> needs_free = true; 2022 }else { 2023QUEUE_REMOVE (w ); 2024tv_dict_watcher_free (watcher ); 2025 } 2026return true; 2027} 2028 2029/// Test if `key` matches with `watcher->key_pattern` 2030/// 2031/// @param[in] watcher Watcher to check key pattern from. 2032/// @param[in] key Key to check. 2033/// 2034/// @return true if key matches, false otherwise. 2035static bool tv_dict_watcher_matches (DictWatcher * watcher ,const char * const key ) 2036FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 2037{ 2038// For now only allow very simple globbing in key patterns: a '*' at the end 2039// of the string means it should match everything up to the '*' instead of the 2040// whole string. 2041const size_t len = watcher -> key_pattern_len ; 2042if (len && watcher -> key_pattern [len - 1 ]== '*' ) { 2043return strncmp (key ,watcher -> key_pattern ,len - 1 )== 0 ; 2044 } 2045return strcmp (key ,watcher -> key_pattern )== 0 ; 2046} 2047 2048/// Send a change notification to all dictionary watchers that match given key 2049/// 2050/// @param[in] dict Dictionary which was modified. 2051/// @param[in] key Key which was modified. 2052/// @param[in] newtv New key value. 2053/// @param[in] oldtv Old key value. 2054void tv_dict_watcher_notify (dict_T * const dict ,const char * const key ,typval_T * const newtv , 2055typval_T * const oldtv ) 2056FUNC_ATTR_NONNULL_ARG (1 ,2 ) 2057{ 2058typval_T argv [3 ]; 2059 2060argv [0 ].v_type = VAR_DICT ; 2061argv [0 ].v_lock = VAR_UNLOCKED ; 2062argv [0 ].vval .v_dict = dict ; 2063argv [1 ].v_type = VAR_STRING ; 2064argv [1 ].v_lock = VAR_UNLOCKED ; 2065argv [1 ].vval .v_string = xstrdup (key ); 2066argv [2 ].v_type = VAR_DICT ; 2067argv [2 ].v_lock = VAR_UNLOCKED ; 2068argv [2 ].vval .v_dict = tv_dict_alloc (); 2069argv [2 ].vval .v_dict -> dv_refcount ++ ; 2070 2071if (newtv ) { 2072dictitem_T * const v = tv_dict_item_alloc_len (S_LEN ("new" )); 2073tv_copy (newtv ,& v -> di_tv ); 2074tv_dict_add (argv [2 ].vval .v_dict ,v ); 2075 } 2076 2077if (oldtv && oldtv -> v_type != VAR_UNKNOWN ) { 2078dictitem_T * const v = tv_dict_item_alloc_len (S_LEN ("old" )); 2079tv_copy (oldtv ,& v -> di_tv ); 2080tv_dict_add (argv [2 ].vval .v_dict ,v ); 2081 } 2082 2083typval_T rettv ; 2084 2085bool any_needs_free = false; 2086dict -> dv_refcount ++ ; 2087QUEUE * w ; 2088QUEUE_FOREACH (w ,& dict -> watchers , { 2089DictWatcher * watcher = tv_dict_watcher_node_data (w ); 2090if (!watcher -> busy && tv_dict_watcher_matches (watcher ,key )) { 2091rettv = TV_INITIAL_VALUE ; 2092watcher -> busy = true; 2093callback_call (& watcher -> callback ,3 ,argv ,& rettv ); 2094watcher -> busy = false; 2095tv_clear (& rettv ); 2096if (watcher -> needs_free ) { 2097any_needs_free = true; 2098 } 2099 } 2100 }) 2101if (any_needs_free ) { 2102QUEUE_FOREACH (w ,& dict -> watchers , { 2103DictWatcher * watcher = tv_dict_watcher_node_data (w ); 2104if (watcher -> needs_free ) { 2105QUEUE_REMOVE (w ); 2106tv_dict_watcher_free (watcher ); 2107 } 2108 }) 2109 } 2110tv_dict_unref (dict ); 2111 2112for (size_t i = 1 ;i < ARRAY_SIZE (argv );i ++ ) { 2113tv_clear (argv + i ); 2114 } 2115} 2116 2117// Dictionary item: 2118 2119/// Allocate a dictionary item 2120/// 2121/// @note that the type and value of the item (->di_tv) still needs to 2122/// be initialized. 2123/// 2124/// @param[in] key Key, is copied to the new item. 2125/// @param[in] key_len Key length. 2126/// 2127/// @return [allocated] new dictionary item. 2128dictitem_T * tv_dict_item_alloc_len (const char * const key ,const size_t key_len ) 2129FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 2130FUNC_ATTR_MALLOC 2131{ 2132// Allocating a struct smaller than its static size is UB (#37160) 2133dictitem_T * const di = xmalloc (MAX (sizeof (dictitem_T ), 2134 offsetof(dictitem_T ,di_key )+ key_len + 1 )); 2135memcpy (di -> di_key ,key ,key_len ); 2136di -> di_key [key_len ]= NUL ; 2137di -> di_flags = DI_FLAGS_ALLOC ; 2138di -> di_tv .v_lock = VAR_UNLOCKED ; 2139di -> di_tv .v_type = VAR_UNKNOWN ; 2140return di ; 2141} 2142 2143/// Allocate a dictionary item 2144/// 2145/// @note that the type and value of the item (->di_tv) still needs to 2146/// be initialized. 2147/// 2148/// @param[in] key Key, is copied to the new item. 2149/// 2150/// @return [allocated] new dictionary item. 2151dictitem_T * tv_dict_item_alloc (const char * const key ) 2152FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 2153FUNC_ATTR_MALLOC 2154{ 2155return tv_dict_item_alloc_len (key ,strlen (key )); 2156} 2157 2158/// Free a dictionary item, also clearing the value 2159/// 2160/// @param item Item to free. 2161void tv_dict_item_free (dictitem_T * const item ) 2162FUNC_ATTR_NONNULL_ALL 2163{ 2164tv_clear (& item -> di_tv ); 2165if (item -> di_flags & DI_FLAGS_ALLOC ) { 2166xfree (item ); 2167 } 2168} 2169 2170/// Make a copy of a dictionary item 2171/// 2172/// @param[in] di Item to copy. 2173/// 2174/// @return [allocated] new dictionary item. 2175dictitem_T * tv_dict_item_copy (dictitem_T * const di ) 2176FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 2177{ 2178dictitem_T * const new_di = tv_dict_item_alloc (di -> di_key ); 2179tv_copy (& di -> di_tv ,& new_di -> di_tv ); 2180return new_di ; 2181} 2182 2183/// Remove item from dictionary and free it 2184/// 2185/// @param dict Dictionary to remove item from. 2186/// @param item Item to remove. 2187void tv_dict_item_remove (dict_T * const dict ,dictitem_T * const item ) 2188FUNC_ATTR_NONNULL_ALL 2189{ 2190hashitem_T * const hi = hash_find (& dict -> dv_hashtab ,item -> di_key ); 2191if (HASHITEM_EMPTY (hi )) { 2192semsg (_ (e_intern2 ),"tv_dict_item_remove()" ); 2193 }else { 2194hash_remove (& dict -> dv_hashtab ,hi ); 2195 } 2196tv_dict_item_free (item ); 2197} 2198 2199// Alloc/free: 2200 2201/// Allocate an empty dictionary. 2202/// Caller should take care of the reference count. 2203/// 2204/// @return [allocated] new dictionary. 2205dict_T * tv_dict_alloc (void ) 2206FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT 2207{ 2208dict_T * const d = xcalloc (1 ,sizeof (dict_T )); 2209 2210// Add the dict to the list of dicts for garbage collection. 2211if (gc_first_dict != NULL ) { 2212gc_first_dict -> dv_used_prev = d ; 2213 } 2214d -> dv_used_next = gc_first_dict ; 2215d -> dv_used_prev = NULL ; 2216gc_first_dict = d ; 2217 2218hash_init (& d -> dv_hashtab ); 2219d -> dv_lock = VAR_UNLOCKED ; 2220d -> dv_scope = VAR_NO_SCOPE ; 2221d -> dv_refcount = 0 ; 2222d -> dv_copyID = 0 ; 2223QUEUE_INIT (& d -> watchers ); 2224 2225d -> lua_table_ref = LUA_NOREF ; 2226 2227return d ; 2228} 2229 2230/// Free items contained in a dictionary 2231/// 2232/// @param[in,out] d Dictionary to clear. 2233void tv_dict_free_contents (dict_T * const d ) 2234FUNC_ATTR_NONNULL_ALL 2235{ 2236// Lock the hashtab, we don't want it to resize while freeing items. 2237hash_lock (& d -> dv_hashtab ); 2238assert (d -> dv_hashtab .ht_locked > 0 ); 2239HASHTAB_ITER (& d -> dv_hashtab ,hi , { 2240// Remove the item before deleting it, just in case there is 2241// something recursive causing trouble. 2242dictitem_T * const di = TV_DICT_HI2DI (hi ); 2243hash_remove (& d -> dv_hashtab ,hi ); 2244tv_dict_item_free (di ); 2245 }); 2246 2247while (!QUEUE_EMPTY (& d -> watchers )) { 2248QUEUE * w = QUEUE_HEAD (& d -> watchers ); 2249QUEUE_REMOVE (w ); 2250DictWatcher * watcher = tv_dict_watcher_node_data (w ); 2251tv_dict_watcher_free (watcher ); 2252 } 2253 2254hash_clear (& d -> dv_hashtab ); 2255d -> dv_hashtab .ht_locked -- ; 2256hash_init (& d -> dv_hashtab ); 2257} 2258 2259/// Free a dictionary itself, ignoring items it contains 2260/// 2261/// Ignores the reference count. 2262/// 2263/// @param[in,out] d Dictionary to free. 2264void tv_dict_free_dict (dict_T * const d ) 2265FUNC_ATTR_NONNULL_ALL 2266{ 2267// Remove the dict from the list of dicts for garbage collection. 2268if (d -> dv_used_prev == NULL ) { 2269gc_first_dict = d -> dv_used_next ; 2270 }else { 2271d -> dv_used_prev -> dv_used_next = d -> dv_used_next ; 2272 } 2273if (d -> dv_used_next != NULL ) { 2274d -> dv_used_next -> dv_used_prev = d -> dv_used_prev ; 2275 } 2276 2277NLUA_CLEAR_REF (d -> lua_table_ref ); 2278xfree (d ); 2279} 2280 2281/// Free a dictionary, including all items it contains 2282/// 2283/// Ignores the reference count. 2284/// 2285/// @param d Dictionary to free. 2286void tv_dict_free (dict_T * const d ) 2287FUNC_ATTR_NONNULL_ALL 2288{ 2289if (tv_in_free_unref_items ) { 2290return ; 2291 } 2292 2293tv_dict_free_contents (d ); 2294tv_dict_free_dict (d ); 2295} 2296 2297/// Unreference a dictionary 2298/// 2299/// Decrements the reference count and frees dictionary when it becomes zero. 2300/// 2301/// @param[in] d Dictionary to operate on. 2302void tv_dict_unref (dict_T * const d ) 2303{ 2304if (d != NULL && -- d -> dv_refcount <=0 ) { 2305tv_dict_free (d ); 2306 } 2307} 2308 2309// Indexing/searching: 2310 2311/// Find item in dictionary 2312/// 2313/// @param[in] d Dictionary to check. 2314/// @param[in] key Dictionary key. 2315/// @param[in] len Key length. If negative, then strlen(key) is used. 2316/// 2317/// @return found item or NULL if nothing was found. 2318dictitem_T * tv_dict_find (const dict_T * const d ,const char * const key ,const ptrdiff_t len ) 2319FUNC_ATTR_NONNULL_ARG (2 )FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2320{ 2321if (d == NULL ) { 2322return NULL ; 2323 } 2324hashitem_T * const hi = (len < 0 2325 ?hash_find (& d -> dv_hashtab ,key ) 2326 :hash_find_len (& d -> dv_hashtab ,key , (size_t )len )); 2327if (HASHITEM_EMPTY (hi )) { 2328return NULL ; 2329 } 2330return TV_DICT_HI2DI (hi ); 2331} 2332 2333/// Check if a key is present in a dictionary. 2334/// 2335/// @param[in] d Dictionary to check. 2336/// @param[in] key Dictionary key. 2337/// 2338/// @return whether the key is present in the dictionary. 2339bool tv_dict_has_key (const dict_T * const d ,const char * const key ) 2340FUNC_ATTR_NONNULL_ARG (2 )FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2341{ 2342return tv_dict_find (d ,key ,-1 )!= NULL ; 2343} 2344 2345/// Get a typval item from a dictionary and copy it into "rettv". 2346/// 2347/// @param[in] d Dictionary to check. 2348/// @param[in] key Dictionary key. 2349/// @param[in] rettv Return value. 2350/// @return OK in case of success or FAIL if nothing was found. 2351int tv_dict_get_tv (dict_T * d ,const char * const key ,typval_T * rettv ) 2352{ 2353dictitem_T * const di = tv_dict_find (d ,key ,-1 ); 2354if (di == NULL ) { 2355return FAIL ; 2356 } 2357 2358tv_copy (& di -> di_tv ,rettv ); 2359return OK ; 2360} 2361 2362/// Gets a number item from a dictionary. 2363/// 2364/// @param[in] d Dictionary to get item from. 2365/// @param[in] key Key to find in dictionary. 2366/// 2367/// @return Number value, or 0 if the item does not exist. 2368varnumber_T tv_dict_get_number (const dict_T * const d ,const char * const key ) 2369FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2370{ 2371return tv_dict_get_number_def (d ,key ,0 ); 2372} 2373 2374/// Gets a number item from a dictionary, or a given default value. 2375/// 2376/// @param[in] d Dictionary to get item from. 2377/// @param[in] key Key to find in dictionary. 2378/// @param[in] def Default value. 2379/// 2380/// @return Number value, or `def` value if the item does not exist. 2381varnumber_T tv_dict_get_number_def (const dict_T * const d ,const char * const key ,const int def ) 2382FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2383{ 2384dictitem_T * const di = tv_dict_find (d ,key ,-1 ); 2385if (di == NULL ) { 2386return def ; 2387 } 2388return tv_get_number (& di -> di_tv ); 2389} 2390 2391/// Gets a bool item from a dictionary, or a given default value. 2392/// 2393/// @param[in] d Dictionary to get item from. 2394/// @param[in] key Key to find in dictionary. 2395/// @param[in] def Default value. 2396/// 2397/// @return Number value, or `def` value if the item does not exist. 2398varnumber_T tv_dict_get_bool (const dict_T * const d ,const char * const key ,const int def ) 2399FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2400{ 2401dictitem_T * const di = tv_dict_find (d ,key ,-1 ); 2402if (di == NULL ) { 2403return def ; 2404 } 2405return tv_get_bool (& di -> di_tv ); 2406} 2407 2408/// Converts a dict to an environment 2409char ** tv_dict_to_env (dict_T * denv ) 2410{ 2411size_t env_size = (size_t )tv_dict_len (denv ); 2412 2413size_t i = 0 ; 2414char ** env = NULL ; 2415 2416// + 1 for NULL 2417env = xmalloc ((env_size + 1 )* sizeof (* env )); 2418 2419TV_DICT_ITER (denv ,var , { 2420const char * str = tv_get_string (& var -> di_tv ); 2421assert (str ); 2422size_t len = strlen (var -> di_key )+ strlen (str )+ strlen ("=" )+ 1 ; 2423env [i ]= xmalloc (len ); 2424snprintf (env [i ],len ,"%s=%s" ,var -> di_key ,str ); 2425i ++ ; 2426 }); 2427 2428// must be null terminated 2429env [env_size ]= NULL ; 2430return env ; 2431} 2432 2433/// Get a string item from a dictionary 2434/// 2435/// @param[in] d Dictionary to get item from. 2436/// @param[in] key Dictionary key. 2437/// @param[in] save If true, returned string will be placed in the allocated 2438/// memory. 2439/// 2440/// @return NULL if key does not exist, empty string in case of type error, 2441/// string item value otherwise. If returned value is not NULL, it may 2442/// be allocated depending on `save` argument. 2443char * tv_dict_get_string (const dict_T * const d ,const char * const key ,const bool save ) 2444FUNC_ATTR_WARN_UNUSED_RESULT 2445{ 2446static char numbuf [NUMBUFLEN ]; 2447const char * const s = tv_dict_get_string_buf (d ,key ,numbuf ); 2448if (save && s != NULL ) { 2449return xstrdup (s ); 2450 } 2451return (char * )s ; 2452} 2453 2454/// Get a string item from a dictionary 2455/// 2456/// @param[in] d Dictionary to get item from. 2457/// @param[in] key Dictionary key. 2458/// @param[in] numbuf Buffer for non-string items converted to strings, at 2459/// least of #NUMBUFLEN length. 2460/// 2461/// @return NULL if key does not exist, empty string in case of type error, 2462/// string item value otherwise. 2463const char * tv_dict_get_string_buf (const dict_T * const d ,const char * const key ,char * const numbuf ) 2464FUNC_ATTR_WARN_UNUSED_RESULT 2465{ 2466const dictitem_T * const di = tv_dict_find (d ,key ,-1 ); 2467if (di == NULL ) { 2468return NULL ; 2469 } 2470return tv_get_string_buf (& di -> di_tv ,numbuf ); 2471} 2472 2473/// Get a string item from a dictionary 2474/// 2475/// @param[in] d Dictionary to get item from. 2476/// @param[in] key Dictionary key. 2477/// @param[in] key_len Key length. 2478/// @param[in] numbuf Buffer for non-string items converted to strings, at 2479/// least of #NUMBUFLEN length. 2480/// @param[in] def Default return when key does not exist. 2481/// 2482/// @return `def` when key does not exist, 2483/// NULL in case of type error, 2484/// string item value in case of success. 2485const char * tv_dict_get_string_buf_chk (const dict_T * const d ,const char * const key , 2486const ptrdiff_t key_len ,char * const numbuf , 2487const char * const def ) 2488FUNC_ATTR_WARN_UNUSED_RESULT 2489{ 2490const dictitem_T * const di = tv_dict_find (d ,key ,key_len ); 2491if (di == NULL ) { 2492return def ; 2493 } 2494return tv_get_string_buf_chk (& di -> di_tv ,numbuf ); 2495} 2496 2497/// Get a function from a dictionary 2498/// 2499/// @param[in] d Dictionary to get callback from. 2500/// @param[in] key Dictionary key. 2501/// @param[in] key_len Key length, may be -1 to use strlen(). 2502/// @param[out] result The address where a pointer to the wanted callback 2503/// will be left. 2504/// 2505/// @return true/false on success/failure. 2506bool tv_dict_get_callback (dict_T * const d ,const char * const key ,const ptrdiff_t key_len , 2507Callback * const result ) 2508FUNC_ATTR_NONNULL_ARG (2 ,4 )FUNC_ATTR_WARN_UNUSED_RESULT 2509{ 2510result -> type = kCallbackNone ; 2511 2512dictitem_T * const di = tv_dict_find (d ,key ,key_len ); 2513 2514if (di == NULL ) { 2515return true; 2516 } 2517 2518if (!tv_is_func (di -> di_tv )&& di -> di_tv .v_type != VAR_STRING ) { 2519emsg (_ ("E6000: Argument is not a function or function name" )); 2520return false; 2521 } 2522 2523typval_T tv ; 2524tv_copy (& di -> di_tv ,& tv ); 2525set_selfdict (& tv ,d ); 2526const bool res = callback_from_typval (result ,& tv ); 2527tv_clear (& tv ); 2528return res ; 2529} 2530 2531/// Check for adding a function to g: or l:. 2532/// If the name is wrong give an error message and return true. 2533int tv_dict_wrong_func_name (dict_T * d ,typval_T * tv ,const char * name ) 2534{ 2535return (d == get_globvar_dict ()|| & d -> dv_hashtab == get_funccal_local_ht ()) 2536&& tv_is_func (* tv ) 2537&& var_wrong_func_name (name , true); 2538} 2539 2540// dict_add*: 2541 2542/// Add item to dictionary 2543/// 2544/// @param[out] d Dictionary to add to. 2545/// @param[in] item Item to add. 2546/// 2547/// @return FAIL if key already exists. 2548int tv_dict_add (dict_T * const d ,dictitem_T * const item ) 2549FUNC_ATTR_NONNULL_ALL 2550{ 2551if (tv_dict_wrong_func_name (d ,& item -> di_tv ,item -> di_key )) { 2552return FAIL ; 2553 } 2554return hash_add (& d -> dv_hashtab ,item -> di_key ); 2555} 2556 2557/// Add a list entry to dictionary 2558/// 2559/// @param[out] d Dictionary to add entry to. 2560/// @param[in] key Key to add. 2561/// @param[in] key_len Key length. 2562/// @param list List to add. Will have reference count incremented. 2563/// 2564/// @return OK in case of success, FAIL when key already exists. 2565int tv_dict_add_list (dict_T * const d ,const char * const key ,const size_t key_len , 2566list_T * const list ) 2567FUNC_ATTR_NONNULL_ALL 2568{ 2569dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2570 2571item -> di_tv .v_type = VAR_LIST ; 2572item -> di_tv .vval .v_list = list ; 2573if (tv_dict_add (d ,item )== FAIL ) { 2574// Detach "list" so tv_dict_item_free() does not unref it: on failure 2575// ownership stays with the caller. 2576item -> di_tv .vval .v_list = NULL ; 2577tv_dict_item_free (item ); 2578return FAIL ; 2579 } 2580tv_list_ref (list ); 2581return OK ; 2582} 2583 2584/// Add a typval entry to dictionary. 2585/// 2586/// @param[out] d Dictionary to add entry to. 2587/// @param[in] key Key to add. 2588/// @param[in] key_len Key length. 2589/// 2590/// @return FAIL if out of memory or key already exists. 2591int tv_dict_add_tv (dict_T * d ,const char * key ,const size_t key_len ,typval_T * tv ) 2592{ 2593dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2594 2595tv_copy (tv ,& item -> di_tv ); 2596if (tv_dict_add (d ,item )== FAIL ) { 2597tv_dict_item_free (item ); 2598return FAIL ; 2599 } 2600return OK ; 2601} 2602 2603/// Add a dictionary entry to dictionary 2604/// 2605/// @param[out] d Dictionary to add entry to. 2606/// @param[in] key Key to add. 2607/// @param[in] key_len Key length. 2608/// @param dict Dictionary to add. Will have reference count incremented. 2609/// 2610/// @return OK in case of success, FAIL when key already exists. 2611int tv_dict_add_dict (dict_T * const d ,const char * const key ,const size_t key_len , 2612dict_T * const dict ) 2613FUNC_ATTR_NONNULL_ALL 2614{ 2615dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2616 2617item -> di_tv .v_type = VAR_DICT ; 2618item -> di_tv .vval .v_dict = dict ; 2619if (tv_dict_add (d ,item )== FAIL ) { 2620// Detach "dict" so tv_dict_item_free() does not unref it: on failure 2621// ownership stays with the caller. 2622item -> di_tv .vval .v_dict = NULL ; 2623tv_dict_item_free (item ); 2624return FAIL ; 2625 } 2626dict -> dv_refcount ++ ; 2627return OK ; 2628} 2629 2630/// Add a number entry to dictionary 2631/// 2632/// @param[out] d Dictionary to add entry to. 2633/// @param[in] key Key to add. 2634/// @param[in] key_len Key length. 2635/// @param[in] nr Number to add. 2636/// 2637/// @return OK in case of success, FAIL when key already exists. 2638int tv_dict_add_nr (dict_T * const d ,const char * const key ,const size_t key_len , 2639const varnumber_T nr ) 2640{ 2641dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2642 2643item -> di_tv .v_type = VAR_NUMBER ; 2644item -> di_tv .vval .v_number = nr ; 2645if (tv_dict_add (d ,item )== FAIL ) { 2646tv_dict_item_free (item ); 2647return FAIL ; 2648 } 2649return OK ; 2650} 2651 2652/// Add a floating point number entry to dictionary 2653/// 2654/// @param[out] d Dictionary to add entry to. 2655/// @param[in] key Key to add. 2656/// @param[in] key_len Key length. 2657/// @param[in] nr Floating point number to add. 2658/// 2659/// @return OK in case of success, FAIL when key already exists. 2660int tv_dict_add_float (dict_T * const d ,const char * const key ,const size_t key_len , 2661const float_T nr ) 2662{ 2663dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2664 2665item -> di_tv .v_type = VAR_FLOAT ; 2666item -> di_tv .vval .v_float = nr ; 2667if (tv_dict_add (d ,item )== FAIL ) { 2668tv_dict_item_free (item ); 2669return FAIL ; 2670 } 2671return OK ; 2672} 2673 2674/// Add a boolean entry to dictionary 2675/// 2676/// @param[out] d Dictionary to add entry to. 2677/// @param[in] key Key to add. 2678/// @param[in] key_len Key length. 2679/// @param[in] val BoolVarValue to add. 2680/// 2681/// @return OK in case of success, FAIL when key already exists. 2682int tv_dict_add_bool (dict_T * const d ,const char * const key ,const size_t key_len ,BoolVarValue val ) 2683{ 2684dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2685 2686item -> di_tv .v_type = VAR_BOOL ; 2687item -> di_tv .vval .v_bool = val ; 2688if (tv_dict_add (d ,item )== FAIL ) { 2689tv_dict_item_free (item ); 2690return FAIL ; 2691 } 2692return OK ; 2693} 2694 2695/// Add a string entry to dictionary 2696/// 2697/// @see tv_dict_add_allocated_str 2698int tv_dict_add_str (dict_T * const d ,const char * const key ,const size_t key_len , 2699const char * const val ) 2700FUNC_ATTR_NONNULL_ARG (1 ,2 ) 2701{ 2702return tv_dict_add_str_len (d ,key ,key_len ,val ,-1 ); 2703} 2704 2705/// Add a string entry to dictionary 2706/// 2707/// @param[out] d Dictionary to add entry to. 2708/// @param[in] key Key to add. 2709/// @param[in] key_len Key length. 2710/// @param[in] val String to add. NULL adds empty string. 2711/// @param[in] len Use this many bytes from `val`, or -1 for whole string. 2712/// 2713/// @return OK in case of success, FAIL when key already exists. 2714int tv_dict_add_str_len (dict_T * const d ,const char * const key ,const size_t key_len , 2715const char * const val ,int len ) 2716FUNC_ATTR_NONNULL_ARG (1 ,2 ) 2717{ 2718char * s = NULL ; 2719if (val != NULL ) { 2720s = (len < 0 ) ?xstrdup (val ) :xstrndup (val , (size_t )len ); 2721 } 2722return tv_dict_add_allocated_str (d ,key ,key_len ,s ); 2723} 2724 2725/// Add a string entry to dictionary 2726/// 2727/// Unlike tv_dict_add_str() saves val to the new dictionary item in place of 2728/// creating a new copy. 2729/// 2730/// @warning String will be freed even in case addition fails. 2731/// 2732/// @param[out] d Dictionary to add entry to. 2733/// @param[in] key Key to add. 2734/// @param[in] key_len Key length. 2735/// @param[in] val String to add. 2736/// 2737/// @return OK in case of success, FAIL when key already exists. 2738int tv_dict_add_allocated_str (dict_T * const d ,const char * const key ,const size_t key_len , 2739char * const val ) 2740FUNC_ATTR_NONNULL_ARG (1 ,2 ) 2741{ 2742dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2743 2744item -> di_tv .v_type = VAR_STRING ; 2745item -> di_tv .vval .v_string = val ; 2746if (tv_dict_add (d ,item )== FAIL ) { 2747tv_dict_item_free (item ); 2748return FAIL ; 2749 } 2750return OK ; 2751} 2752 2753/// Add a function entry to dictionary. 2754/// 2755/// @param[out] d Dictionary to add entry to. 2756/// @param[in] key Key to add. 2757/// @param[in] key_len Key length. 2758/// @param[in] fp Function to add. 2759/// 2760/// @return OK in case of success, FAIL when key already exists. 2761int tv_dict_add_func (dict_T * const d ,const char * const key ,const size_t key_len , 2762ufunc_T * const fp ) 2763FUNC_ATTR_NONNULL_ARG (1 ,2 ,4 ) 2764{ 2765dictitem_T * const item = tv_dict_item_alloc_len (key ,key_len ); 2766 2767item -> di_tv .v_type = VAR_FUNC ; 2768item -> di_tv .vval .v_string = xmemdupz (fp -> uf_name ,fp -> uf_namelen ); 2769// Reference before tv_dict_add() so tv_dict_item_free()'s unref stays balanced on failure. 2770func_ref (item -> di_tv .vval .v_string ); 2771if (tv_dict_add (d ,item )== FAIL ) { 2772tv_dict_item_free (item ); 2773return FAIL ; 2774 } 2775return OK ; 2776} 2777 2778// Operations on the whole dict: 2779 2780/// Clear all the keys of a Dictionary. "d" remains a valid empty Dictionary. 2781/// 2782/// @param d The Dictionary to clear 2783void tv_dict_clear (dict_T * const d ) 2784FUNC_ATTR_NONNULL_ALL 2785{ 2786hash_lock (& d -> dv_hashtab ); 2787assert (d -> dv_hashtab .ht_locked > 0 ); 2788 2789HASHTAB_ITER (& d -> dv_hashtab ,hi , { 2790tv_dict_item_free (TV_DICT_HI2DI (hi )); 2791hash_remove (& d -> dv_hashtab ,hi ); 2792 }); 2793 2794hash_unlock (& d -> dv_hashtab ); 2795} 2796 2797/// Extend dictionary with items from another dictionary 2798/// 2799/// @param d1 Dictionary to extend. 2800/// @param[in] d2 Dictionary to extend with. 2801/// @param[in] action "error", "force", "move", "keep": 2802/// e*, including "error": duplicate key gives an error. 2803/// f*, including "force": duplicate d2 keys override d1. 2804/// m*, including "move": move items instead of copying. 2805/// other, including "keep": duplicate d2 keys ignored. 2806void tv_dict_extend (dict_T * const d1 ,dict_T * const d2 ,const char * const action ) 2807FUNC_ATTR_NONNULL_ALL 2808{ 2809const bool watched = tv_dict_is_watched (d1 ); 2810const char * const arg_errmsg = _ ("extend() argument" ); 2811const size_t arg_errmsg_len = strlen (arg_errmsg ); 2812 2813if (* action == 'm' ) { 2814hash_lock (& d2 -> dv_hashtab );// don't rehash on hash_remove() 2815 } 2816 2817HASHTAB_ITER (& d2 -> dv_hashtab ,hi2 , { 2818dictitem_T * const di2 = TV_DICT_HI2DI (hi2 ); 2819dictitem_T * const di1 = tv_dict_find (d1 ,di2 -> di_key ,-1 ); 2820// Check the key to be valid when adding to any scope. 2821if (d1 -> dv_scope != VAR_NO_SCOPE && !valid_varname (di2 -> di_key )) { 2822break ; 2823 } 2824if (di1 == NULL ) { 2825if (* action == 'm' ) { 2826// Cheap way to move a dict item from "d2" to "d1". 2827// If dict_add() fails then "d2" won't be empty. 2828dictitem_T * const new_di = di2 ; 2829if (tv_dict_add (d1 ,new_di )== OK ) { 2830hash_remove (& d2 -> dv_hashtab ,hi2 ); 2831tv_dict_watcher_notify (d1 ,new_di -> di_key ,& new_di -> di_tv ,NULL ); 2832 } 2833 }else { 2834dictitem_T * const new_di = tv_dict_item_copy (di2 ); 2835if (tv_dict_add (d1 ,new_di )== FAIL ) { 2836tv_dict_item_free (new_di ); 2837 }else if (watched ) { 2838tv_dict_watcher_notify (d1 ,new_di -> di_key ,& new_di -> di_tv ,NULL ); 2839 } 2840 } 2841 }else if (* action == 'e' ) { 2842semsg (_ ("E737: Key already exists: %s" ),di2 -> di_key ); 2843break ; 2844 }else if (* action == 'f' && di2 != di1 ) { 2845typval_T oldtv ; 2846 2847if (value_check_lock (di1 -> di_tv .v_lock ,arg_errmsg ,arg_errmsg_len ) 2848|| var_check_ro (di1 -> di_flags ,arg_errmsg ,arg_errmsg_len )) { 2849break ; 2850 } 2851// Disallow replacing a builtin function. 2852if (tv_dict_wrong_func_name (d1 ,& di2 -> di_tv ,di2 -> di_key )) { 2853break ; 2854 } 2855 2856if (watched ) { 2857tv_copy (& di1 -> di_tv ,& oldtv ); 2858 } 2859 2860tv_clear (& di1 -> di_tv ); 2861tv_copy (& di2 -> di_tv ,& di1 -> di_tv ); 2862 2863if (watched ) { 2864tv_dict_watcher_notify (d1 ,di1 -> di_key ,& di1 -> di_tv ,& oldtv ); 2865tv_clear (& oldtv ); 2866 } 2867 } 2868 }); 2869 2870if (* action == 'm' ) { 2871hash_unlock (& d2 -> dv_hashtab ); 2872 } 2873} 2874 2875/// Compare two dictionaries 2876/// 2877/// @param[in] d1 First dictionary. 2878/// @param[in] d2 Second dictionary. 2879/// @param[in] ic True if case is to be ignored. 2880/// 2881/// @return True if dictionaries are equal, false otherwise. 2882bool tv_dict_equal (dict_T * const d1 ,dict_T * const d2 ,const bool ic ) 2883FUNC_ATTR_WARN_UNUSED_RESULT 2884{ 2885if (d1 == d2 ) { 2886return true; 2887 } 2888if (tv_dict_len (d1 )!= tv_dict_len (d2 )) { 2889return false; 2890 } 2891if (tv_dict_len (d1 )== 0 ) { 2892// empty and NULL dicts are considered equal 2893return true; 2894 } 2895if (d1 == NULL || d2 == NULL ) { 2896return false; 2897 } 2898 2899TV_DICT_ITER (d1 ,di1 , { 2900dictitem_T * const di2 = tv_dict_find (d2 ,di1 -> di_key ,-1 ); 2901if (di2 == NULL ) { 2902return false; 2903 } 2904if (!tv_equal (& di1 -> di_tv ,& di2 -> di_tv ,ic )) { 2905return false; 2906 } 2907 }); 2908return true; 2909} 2910 2911/// Make a copy of dictionary 2912/// 2913/// @param[in] conv If non-NULL, then all internal strings will be converted. 2914/// @param[in] orig Original dictionary to copy. 2915/// @param[in] deep If false, then shallow copy will be done. 2916/// @param[in] copyID See var_item_copy(). 2917/// 2918/// @return Copied dictionary. May be NULL in case original dictionary is NULL 2919/// or some failure happens. The refcount of the new dictionary is set 2920/// to 1. 2921dict_T * tv_dict_copy (const vimconv_T * const conv ,dict_T * const orig ,const bool deep , 2922const int copyID ) 2923{ 2924if (orig == NULL ) { 2925return NULL ; 2926 } 2927 2928dict_T * copy = tv_dict_alloc (); 2929if (copyID != 0 ) { 2930orig -> dv_copyID = copyID ; 2931orig -> dv_copydict = copy ; 2932 } 2933TV_DICT_ITER (orig ,di , { 2934if (got_int ) { 2935break ; 2936 } 2937dictitem_T * new_di ; 2938if (conv == NULL || conv -> vc_type == CONV_NONE ) { 2939new_di = tv_dict_item_alloc (di -> di_key ); 2940 }else { 2941size_t len = strlen (di -> di_key ); 2942char * const key = string_convert (conv ,di -> di_key ,& len ); 2943if (key == NULL ) { 2944new_di = tv_dict_item_alloc_len (di -> di_key ,len ); 2945 }else { 2946new_di = tv_dict_item_alloc_len (key ,len ); 2947xfree (key ); 2948 } 2949 } 2950if (deep ) { 2951if (var_item_copy (conv ,& di -> di_tv ,& new_di -> di_tv ,deep , 2952copyID )== FAIL ) { 2953xfree (new_di ); 2954break ; 2955 } 2956 }else { 2957tv_copy (& di -> di_tv ,& new_di -> di_tv ); 2958 } 2959if (tv_dict_add (copy ,new_di )== FAIL ) { 2960tv_dict_item_free (new_di ); 2961break ; 2962 } 2963 }); 2964 2965copy -> dv_refcount ++ ; 2966if (got_int ) { 2967tv_dict_unref (copy ); 2968copy = NULL ; 2969 } 2970 2971return copy ; 2972} 2973 2974/// Set all existing keys in "dict" as read-only. 2975/// 2976/// This does not protect against adding new keys to the Dictionary. 2977/// 2978/// @param dict The dict whose keys should be frozen. 2979void tv_dict_set_keys_readonly (dict_T * const dict ) 2980FUNC_ATTR_NONNULL_ALL 2981{ 2982TV_DICT_ITER (dict ,di , { 2983di -> di_flags |=DI_FLAGS_RO |DI_FLAGS_FIX ; 2984 }); 2985} 2986 2987// Blobs: 2988// Alloc/free: 2989 2990/// Allocate an empty blob. 2991/// 2992/// Caller should take care of the reference count. 2993/// 2994/// @return [allocated] new blob. 2995blob_T * tv_blob_alloc (void ) 2996FUNC_ATTR_NONNULL_RET 2997{ 2998blob_T * const blob = xcalloc (1 ,sizeof (blob_T )); 2999ga_init (& blob -> bv_ga ,1 ,100 ); 3000return blob ; 3001} 3002 3003/// Free a blob. Ignores the reference count. 3004/// 3005/// @param[in,out] b Blob to free. 3006void tv_blob_free (blob_T * const b ) 3007FUNC_ATTR_NONNULL_ALL 3008{ 3009ga_clear (& b -> bv_ga ); 3010xfree (b ); 3011} 3012 3013/// Unreference a blob. 3014/// 3015/// Decrements the reference count and frees blob when it becomes zero. 3016/// 3017/// @param[in,out] b Blob to operate on. 3018void tv_blob_unref (blob_T * const b ) 3019{ 3020if (b != NULL && -- b -> bv_refcount <=0 ) { 3021tv_blob_free (b ); 3022 } 3023} 3024 3025// Operations on the whole blob: 3026 3027/// Check whether two blobs are equal. 3028/// 3029/// @param[in] b1 First blob. 3030/// @param[in] b2 Second blob. 3031/// 3032/// @return true if blobs are equal, false otherwise. 3033bool tv_blob_equal (const blob_T * const b1 ,const blob_T * const b2 ) 3034FUNC_ATTR_WARN_UNUSED_RESULT 3035{ 3036const int len1 = tv_blob_len (b1 ); 3037const int len2 = tv_blob_len (b2 ); 3038 3039// empty and NULL are considered the same 3040if (len1 == 0 && len2 == 0 ) { 3041return true; 3042 } 3043if (b1 == b2 ) { 3044return true; 3045 } 3046if (len1 != len2 ) { 3047return false; 3048 } 3049 3050for (int i = 0 ;i < b1 -> bv_ga .ga_len ;i ++ ) { 3051if (tv_blob_get (b1 ,i )!= tv_blob_get (b2 ,i )) { 3052return false; 3053 } 3054 } 3055return true; 3056} 3057 3058/// Returns a slice of "blob" from index "n1" to "n2" in "rettv". The length of 3059/// the blob is "len". Returns an empty blob if the indexes are out of range. 3060static int tv_blob_slice (const blob_T * blob ,int len ,varnumber_T n1 ,varnumber_T n2 , 3061bool exclusive ,typval_T * rettv ) 3062{ 3063// The resulting variable is a sub-blob. If the indexes 3064// are out of range the result is empty. 3065if (n1 < 0 ) { 3066n1 = len + n1 ; 3067if (n1 < 0 ) { 3068n1 = 0 ; 3069 } 3070 } 3071if (n2 < 0 ) { 3072n2 = len + n2 ; 3073 }else if (n2 >=len ) { 3074n2 = len - (exclusive ?0 :1 ); 3075 } 3076if (exclusive ) { 3077n2 -- ; 3078 } 3079if (n1 >=len || n2 < 0 || n1 > n2 ) { 3080tv_clear (rettv ); 3081rettv -> v_type = VAR_BLOB ; 3082rettv -> vval .v_blob = NULL ; 3083 }else { 3084blob_T * const new_blob = tv_blob_alloc (); 3085ga_grow (& new_blob -> bv_ga , (int )(n2 - n1 + 1 )); 3086new_blob -> bv_ga .ga_len = (int )(n2 - n1 + 1 ); 3087for (int i = (int )n1 ;i <= (int )n2 ;i ++ ) { 3088tv_blob_set (new_blob ,i - (int )n1 ,tv_blob_get (rettv -> vval .v_blob ,i )); 3089 } 3090tv_clear (rettv ); 3091tv_blob_set_ret (rettv ,new_blob ); 3092 } 3093 3094return OK ; 3095} 3096 3097/// Return the byte value in "blob" at index "idx" in "rettv". If the index is 3098/// too big or negative that is an error. The length of the blob is "len". 3099static int tv_blob_index (const blob_T * blob ,int len ,varnumber_T idx ,typval_T * rettv ) 3100{ 3101// The resulting variable is a byte value. 3102// If the index is too big or negative that is an error. 3103if (idx < 0 ) { 3104idx = len + idx ; 3105 } 3106if (idx < len && idx >=0 ) { 3107const int v = (int )tv_blob_get (rettv -> vval .v_blob , (int )idx ); 3108tv_clear (rettv ); 3109rettv -> v_type = VAR_NUMBER ; 3110rettv -> vval .v_number = v ; 3111 }else { 3112semsg (_ (e_blobidx ),idx ); 3113return FAIL ; 3114 } 3115 3116return OK ; 3117} 3118 3119int tv_blob_slice_or_index (const blob_T * blob ,bool is_range ,varnumber_T n1 ,varnumber_T n2 , 3120bool exclusive ,typval_T * rettv ) 3121{ 3122int len = tv_blob_len (rettv -> vval .v_blob ); 3123 3124if (is_range ) { 3125return tv_blob_slice (blob ,len ,n1 ,n2 ,exclusive ,rettv ); 3126 }else { 3127return tv_blob_index (blob ,len ,n1 ,rettv ); 3128 } 3129} 3130 3131/// Check if "n1" is a valid index for a blob with length "bloblen". 3132int tv_blob_check_index (int bloblen ,varnumber_T n1 ,bool quiet ) 3133{ 3134if (n1 < 0 || n1 > bloblen ) { 3135if (!quiet ) { 3136semsg (_ (e_blobidx ),n1 ); 3137 } 3138return FAIL ; 3139 } 3140return OK ; 3141} 3142 3143/// Check if "n1"-"n2" is a valid range for a blob with length "bloblen". 3144int tv_blob_check_range (int bloblen ,varnumber_T n1 ,varnumber_T n2 ,bool quiet ) 3145{ 3146if (n2 < 0 || n2 >=bloblen || n2 < n1 ) { 3147if (!quiet ) { 3148semsg (_ (e_blobidx ),n2 ); 3149 } 3150return FAIL ; 3151 } 3152return OK ; 3153} 3154 3155/// Set bytes "n1" to "n2" (inclusive) in "dest" to the value of "src". 3156/// Caller must make sure "src" is a blob. 3157/// Returns FAIL if the number of bytes does not match. 3158int tv_blob_set_range (blob_T * dest ,varnumber_T n1 ,varnumber_T n2 ,typval_T * src ) 3159{ 3160if (n2 - n1 + 1 != tv_blob_len (src -> vval .v_blob )) { 3161emsg (_ ("E972: Blob value does not have the right number of bytes" )); 3162return FAIL ; 3163 } 3164 3165for (int il = (int )n1 ,ir = 0 ;il <= (int )n2 ;il ++ ) { 3166tv_blob_set (dest ,il ,tv_blob_get (src -> vval .v_blob ,ir ++ )); 3167 } 3168return OK ; 3169} 3170 3171/// Store one byte "byte" in blob "blob" at "idx". 3172/// Append one byte if needed. 3173void tv_blob_set_append (blob_T * blob ,int idx ,uint8_t byte ) 3174{ 3175garray_T * gap = & blob -> bv_ga ; 3176 3177// Allow for appending a byte. Setting a byte beyond 3178// the end is an error otherwise. 3179if (idx <=gap -> ga_len ) { 3180if (idx == gap -> ga_len ) { 3181ga_grow (gap ,1 ); 3182gap -> ga_len ++ ; 3183 } 3184tv_blob_set (blob ,idx ,byte ); 3185 } 3186} 3187 3188/// "remove({blob})" function 3189void tv_blob_remove (typval_T * argvars ,typval_T * rettv ,const char * arg_errmsg ) 3190{ 3191blob_T * const b = argvars [0 ].vval .v_blob ; 3192 3193if (b != NULL && value_check_lock (b -> bv_lock ,arg_errmsg ,TV_TRANSLATE )) { 3194return ; 3195 } 3196 3197bool error = false; 3198int64_t idx = tv_get_number_chk (& argvars [1 ],& error ); 3199 3200if (!error ) { 3201const int len = tv_blob_len (b ); 3202 3203if (idx < 0 ) { 3204// count from the end 3205idx = len + idx ; 3206 } 3207if (idx < 0 || idx >=len ) { 3208semsg (_ (e_blobidx ),idx ); 3209return ; 3210 } 3211if (argvars [2 ].v_type == VAR_UNKNOWN ) { 3212// Remove one item, return its value. 3213uint8_t * const p = (uint8_t * )b -> bv_ga .ga_data ; 3214rettv -> vval .v_number = (varnumber_T )(* (p + idx )); 3215memmove (p + idx ,p + idx + 1 , (size_t )(len - idx - 1 )); 3216b -> bv_ga .ga_len -- ; 3217 }else { 3218// Remove range of items, return blob with values. 3219int64_t end = tv_get_number_chk (& argvars [2 ],& error ); 3220if (error ) { 3221return ; 3222 } 3223if (end < 0 ) { 3224// count from the end 3225end = len + end ; 3226 } 3227if (end >=len || idx > end ) { 3228semsg (_ (e_blobidx ),end ); 3229return ; 3230 } 3231blob_T * const blob = tv_blob_alloc (); 3232blob -> bv_ga .ga_len = (int )(end - idx + 1 ); 3233ga_grow (& blob -> bv_ga , (int )(end - idx + 1 )); 3234 3235uint8_t * const p = (uint8_t * )b -> bv_ga .ga_data ; 3236memmove (blob -> bv_ga .ga_data ,p + idx , (size_t )(end - idx + 1 )); 3237tv_blob_set_ret (rettv ,blob ); 3238 3239if (len - end - 1 > 0 ) { 3240memmove (p + idx ,p + end + 1 , (size_t )(len - end - 1 )); 3241 } 3242b -> bv_ga .ga_len -= (int )(end - idx + 1 ); 3243 } 3244 } 3245} 3246 3247/// blob2list() function 3248void f_blob2list (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3249{ 3250tv_list_alloc_ret (rettv ,kListLenMayKnow ); 3251 3252if (tv_check_for_blob_arg (argvars ,0 )== FAIL ) { 3253return ; 3254 } 3255 3256blob_T * const blob = argvars -> vval .v_blob ; 3257list_T * const l = rettv -> vval .v_list ; 3258for (int i = 0 ;i < tv_blob_len (blob );i ++ ) { 3259tv_list_append_number (l ,tv_blob_get (blob ,i )); 3260 } 3261} 3262 3263/// list2blob() function 3264void f_list2blob (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3265{ 3266blob_T * blob = tv_blob_alloc_ret (rettv ); 3267 3268if (tv_check_for_list_arg (argvars ,0 )== FAIL ) { 3269return ; 3270 } 3271 3272list_T * const l = argvars -> vval .v_list ; 3273if (l == NULL ) { 3274return ; 3275 } 3276 3277ga_grow (& blob -> bv_ga ,tv_list_len (l )); 3278 3279TV_LIST_ITER_CONST (l ,li , { 3280bool error = false; 3281varnumber_T n = tv_get_number_chk (TV_LIST_ITEM_TV (li ),& error ); 3282if (error || n < 0 || n > 255 ) { 3283if (!error ) { 3284semsg (_ (e_invalid_value_for_blob_nr ), (int )n ); 3285 } 3286ga_clear (& blob -> bv_ga ); 3287return ; 3288 } 3289 ((uint8_t * )blob -> bv_ga .ga_data )[blob -> bv_ga .ga_len ++ ]= (uint8_t )n ; 3290 }); 3291} 3292 3293// Generic typval operations: 3294// Init/alloc/clear: 3295// Alloc: 3296 3297/// Allocate an empty list for a return value 3298/// 3299/// Also sets reference count. 3300/// 3301/// @param[out] ret_tv Structure where list is saved. 3302/// @param[in] len Expected number of items to be populated before list 3303/// becomes accessible from Vimscript. It is still valid to 3304/// underpopulate a list, value only controls how many elements 3305/// will be allocated in advance. @see ListLenSpecials. 3306/// 3307/// @return [allocated] pointer to the created list. 3308list_T * tv_list_alloc_ret (typval_T * const ret_tv ,const ptrdiff_t len ) 3309FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 3310{ 3311list_T * const l = tv_list_alloc (len ); 3312tv_list_set_ret (ret_tv ,l ); 3313ret_tv -> v_lock = VAR_UNLOCKED ; 3314return l ; 3315} 3316 3317dict_T * tv_dict_alloc_lock (VarLockStatus lock ) 3318FUNC_ATTR_NONNULL_RET 3319{ 3320dict_T * const d = tv_dict_alloc (); 3321d -> dv_lock = lock ; 3322return d ; 3323} 3324 3325/// Allocate an empty dictionary for a return value 3326/// 3327/// Also sets reference count. 3328/// 3329/// @param[out] ret_tv Structure where dictionary is saved. 3330void tv_dict_alloc_ret (typval_T * const ret_tv ) 3331FUNC_ATTR_NONNULL_ALL 3332{ 3333dict_T * const d = tv_dict_alloc_lock (VAR_UNLOCKED ); 3334tv_dict_set_ret (ret_tv ,d ); 3335} 3336 3337/// Turn a dictionary into a list 3338/// 3339/// @param[in] argvars Arguments to items(). The first argument is check for being 3340/// a dictionary, will give an error if not. 3341/// @param[out] rettv Location where result will be saved. 3342/// @param[in] what What to save in rettv. 3343static void tv_dict2list (typval_T * const argvars ,typval_T * const rettv ,const DictListType what ) 3344{ 3345if (tv_check_for_dict_arg (argvars ,0 )== FAIL ) { 3346tv_list_alloc_ret (rettv ,0 ); 3347return ; 3348 } 3349 3350dict_T * d = argvars [0 ].vval .v_dict ; 3351tv_list_alloc_ret (rettv ,tv_dict_len (d )); 3352if (d == NULL ) { 3353// NULL dict behaves like an empty dict 3354return ; 3355 } 3356 3357TV_DICT_ITER (d ,di , { 3358typval_T tv_item = { .v_lock = VAR_UNLOCKED }; 3359 3360switch (what ) { 3361case kDict2ListKeys : 3362tv_item .v_type = VAR_STRING ; 3363tv_item .vval .v_string = xstrdup (di -> di_key ); 3364break ; 3365case kDict2ListValues : 3366tv_copy (& di -> di_tv ,& tv_item ); 3367break ; 3368case kDict2ListItems : { 3369// items() 3370list_T * const sub_l = tv_list_alloc (2 ); 3371tv_item .v_type = VAR_LIST ; 3372tv_item .vval .v_list = sub_l ; 3373tv_list_ref (sub_l ); 3374tv_list_append_string (sub_l ,di -> di_key ,-1 ); 3375tv_list_append_tv (sub_l ,& di -> di_tv ); 3376break ; 3377 } 3378 } 3379 3380tv_list_append_owned_tv (rettv -> vval .v_list ,tv_item ); 3381 }); 3382} 3383 3384/// "items()" function 3385void f_items (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3386{ 3387if (argvars [0 ].v_type == VAR_STRING ) { 3388tv_string2items (argvars ,rettv ); 3389 }else if (argvars [0 ].v_type == VAR_LIST ) { 3390tv_list2items (argvars ,rettv ); 3391 }else if (argvars [0 ].v_type == VAR_BLOB ) { 3392tv_blob2items (argvars ,rettv ); 3393 }else if (argvars [0 ].v_type == VAR_DICT ) { 3394tv_dict2items (argvars ,rettv ); 3395 }else { 3396semsg (_ (e_list_dict_blob_or_string_required_for_argument_nr ),1 ); 3397 } 3398} 3399 3400/// "keys()" function 3401void f_keys (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3402{ 3403tv_dict2list (argvars ,rettv ,kDict2ListKeys ); 3404} 3405 3406/// "values(dict)" function 3407void f_values (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3408{ 3409tv_dict2list (argvars ,rettv ,kDict2ListValues ); 3410} 3411 3412/// "has_key()" function 3413void f_has_key (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3414{ 3415if (tv_check_for_dict_arg (argvars ,0 )== FAIL ) { 3416return ; 3417 } 3418 3419if (argvars [0 ].vval .v_dict == NULL ) { 3420return ; 3421 } 3422 3423rettv -> vval .v_number = tv_dict_find (argvars [0 ].vval .v_dict , 3424tv_get_string (& argvars [1 ]), 3425-1 )!= NULL ; 3426} 3427 3428/// "remove({dict})" function 3429void tv_dict_remove (typval_T * argvars ,typval_T * rettv ,const char * arg_errmsg ) 3430{ 3431dict_T * d ; 3432if (argvars [2 ].v_type != VAR_UNKNOWN ) { 3433semsg (_ (e_toomanyarg ),"remove()" ); 3434 }else if ((d = argvars [0 ].vval .v_dict )!= NULL 3435&& !value_check_lock (d -> dv_lock ,arg_errmsg ,TV_TRANSLATE )) { 3436const char * key = tv_get_string_chk (& argvars [1 ]); 3437if (key != NULL ) { 3438dictitem_T * di = tv_dict_find (d ,key ,-1 ); 3439if (di == NULL ) { 3440semsg (_ (e_dictkey ),key ); 3441 }else if (!var_check_fixed (di -> di_flags ,arg_errmsg ,TV_TRANSLATE ) 3442&& !var_check_ro (di -> di_flags ,arg_errmsg ,TV_TRANSLATE )) { 3443* rettv = di -> di_tv ; 3444di -> di_tv = TV_INITIAL_VALUE ; 3445tv_dict_item_remove (d ,di ); 3446if (tv_dict_is_watched (d )) { 3447tv_dict_watcher_notify (d ,key ,NULL ,rettv ); 3448 } 3449 } 3450 } 3451 } 3452} 3453 3454/// Allocate an empty blob for a return value. 3455/// 3456/// Also sets reference count. 3457/// 3458/// @param[out] ret_tv Structure where blob is saved. 3459blob_T * tv_blob_alloc_ret (typval_T * const ret_tv ) 3460FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 3461{ 3462blob_T * const b = tv_blob_alloc (); 3463tv_blob_set_ret (ret_tv ,b ); 3464return b ; 3465} 3466 3467/// Copy a blob typval to a different typval. 3468/// 3469/// @param[in] from Blob object to copy from. 3470/// @param[out] to Blob object to copy to. 3471void tv_blob_copy (blob_T * const from ,typval_T * const to ) 3472FUNC_ATTR_NONNULL_ARG (2 ) 3473{ 3474to -> v_type = VAR_BLOB ; 3475to -> v_lock = VAR_UNLOCKED ; 3476if (from == NULL ) { 3477to -> vval .v_blob = NULL ; 3478 }else { 3479tv_blob_alloc_ret (to ); 3480int len = from -> bv_ga .ga_len ; 3481 3482if (len > 0 ) { 3483to -> vval .v_blob -> bv_ga .ga_data = xmemdup (from -> bv_ga .ga_data , (size_t )len ); 3484 } 3485to -> vval .v_blob -> bv_ga .ga_len = len ; 3486to -> vval .v_blob -> bv_ga .ga_maxlen = len ; 3487 } 3488} 3489 3490// Clear: 3491#define TYPVAL_ENCODE_ALLOW_SPECIALS false 3492#define TYPVAL_ENCODE_CHECK_BEFORE 3493 3494#define TYPVAL_ENCODE_CONV_NIL (tv ) \ 3495 do { \ 3496 (tv)->vval.v_special = kSpecialVarNull; \ 3497 (tv)->v_lock = VAR_UNLOCKED; \ 3498 } while (0) 3499 3500#define TYPVAL_ENCODE_CONV_BOOL (tv ,num ) \ 3501 do { \ 3502 (tv)->vval.v_bool = kBoolVarFalse; \ 3503 (tv)->v_lock = VAR_UNLOCKED; \ 3504 } while (0) 3505 3506#define TYPVAL_ENCODE_CONV_NUMBER (tv ,num ) \ 3507 do { \ 3508 (void)(num); \ 3509 (tv)->vval.v_number = 0; \ 3510 (tv)->v_lock = VAR_UNLOCKED; \ 3511 } while (0) 3512 3513#define TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER (tv ,num ) 3514 3515#define TYPVAL_ENCODE_CONV_FLOAT (tv ,flt ) \ 3516 do { \ 3517 (tv)->vval.v_float = 0; \ 3518 (tv)->v_lock = VAR_UNLOCKED; \ 3519 } while (0) 3520 3521#define TYPVAL_ENCODE_CONV_STRING (tv ,buf ,len ) \ 3522 do { \ 3523 xfree(buf); \ 3524 (tv)->vval.v_string = NULL; \ 3525 (tv)->v_lock = VAR_UNLOCKED; \ 3526 } while (0) 3527 3528#define TYPVAL_ENCODE_CONV_STR_STRING (tv ,buf ,len ) 3529 3530#define TYPVAL_ENCODE_CONV_EXT_STRING (tv ,buf ,len ,type ) 3531 3532#define TYPVAL_ENCODE_CONV_BLOB (tv ,blob ,len ) \ 3533 do { \ 3534 tv_blob_unref((tv)->vval.v_blob); \ 3535 (tv)->vval.v_blob = NULL; \ 3536 (tv)->v_lock = VAR_UNLOCKED; \ 3537 } while (0) 3538 3539static inline int _nothing_conv_func_start (typval_T * const tv ,char * const fun ) 3540FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ARG (1 ) 3541{ 3542tv -> v_lock = VAR_UNLOCKED ; 3543if (tv -> v_type == VAR_PARTIAL ) { 3544partial_T * const pt_ = tv -> vval .v_partial ; 3545if (pt_ != NULL && pt_ -> pt_refcount > 1 ) { 3546pt_ -> pt_refcount -- ; 3547tv -> vval .v_partial = NULL ; 3548return OK ; 3549 } 3550 }else { 3551func_unref (fun ); 3552if (fun != tv_empty_string ) { 3553xfree (fun ); 3554 } 3555tv -> vval .v_string = NULL ; 3556 } 3557return NOTDONE ; 3558} 3559#define TYPVAL_ENCODE_CONV_FUNC_START (tv ,fun ,prefix ) \ 3560 do { \ 3561 if (_nothing_conv_func_start(tv, fun) != NOTDONE) { \ 3562 return OK; \ 3563 } \ 3564 } while (0) 3565 3566#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS (tv ,len ) 3567#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF (tv ,len ) 3568 3569static inline void _nothing_conv_func_end (typval_T * const tv ,const int copyID ) 3570FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL 3571{ 3572if (tv -> v_type == VAR_PARTIAL ) { 3573partial_T * const pt = tv -> vval .v_partial ; 3574if (pt == NULL ) { 3575return ; 3576 } 3577// Dictionary should already be freed by the time. 3578// If it was not freed then it is a part of the reference cycle. 3579assert (pt -> pt_dict == NULL || pt -> pt_dict -> dv_copyID == copyID ); 3580pt -> pt_dict = NULL ; 3581// As well as all arguments. 3582pt -> pt_argc = 0 ; 3583assert (pt -> pt_refcount <=1 ); 3584partial_unref (pt ); 3585tv -> vval .v_partial = NULL ; 3586assert (tv -> v_lock == VAR_UNLOCKED ); 3587 } 3588} 3589#define TYPVAL_ENCODE_CONV_FUNC_END (tv ) _nothing_conv_func_end(tv, copyID) 3590 3591#define TYPVAL_ENCODE_CONV_EMPTY_LIST (tv ) \ 3592 do { \ 3593 tv_list_unref((tv)->vval.v_list); \ 3594 (tv)->vval.v_list = NULL; \ 3595 (tv)->v_lock = VAR_UNLOCKED; \ 3596 } while (0) 3597 3598static inline void _nothing_conv_empty_dict (typval_T * const tv ,dict_T ** const dictp ) 3599FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ARG (2 ) 3600{ 3601tv_dict_unref (* dictp ); 3602* dictp = NULL ; 3603if (tv != NULL ) { 3604tv -> v_lock = VAR_UNLOCKED ; 3605 } 3606} 3607#define TYPVAL_ENCODE_CONV_EMPTY_DICT (tv ,dict ) \ 3608 do { \ 3609 assert((void *)&(dict) != (void *)&TYPVAL_ENCODE_NODICT_VAR); \ 3610 _nothing_conv_empty_dict(tv, ((dict_T **)&(dict))); \ 3611 } while (0) 3612 3613static inline int _nothing_conv_real_list_after_start (typval_T * const tv , 3614MPConvStackVal * const mpsv ) 3615FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_WARN_UNUSED_RESULT 3616{ 3617assert (tv != NULL ); 3618tv -> v_lock = VAR_UNLOCKED ; 3619if (tv -> vval .v_list -> lv_refcount > 1 ) { 3620tv -> vval .v_list -> lv_refcount -- ; 3621tv -> vval .v_list = NULL ; 3622mpsv -> data .l .li = NULL ; 3623return OK ; 3624 } 3625return NOTDONE ; 3626} 3627#define TYPVAL_ENCODE_CONV_LIST_START (tv ,len ) 3628 3629#define TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START (tv ,mpsv ) \ 3630 do { \ 3631 if (_nothing_conv_real_list_after_start(tv, &(mpsv)) != NOTDONE) { \ 3632 goto typval_encode_stop_converting_one_item; \ 3633 } \ 3634 } while (0) 3635 3636#define TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS (tv ) 3637 3638static inline void _nothing_conv_list_end (typval_T * const tv ) 3639FUNC_ATTR_ALWAYS_INLINE 3640{ 3641if (tv == NULL ) { 3642return ; 3643 } 3644assert (tv -> v_type == VAR_LIST ); 3645list_T * const list = tv -> vval .v_list ; 3646tv_list_unref (list ); 3647tv -> vval .v_list = NULL ; 3648} 3649#define TYPVAL_ENCODE_CONV_LIST_END (tv ) _nothing_conv_list_end(tv) 3650 3651static inline int _nothing_conv_real_dict_after_start (typval_T * const tv ,dict_T ** const dictp , 3652const void * const nodictvar , 3653MPConvStackVal * const mpsv ) 3654FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_WARN_UNUSED_RESULT 3655{ 3656if (tv != NULL ) { 3657tv -> v_lock = VAR_UNLOCKED ; 3658 } 3659if ((const void * )dictp != nodictvar && (* dictp )-> dv_refcount > 1 ) { 3660 (* dictp )-> dv_refcount -- ; 3661* dictp = NULL ; 3662mpsv -> data .d .todo = 0 ; 3663return OK ; 3664 } 3665return NOTDONE ; 3666} 3667#define TYPVAL_ENCODE_CONV_DICT_START (tv ,dict ,len ) 3668 3669#define TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START (tv ,dict ,mpsv ) \ 3670 do { \ 3671 if (_nothing_conv_real_dict_after_start(tv, (dict_T **)&(dict), \ 3672 (void *)&TYPVAL_ENCODE_NODICT_VAR, &(mpsv)) \ 3673 != NOTDONE) { \ 3674 goto typval_encode_stop_converting_one_item; \ 3675 } \ 3676 } while (0) 3677 3678#define TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK (tv ,dict ) 3679#define TYPVAL_ENCODE_CONV_DICT_AFTER_KEY (tv ,dict ) 3680#define TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS (tv ,dict ) 3681 3682static inline void _nothing_conv_dict_end (typval_T * const tv ,dict_T ** const dictp , 3683const void * const nodictvar ) 3684FUNC_ATTR_ALWAYS_INLINE 3685{ 3686if ((const void * )dictp != nodictvar ) { 3687tv_dict_unref (* dictp ); 3688* dictp = NULL ; 3689 } 3690} 3691#define TYPVAL_ENCODE_CONV_DICT_END (tv ,dict ) \ 3692 _nothing_conv_dict_end(tv, (dict_T **)&(dict), \ 3693 (void *)&TYPVAL_ENCODE_NODICT_VAR) 3694 3695#define TYPVAL_ENCODE_CONV_RECURSE (val ,conv_type ) 3696 3697#define TYPVAL_ENCODE_SCOPE static 3698#define TYPVAL_ENCODE_NAME nothing 3699#define TYPVAL_ENCODE_FIRST_ARG_TYPE const void *const 3700#define TYPVAL_ENCODE_FIRST_ARG_NAME ignored 3701#include "nvim/eval/typval_encode.c.h" 3702 3703#undef TYPVAL_ENCODE_SCOPE 3704#undef TYPVAL_ENCODE_NAME 3705#undef TYPVAL_ENCODE_FIRST_ARG_TYPE 3706#undef TYPVAL_ENCODE_FIRST_ARG_NAME 3707 3708#undef TYPVAL_ENCODE_ALLOW_SPECIALS 3709#undef TYPVAL_ENCODE_CHECK_BEFORE 3710#undef TYPVAL_ENCODE_CONV_NIL 3711#undef TYPVAL_ENCODE_CONV_BOOL 3712#undef TYPVAL_ENCODE_CONV_NUMBER 3713#undef TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER 3714#undef TYPVAL_ENCODE_CONV_FLOAT 3715#undef TYPVAL_ENCODE_CONV_STRING 3716#undef TYPVAL_ENCODE_CONV_STR_STRING 3717#undef TYPVAL_ENCODE_CONV_EXT_STRING 3718#undef TYPVAL_ENCODE_CONV_BLOB 3719#undef TYPVAL_ENCODE_CONV_FUNC_START 3720#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS 3721#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF 3722#undef TYPVAL_ENCODE_CONV_FUNC_END 3723#undef TYPVAL_ENCODE_CONV_EMPTY_LIST 3724#undef TYPVAL_ENCODE_CONV_EMPTY_DICT 3725#undef TYPVAL_ENCODE_CONV_LIST_START 3726#undef TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START 3727#undef TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS 3728#undef TYPVAL_ENCODE_CONV_LIST_END 3729#undef TYPVAL_ENCODE_CONV_DICT_START 3730#undef TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START 3731#undef TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK 3732#undef TYPVAL_ENCODE_CONV_DICT_AFTER_KEY 3733#undef TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS 3734#undef TYPVAL_ENCODE_CONV_DICT_END 3735#undef TYPVAL_ENCODE_CONV_RECURSE 3736 3737/// Free memory for a variable value and set the value to NULL or 0 3738/// 3739/// @param[in,out] tv Value to free. 3740void tv_clear (typval_T * const tv ) 3741{ 3742if (tv == NULL || tv -> v_type == VAR_UNKNOWN ) { 3743return ; 3744 } 3745 3746// WARNING: do not translate the string here, gettext is slow and function 3747// is used *very* often. At the current state encode_vim_to_nothing() does 3748// not error out and does not use the argument anywhere. 3749// 3750// If situation changes and this argument will be used, translate it in the 3751// place where it is used. 3752const int evn_ret = encode_vim_to_nothing (NULL ,tv ,"tv_clear() argument" ); 3753 (void )evn_ret ; 3754assert (evn_ret == OK ); 3755} 3756 3757// Free: 3758 3759/// Free allocated Vimscript object and value stored inside 3760/// 3761/// @param tv Object to free. 3762void tv_free (typval_T * tv ) 3763{ 3764if (tv == NULL ) { 3765return ; 3766 } 3767 3768switch (tv -> v_type ) { 3769case VAR_PARTIAL : 3770partial_unref (tv -> vval .v_partial ); 3771break ; 3772case VAR_FUNC : 3773func_unref (tv -> vval .v_string ); 3774FALLTHROUGH ; 3775case VAR_STRING : 3776xfree (tv -> vval .v_string ); 3777break ; 3778case VAR_BLOB : 3779tv_blob_unref (tv -> vval .v_blob ); 3780break ; 3781case VAR_LIST : 3782tv_list_unref (tv -> vval .v_list ); 3783break ; 3784case VAR_DICT : 3785tv_dict_unref (tv -> vval .v_dict ); 3786break ; 3787case VAR_BOOL : 3788case VAR_SPECIAL : 3789case VAR_NUMBER : 3790case VAR_FLOAT : 3791case VAR_UNKNOWN : 3792break ; 3793 } 3794xfree (tv ); 3795} 3796 3797// Copy: 3798 3799/// Copy typval from one location to another 3800/// 3801/// When needed allocates string or increases reference count. Does not make 3802/// a copy of a container, but copies its reference! 3803/// 3804/// It is OK for `from` and `to` to point to the same location; this is used to 3805/// make a copy later. 3806/// 3807/// @param[in] from Location to copy from. 3808/// @param[out] to Location to copy to. 3809void tv_copy (const typval_T * const from ,typval_T * const to ) 3810{ 3811to -> v_type = from -> v_type ; 3812to -> v_lock = VAR_UNLOCKED ; 3813memmove (& to -> vval ,& from -> vval ,sizeof (to -> vval )); 3814switch (from -> v_type ) { 3815case VAR_NUMBER : 3816case VAR_FLOAT : 3817case VAR_BOOL : 3818case VAR_SPECIAL : 3819break ; 3820case VAR_STRING : 3821case VAR_FUNC : 3822if (from -> vval .v_string != NULL ) { 3823to -> vval .v_string = xstrdup (from -> vval .v_string ); 3824if (from -> v_type == VAR_FUNC ) { 3825func_ref (to -> vval .v_string ); 3826 } 3827 } 3828break ; 3829case VAR_PARTIAL : 3830if (to -> vval .v_partial != NULL ) { 3831to -> vval .v_partial -> pt_refcount ++ ; 3832 } 3833break ; 3834case VAR_BLOB : 3835if (from -> vval .v_blob != NULL ) { 3836to -> vval .v_blob -> bv_refcount ++ ; 3837 } 3838break ; 3839case VAR_LIST : 3840tv_list_ref (to -> vval .v_list ); 3841break ; 3842case VAR_DICT : 3843if (from -> vval .v_dict != NULL ) { 3844to -> vval .v_dict -> dv_refcount ++ ; 3845 } 3846break ; 3847case VAR_UNKNOWN : 3848semsg (_ (e_intern2 ),"tv_copy(UNKNOWN)" ); 3849break ; 3850 } 3851} 3852 3853// Locks: 3854 3855/// Lock or unlock an item 3856/// 3857/// @param[out] tv Item to (un)lock. 3858/// @param[in] deep Levels to (un)lock, -1 to (un)lock everything. 3859/// @param[in] lock True if it is needed to lock an item, false to unlock. 3860/// @param[in] check_refcount If true, do not lock a list or dict with a 3861/// reference count larger than 1. 3862void tv_item_lock (typval_T * const tv ,const int deep ,const bool lock ,const bool check_refcount ) 3863FUNC_ATTR_NONNULL_ALL 3864{ 3865// TODO(ZyX-I): Make this not recursive 3866static int recurse = 0 ; 3867 3868if (recurse >=DICT_MAXNEST ) { 3869emsg (_ (e_variable_nested_too_deep_for_unlock )); 3870return ; 3871 } 3872if (deep == 0 ) { 3873return ; 3874 } 3875recurse ++ ; 3876 3877// lock/unlock the item itself 3878#define CHANGE_LOCK (lock ,var ) \ 3879 do { \ 3880 (var) = ((VarLockStatus[]) { \ 3881 [VAR_UNLOCKED] = ((lock) ? VAR_LOCKED : VAR_UNLOCKED), \ 3882 [VAR_LOCKED] = ((lock) ? VAR_LOCKED : VAR_UNLOCKED), \ 3883 [VAR_FIXED] = VAR_FIXED, \ 3884 })[var]; \ 3885 } while (0) 3886CHANGE_LOCK (lock ,tv -> v_lock ); 3887 3888switch (tv -> v_type ) { 3889case VAR_BLOB : { 3890blob_T * const b = tv -> vval .v_blob ; 3891if (b != NULL && !(check_refcount && b -> bv_refcount > 1 )) { 3892CHANGE_LOCK (lock ,b -> bv_lock ); 3893 } 3894break ; 3895 } 3896case VAR_LIST : { 3897list_T * const l = tv -> vval .v_list ; 3898if (l != NULL && !(check_refcount && l -> lv_refcount > 1 )) { 3899CHANGE_LOCK (lock ,l -> lv_lock ); 3900if (deep < 0 || deep > 1 ) { 3901// Recursive: lock/unlock the items the List contains. 3902TV_LIST_ITER (l ,li , { 3903tv_item_lock (TV_LIST_ITEM_TV (li ),deep - 1 ,lock ,check_refcount ); 3904 }); 3905 } 3906 } 3907break ; 3908 } 3909case VAR_DICT : { 3910dict_T * const d = tv -> vval .v_dict ; 3911if (d != NULL && !(check_refcount && d -> dv_refcount > 1 )) { 3912CHANGE_LOCK (lock ,d -> dv_lock ); 3913if (deep < 0 || deep > 1 ) { 3914// recursive: lock/unlock the items the List contains 3915TV_DICT_ITER (d ,di , { 3916tv_item_lock (& di -> di_tv ,deep - 1 ,lock ,check_refcount ); 3917 }); 3918 } 3919 } 3920break ; 3921 } 3922case VAR_NUMBER : 3923case VAR_FLOAT : 3924case VAR_STRING : 3925case VAR_FUNC : 3926case VAR_PARTIAL : 3927case VAR_BOOL : 3928case VAR_SPECIAL : 3929break ; 3930case VAR_UNKNOWN : 3931abort (); 3932 } 3933#undef CHANGE_LOCK 3934recurse -- ; 3935} 3936 3937/// Check whether Vimscript value is locked itself or refers to a locked container 3938/// 3939/// @warning Fixed container is not the same as locked. 3940/// 3941/// @param[in] tv Value to check. 3942/// 3943/// @return True if value is locked, false otherwise. 3944bool tv_islocked (const typval_T * const tv ) 3945FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 3946{ 3947return ((tv -> v_lock == VAR_LOCKED ) 3948|| (tv -> v_type == VAR_LIST 3949&& (tv_list_locked (tv -> vval .v_list )== VAR_LOCKED )) 3950|| (tv -> v_type == VAR_DICT 3951&& tv -> vval .v_dict != NULL 3952&& (tv -> vval .v_dict -> dv_lock == VAR_LOCKED ))); 3953} 3954 3955/// Return true if typval is locked 3956/// 3957/// Also gives an error message when typval is locked. 3958/// 3959/// @param[in] tv Typval. 3960/// @param[in] name Variable name, used in the error message. 3961/// @param[in] name_len Variable name length. Use #TV_TRANSLATE to translate 3962/// variable name and compute the length. Use #TV_CSTRING 3963/// to compute the length with strlen() without 3964/// translating. 3965/// 3966/// Both #TV_… values are used for optimization purposes: 3967/// variable name with its length is needed only in case 3968/// of error, when no error occurs computing them is 3969/// a waste of CPU resources. This especially applies to 3970/// gettext. 3971/// 3972/// @return true if variable is locked, false otherwise. 3973bool tv_check_lock (const typval_T * tv ,const char * name ,size_t name_len ) 3974FUNC_ATTR_WARN_UNUSED_RESULT 3975{ 3976VarLockStatus lock = VAR_UNLOCKED ; 3977 3978switch (tv -> v_type ) { 3979case VAR_BLOB : 3980if (tv -> vval .v_blob != NULL ) { 3981lock = tv -> vval .v_blob -> bv_lock ; 3982 } 3983break ; 3984case VAR_LIST : 3985if (tv -> vval .v_list != NULL ) { 3986lock = tv -> vval .v_list -> lv_lock ; 3987 } 3988break ; 3989case VAR_DICT : 3990if (tv -> vval .v_dict != NULL ) { 3991lock = tv -> vval .v_dict -> dv_lock ; 3992 } 3993break ; 3994default : 3995break ; 3996 } 3997return value_check_lock (tv -> v_lock ,name ,name_len ) 3998|| (lock != VAR_UNLOCKED && value_check_lock (lock ,name ,name_len )); 3999} 4000 4001/// @return true if variable "name" has a locked (immutable) value 4002bool value_check_lock (VarLockStatus lock ,const char * name ,size_t name_len ) 4003{ 4004const char * error_message = NULL ; 4005switch (lock ) { 4006case VAR_UNLOCKED : 4007return false; 4008case VAR_LOCKED : 4009error_message = name == NULL ?N_ (e_value_is_locked ) 4010 :N_ (e_value_is_locked_str ); 4011break ; 4012case VAR_FIXED : 4013error_message = name == NULL ?N_ (e_cannot_change_value ) 4014 :N_ (e_cannot_change_value_of_str ); 4015break ; 4016 } 4017assert (error_message != NULL ); 4018 4019if (name == NULL ) { 4020emsg (_ (error_message )); 4021 }else { 4022if (name_len == TV_TRANSLATE ) { 4023name = _ (name ); 4024name_len = strlen (name ); 4025 }else if (name_len == TV_CSTRING ) { 4026name_len = strlen (name ); 4027 } 4028semsg (_ (error_message ), (int )name_len ,name ); 4029 } 4030 4031return true; 4032} 4033 4034// Comparison: 4035 4036static int tv_equal_recurse_limit ; 4037 4038/// Compare two Vimscript values 4039/// 4040/// Like "==", but strings and numbers are different, as well as floats and 4041/// numbers. 4042/// 4043/// @warning Too nested structures may be considered equal even if they are not. 4044/// 4045/// @param[in] tv1 First value to compare. 4046/// @param[in] tv2 Second value to compare. 4047/// @param[in] ic True if case is to be ignored. 4048/// 4049/// @return true if values are equal. 4050bool tv_equal (typval_T * const tv1 ,typval_T * const tv2 ,const bool ic ) 4051FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 4052{ 4053// TODO(ZyX-I): Make this not recursive 4054static int recursive_cnt = 0 ;// Catch recursive loops. 4055 4056if (!(tv_is_func (* tv1 )&& tv_is_func (* tv2 ))&& tv1 -> v_type != tv2 -> v_type ) { 4057return false; 4058 } 4059 4060// Catch lists and dicts that have an endless loop by limiting 4061// recursiveness to a limit. We guess they are equal then. 4062// A fixed limit has the problem of still taking an awful long time. 4063// Reduce the limit every time running into it. That should work fine for 4064// deeply linked structures that are not recursively linked and catch 4065// recursiveness quickly. 4066if (recursive_cnt == 0 ) { 4067tv_equal_recurse_limit = 1000 ; 4068 } 4069if (recursive_cnt >=tv_equal_recurse_limit ) { 4070tv_equal_recurse_limit -- ; 4071return true; 4072 } 4073 4074switch (tv1 -> v_type ) { 4075case VAR_LIST : { 4076recursive_cnt ++ ; 4077const bool r = tv_list_equal (tv1 -> vval .v_list ,tv2 -> vval .v_list ,ic ); 4078recursive_cnt -- ; 4079return r ; 4080 } 4081case VAR_DICT : { 4082recursive_cnt ++ ; 4083const bool r = tv_dict_equal (tv1 -> vval .v_dict ,tv2 -> vval .v_dict ,ic ); 4084recursive_cnt -- ; 4085return r ; 4086 } 4087case VAR_PARTIAL : 4088case VAR_FUNC : { 4089if ((tv1 -> v_type == VAR_PARTIAL && tv1 -> vval .v_partial == NULL ) 4090|| (tv2 -> v_type == VAR_PARTIAL && tv2 -> vval .v_partial == NULL )) { 4091return false; 4092 } 4093recursive_cnt ++ ; 4094const bool r = func_equal (tv1 ,tv2 ,ic ); 4095recursive_cnt -- ; 4096return r ; 4097 } 4098case VAR_BLOB : 4099return tv_blob_equal (tv1 -> vval .v_blob ,tv2 -> vval .v_blob ); 4100case VAR_NUMBER : 4101return tv1 -> vval .v_number == tv2 -> vval .v_number ; 4102case VAR_FLOAT : 4103return tv1 -> vval .v_float == tv2 -> vval .v_float ; 4104case VAR_STRING : { 4105char buf1 [NUMBUFLEN ]; 4106char buf2 [NUMBUFLEN ]; 4107const char * s1 = tv_get_string_buf (tv1 ,buf1 ); 4108const char * s2 = tv_get_string_buf (tv2 ,buf2 ); 4109return mb_strcmp_ic (ic ,s1 ,s2 )== 0 ; 4110 } 4111case VAR_BOOL : 4112return tv1 -> vval .v_bool == tv2 -> vval .v_bool ; 4113case VAR_SPECIAL : 4114return tv1 -> vval .v_special == tv2 -> vval .v_special ; 4115case VAR_UNKNOWN : 4116// VAR_UNKNOWN can be the result of an invalid expression, let’s say it 4117// does not equal anything, not even self. 4118return false; 4119 } 4120 4121abort (); 4122return false; 4123} 4124 4125// Type checks: 4126 4127/// Check that given value is a number or string 4128/// 4129/// Error messages are compatible with tv_get_number() previously used for the 4130/// same purpose in buf*() functions. Special values are not accepted (previous 4131/// behaviour: silently fail to find buffer). 4132/// 4133/// @param[in] tv Value to check. 4134/// 4135/// @return true if everything is OK, false otherwise. 4136bool tv_check_str_or_nr (const typval_T * const tv ) 4137FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 4138{ 4139switch (tv -> v_type ) { 4140case VAR_NUMBER : 4141case VAR_STRING : 4142return true; 4143case VAR_FLOAT : 4144emsg (_ ("E805: Expected a Number or a String, Float found" )); 4145return false; 4146case VAR_PARTIAL : 4147case VAR_FUNC : 4148emsg (_ ("E703: Expected a Number or a String, Funcref found" )); 4149return false; 4150case VAR_LIST : 4151emsg (_ ("E745: Expected a Number or a String, List found" )); 4152return false; 4153case VAR_DICT : 4154emsg (_ ("E728: Expected a Number or a String, Dictionary found" )); 4155return false; 4156case VAR_BLOB : 4157emsg (_ ("E974: Expected a Number or a String, Blob found" )); 4158return false; 4159case VAR_BOOL : 4160emsg (_ ("E5299: Expected a Number or a String, Boolean found" )); 4161return false; 4162case VAR_SPECIAL : 4163emsg (_ ("E5300: Expected a Number or a String" )); 4164return false; 4165case VAR_UNKNOWN : 4166semsg (_ (e_intern2 ),"tv_check_str_or_nr(UNKNOWN)" ); 4167return false; 4168 } 4169abort (); 4170return false; 4171} 4172 4173#define FUNC_ERROR "E703: Using a Funcref as a Number" 4174 4175static const char * const num_errors []= { 4176 [VAR_PARTIAL ]= N_ (FUNC_ERROR ), 4177 [VAR_FUNC ]= N_ (FUNC_ERROR ), 4178 [VAR_LIST ]= N_ ("E745: Using a List as a Number" ), 4179 [VAR_DICT ]= N_ ("E728: Using a Dictionary as a Number" ), 4180 [VAR_FLOAT ]= N_ ("E805: Using a Float as a Number" ), 4181 [VAR_BLOB ]= N_ ("E974: Using a Blob as a Number" ), 4182 [VAR_UNKNOWN ]= N_ ("E685: using an invalid value as a Number" ), 4183}; 4184 4185#undef FUNC_ERROR 4186 4187/// Check that given value is a number or can be converted to it 4188/// 4189/// Error messages are compatible with tv_get_number_chk() previously used for 4190/// the same purpose. 4191/// 4192/// @param[in] tv Value to check. 4193/// 4194/// @return true if everything is OK, false otherwise. 4195bool tv_check_num (const typval_T * const tv ) 4196FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4197{ 4198switch (tv -> v_type ) { 4199case VAR_NUMBER : 4200case VAR_BOOL : 4201case VAR_SPECIAL : 4202case VAR_STRING : 4203return true; 4204case VAR_FUNC : 4205case VAR_PARTIAL : 4206case VAR_LIST : 4207case VAR_DICT : 4208case VAR_FLOAT : 4209case VAR_BLOB : 4210case VAR_UNKNOWN : 4211emsg (_ (num_errors [tv -> v_type ])); 4212return false; 4213 } 4214abort (); 4215return false; 4216} 4217 4218#define FUNC_ERROR "E729: Using a Funcref as a String" 4219 4220static const char * const str_errors []= { 4221 [VAR_PARTIAL ]= N_ (FUNC_ERROR ), 4222 [VAR_FUNC ]= N_ (FUNC_ERROR ), 4223 [VAR_LIST ]= N_ ("E730: Using a List as a String" ), 4224 [VAR_DICT ]= N_ ("E731: Using a Dictionary as a String" ), 4225 [VAR_BLOB ]= N_ ("E976: Using a Blob as a String" ), 4226 [VAR_UNKNOWN ]= e_using_invalid_value_as_string , 4227}; 4228 4229#undef FUNC_ERROR 4230 4231/// Check that given value is a Vimscript String or can be "cast" to it. 4232/// 4233/// Error messages are compatible with tv_get_string_chk() previously used for 4234/// the same purpose. 4235/// 4236/// @param[in] tv Value to check. 4237/// 4238/// @return true if everything is OK, false otherwise. 4239bool tv_check_str (const typval_T * const tv ) 4240FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4241{ 4242switch (tv -> v_type ) { 4243case VAR_NUMBER : 4244case VAR_BOOL : 4245case VAR_SPECIAL : 4246case VAR_STRING : 4247case VAR_FLOAT : 4248return true; 4249case VAR_PARTIAL : 4250case VAR_FUNC : 4251case VAR_LIST : 4252case VAR_DICT : 4253case VAR_BLOB : 4254case VAR_UNKNOWN : 4255emsg (_ (str_errors [tv -> v_type ])); 4256return false; 4257 } 4258abort (); 4259return false; 4260} 4261 4262// Get: 4263 4264/// Get the number value of a Vimscript object 4265/// 4266/// @note Use tv_get_number_chk() if you need to determine whether there was an 4267/// error. 4268/// 4269/// @param[in] tv Object to get value from. 4270/// 4271/// @return Number value: vim_str2nr() output for VAR_STRING objects, value 4272/// for VAR_NUMBER objects, 0 for other types. 4273varnumber_T tv_get_number (const typval_T * const tv ) 4274FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4275{ 4276bool error = false; 4277return tv_get_number_chk (tv ,& error ); 4278} 4279 4280/// Get the number value of a Vimscript object 4281/// 4282/// @param[in] tv Object to get value from. 4283/// @param[out] ret_error If type error occurred then `true` will be written 4284/// to this location. Otherwise it is not touched. 4285/// 4286/// @note Needs to be initialized to `false` to be 4287/// useful. 4288/// 4289/// @return Number value: vim_str2nr() output for VAR_STRING objects, 4290/// value for VAR_NUMBER objects, 4291/// 1 (true) or 0 (false) for VAR_BOOL objects, 4292/// 0 for VAR_SPECIAL objects, 4293/// -1 (ret_error == NULL) or 0 (otherwise) for other types. 4294varnumber_T tv_get_number_chk (const typval_T * const tv ,bool * const ret_error ) 4295FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG (1 ) 4296{ 4297switch (tv -> v_type ) { 4298case VAR_FUNC : 4299case VAR_PARTIAL : 4300case VAR_LIST : 4301case VAR_DICT : 4302case VAR_BLOB : 4303case VAR_FLOAT : 4304emsg (_ (num_errors [tv -> v_type ])); 4305break ; 4306case VAR_NUMBER : 4307return tv -> vval .v_number ; 4308case VAR_STRING : { 4309varnumber_T n = 0 ; 4310if (tv -> vval .v_string != NULL ) { 4311vim_str2nr (tv -> vval .v_string ,NULL ,NULL ,STR2NR_ALL ,& n ,NULL ,0 , false,NULL ); 4312 } 4313return n ; 4314 } 4315case VAR_BOOL : 4316return tv -> vval .v_bool == kBoolVarTrue ?1 :0 ; 4317case VAR_SPECIAL : 4318return 0 ; 4319case VAR_UNKNOWN : 4320semsg (_ (e_intern2 ),"tv_get_number(UNKNOWN)" ); 4321break ; 4322 } 4323if (ret_error != NULL ) { 4324* ret_error = true; 4325 } 4326return (ret_error == NULL ?-1 :0 ); 4327} 4328 4329/// Get the boolean value of a Vimscript object 4330/// 4331/// @note Use tv_get_bool_chk() if you need to determine whether there was an 4332/// error. 4333/// 4334/// @param[in] tv Object to get value from. 4335/// 4336/// @return Number value: vim_str2nr() output for VAR_STRING objects, value 4337/// for VAR_NUMBER objects, -1 for other types. 4338varnumber_T tv_get_bool (const typval_T * const tv ) 4339FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4340{ 4341return tv_get_number_chk (tv ,NULL ); 4342} 4343 4344varnumber_T tv_get_bool_chk (const typval_T * const tv ,bool * const ret_error ) 4345FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG (1 ) 4346{ 4347return tv_get_number_chk (tv ,ret_error ); 4348} 4349 4350/// Get the line number from Vimscript object 4351/// 4352/// @param[in] tv Object to get value from. Is expected to be a number or 4353/// a special string like ".", "$", … (works with current buffer 4354/// only). 4355/// 4356/// @return Line number or -1 or 0. 4357linenr_T tv_get_lnum (const typval_T * const tv ) 4358FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4359{ 4360const int did_emsg_before = did_emsg ; 4361linenr_T lnum = (linenr_T )tv_get_number_chk (tv ,NULL ); 4362if (lnum <=0 && did_emsg_before == did_emsg && tv -> v_type != VAR_NUMBER ) { 4363int fnum ; 4364// No valid number, try using same function as line() does. 4365pos_T * const fp = var2fpos (tv , true,& fnum , false,curwin ); 4366if (fp != NULL ) { 4367lnum = fp -> lnum ; 4368 } 4369 } 4370return lnum ; 4371} 4372 4373/// Get the line number from Vimscript object 4374/// 4375/// @note Unlike tv_get_lnum(), this one supports only "$" special string. 4376/// 4377/// @param[in] tv Object to get value from. Is expected to be a number or 4378/// a special string "$". 4379/// @param[in] buf Buffer to take last line number from in case tv is "$". May 4380/// be NULL, in this case "$" results in zero return. 4381/// 4382/// @return Line number or 0 in case of error. 4383linenr_T tv_get_lnum_buf (const typval_T * const tv ,const buf_T * const buf ) 4384FUNC_ATTR_NONNULL_ARG (1 )FUNC_ATTR_WARN_UNUSED_RESULT 4385{ 4386if (tv -> v_type == VAR_STRING 4387&& tv -> vval .v_string != NULL 4388&& tv -> vval .v_string [0 ]== '$' 4389&& tv -> vval .v_string [1 ]== NUL 4390&& buf != NULL ) { 4391return buf -> b_ml .ml_line_count ; 4392 } 4393return (linenr_T )tv_get_number_chk (tv ,NULL ); 4394} 4395 4396/// Get the floating-point value of a Vimscript object 4397/// 4398/// Raises an error if object is not number or floating-point. 4399/// 4400/// @param[in] tv Object to get value of. 4401/// 4402/// @return Floating-point value of the variable or zero. 4403float_T tv_get_float (const typval_T * const tv ) 4404FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4405{ 4406switch (tv -> v_type ) { 4407case VAR_NUMBER : 4408return (float_T )(tv -> vval .v_number ); 4409case VAR_FLOAT : 4410return tv -> vval .v_float ; 4411case VAR_PARTIAL : 4412case VAR_FUNC : 4413emsg (_ ("E891: Using a Funcref as a Float" )); 4414break ; 4415case VAR_STRING : 4416emsg (_ ("E892: Using a String as a Float" )); 4417break ; 4418case VAR_LIST : 4419emsg (_ ("E893: Using a List as a Float" )); 4420break ; 4421case VAR_DICT : 4422emsg (_ ("E894: Using a Dictionary as a Float" )); 4423break ; 4424case VAR_BOOL : 4425emsg (_ ("E362: Using a boolean value as a Float" )); 4426break ; 4427case VAR_SPECIAL : 4428emsg (_ ("E907: Using a special value as a Float" )); 4429break ; 4430case VAR_BLOB : 4431emsg (_ ("E975: Using a Blob as a Float" )); 4432break ; 4433case VAR_UNKNOWN : 4434semsg (_ (e_intern2 ),"tv_get_float(UNKNOWN)" ); 4435break ; 4436 } 4437return 0 ; 4438} 4439 4440/// Give an error and return FAIL unless "args[idx]" is a string. 4441int tv_check_for_string_arg (const typval_T * const args ,const int idx ) 4442FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4443{ 4444if (args [idx ].v_type != VAR_STRING ) { 4445semsg (_ (e_string_required_for_argument_nr ),idx + 1 ); 4446return FAIL ; 4447 } 4448return OK ; 4449} 4450 4451/// Give an error and return FAIL unless "args[idx]" is a non-empty string. 4452int tv_check_for_nonempty_string_arg (const typval_T * const args ,const int idx ) 4453FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4454{ 4455if (tv_check_for_string_arg (args ,idx )== FAIL ) { 4456return FAIL ; 4457 } 4458if (args [idx ].vval .v_string == NULL || * args [idx ].vval .v_string == NUL ) { 4459semsg (_ (e_non_empty_string_required_for_argument_nr ),idx + 1 ); 4460return FAIL ; 4461 } 4462return OK ; 4463} 4464 4465/// Check for an optional string argument at "idx" 4466int tv_check_for_opt_string_arg (const typval_T * const args ,const int idx ) 4467FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4468{ 4469return (args [idx ].v_type == VAR_UNKNOWN 4470|| tv_check_for_string_arg (args ,idx )!= FAIL ) ?OK :FAIL ; 4471} 4472 4473/// Give an error and return FAIL unless "args[idx]" is a number. 4474int tv_check_for_number_arg (const typval_T * const args ,const int idx ) 4475FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4476{ 4477if (args [idx ].v_type != VAR_NUMBER ) { 4478semsg (_ (e_number_required_for_argument_nr ),idx + 1 ); 4479return FAIL ; 4480 } 4481return OK ; 4482} 4483 4484/// Check for an optional number argument at "idx" 4485int tv_check_for_opt_number_arg (const typval_T * const args ,const int idx ) 4486FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4487{ 4488return (args [idx ].v_type == VAR_UNKNOWN 4489|| tv_check_for_number_arg (args ,idx )!= FAIL ) ?OK :FAIL ; 4490} 4491 4492/// Give an error and return FAIL unless "args[idx]" is a float or a number. 4493int tv_check_for_float_or_nr_arg (const typval_T * const args ,const int idx ) 4494FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4495{ 4496if (args [idx ].v_type != VAR_FLOAT && args [idx ].v_type != VAR_NUMBER ) { 4497semsg (_ (e_float_or_number_required_for_argument_nr ),idx + 1 ); 4498return FAIL ; 4499 } 4500return OK ; 4501} 4502 4503/// Give an error and return FAIL unless "args[idx]" is a bool. 4504int tv_check_for_bool_arg (const typval_T * const args ,const int idx ) 4505FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4506{ 4507if (args [idx ].v_type != VAR_BOOL 4508&& !(args [idx ].v_type == VAR_NUMBER 4509&& (args [idx ].vval .v_number == 0 4510|| args [idx ].vval .v_number == 1 ))) { 4511semsg (_ (e_bool_required_for_argument_nr ),idx + 1 ); 4512return FAIL ; 4513 } 4514return OK ; 4515} 4516 4517/// Check for an optional bool argument at "idx". 4518/// Return FAIL if the type is wrong. 4519int tv_check_for_opt_bool_arg (const typval_T * const args ,const int idx ) 4520FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4521{ 4522if (args [idx ].v_type == VAR_UNKNOWN ) { 4523return OK ; 4524 } 4525return tv_check_for_bool_arg (args ,idx ); 4526} 4527 4528/// Give an error and return FAIL unless "args[idx]" is a blob. 4529int tv_check_for_blob_arg (const typval_T * const args ,const int idx ) 4530FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4531{ 4532if (args [idx ].v_type != VAR_BLOB ) { 4533semsg (_ (e_blob_required_for_argument_nr ),idx + 1 ); 4534return FAIL ; 4535 } 4536return OK ; 4537} 4538 4539/// Give an error and return FAIL unless "args[idx]" is a list. 4540int tv_check_for_list_arg (const typval_T * const args ,const int idx ) 4541FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4542{ 4543if (args [idx ].v_type != VAR_LIST ) { 4544semsg (_ (e_list_required_for_argument_nr ),idx + 1 ); 4545return FAIL ; 4546 } 4547return OK ; 4548} 4549 4550/// Give an error and return FAIL unless "args[idx]" is a dict. 4551int tv_check_for_dict_arg (const typval_T * const args ,const int idx ) 4552FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4553{ 4554if (args [idx ].v_type != VAR_DICT ) { 4555semsg (_ (e_dict_required_for_argument_nr ),idx + 1 ); 4556return FAIL ; 4557 } 4558return OK ; 4559} 4560 4561/// Give an error and return FAIL unless "args[idx]" is a non-NULL dict. 4562int tv_check_for_nonnull_dict_arg (const typval_T * const args ,const int idx ) 4563FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4564{ 4565if (tv_check_for_dict_arg (args ,idx )== FAIL ) { 4566return FAIL ; 4567 } 4568if (args [idx ].vval .v_dict == NULL ) { 4569semsg (_ (e_non_null_dict_required_for_argument_nr ),idx + 1 ); 4570return FAIL ; 4571 } 4572return OK ; 4573} 4574 4575/// Check for an optional dict argument at "idx" 4576int tv_check_for_opt_dict_arg (const typval_T * const args ,const int idx ) 4577FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4578{ 4579return (args [idx ].v_type == VAR_UNKNOWN 4580|| tv_check_for_dict_arg (args ,idx )!= FAIL ) ?OK :FAIL ; 4581} 4582 4583/// Give an error and return FAIL unless "args[idx]" is a string or 4584/// a number. 4585int tv_check_for_string_or_number_arg (const typval_T * const args ,const int idx ) 4586FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4587{ 4588if (args [idx ].v_type != VAR_STRING && args [idx ].v_type != VAR_NUMBER ) { 4589semsg (_ (e_string_or_number_required_for_argument_nr ),idx + 1 ); 4590return FAIL ; 4591 } 4592return OK ; 4593} 4594 4595/// Give an error and return FAIL unless "args[idx]" is a buffer number. 4596/// Buffer number can be a number or a string. 4597int tv_check_for_buffer_arg (const typval_T * const args ,const int idx ) 4598FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4599{ 4600return tv_check_for_string_or_number_arg (args ,idx ); 4601} 4602 4603/// Give an error and return FAIL unless "args[idx]" is a line number. 4604/// Line number can be a number or a string. 4605int tv_check_for_lnum_arg (const typval_T * const args ,const int idx ) 4606FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4607{ 4608return tv_check_for_string_or_number_arg (args ,idx ); 4609} 4610 4611/// Give an error and return FAIL unless "args[idx]" is a string or a list. 4612int tv_check_for_string_or_list_arg (const typval_T * const args ,const int idx ) 4613FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4614{ 4615if (args [idx ].v_type != VAR_STRING && args [idx ].v_type != VAR_LIST ) { 4616semsg (_ (e_string_or_list_required_for_argument_nr ),idx + 1 ); 4617return FAIL ; 4618 } 4619return OK ; 4620} 4621 4622/// Give an error and return FAIL unless "args[idx]" is a string, a list or a blob. 4623int tv_check_for_string_or_list_or_blob_arg (const typval_T * const args ,const int idx ) 4624FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4625{ 4626if (args [idx ].v_type != VAR_STRING 4627&& args [idx ].v_type != VAR_LIST 4628&& args [idx ].v_type != VAR_BLOB ) { 4629semsg (_ (e_string_list_or_blob_required_for_argument_nr ),idx + 1 ); 4630return FAIL ; 4631 } 4632return OK ; 4633} 4634 4635/// Check for an optional string or list argument at "idx" 4636int tv_check_for_opt_string_or_list_arg (const typval_T * const args ,const int idx ) 4637FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4638{ 4639return (args [idx ].v_type == VAR_UNKNOWN 4640|| tv_check_for_string_or_list_arg (args ,idx )!= FAIL ) ?OK :FAIL ; 4641} 4642 4643/// Give an error and return FAIL unless "args[idx]" is a string 4644/// or a function reference. 4645int tv_check_for_string_or_func_arg (const typval_T * const args ,const int idx ) 4646FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4647{ 4648if (args [idx ].v_type != VAR_PARTIAL 4649&& args [idx ].v_type != VAR_FUNC 4650&& args [idx ].v_type != VAR_STRING ) { 4651semsg (_ (e_string_or_function_required_for_argument_nr ),idx + 1 ); 4652return FAIL ; 4653 } 4654return OK ; 4655} 4656 4657/// Give an error and return FAIL unless "args[idx]" is a list or a blob. 4658int tv_check_for_list_or_blob_arg (const typval_T * const args ,const int idx ) 4659FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 4660{ 4661if (args [idx ].v_type != VAR_LIST && args [idx ].v_type != VAR_BLOB ) { 4662semsg (_ (e_list_or_blob_required_for_argument_nr ),idx + 1 ); 4663return FAIL ; 4664 } 4665return OK ; 4666} 4667 4668/// Get the string value of a "stringish" Vimscript object. 4669/// 4670/// @param[in] tv Object to get value of. 4671/// @param buf Buffer used to hold numbers and special variables converted to 4672/// string. When function encounters one of these stringified value 4673/// will be written to buf and buf will be returned. 4674/// 4675/// Buffer must have NUMBUFLEN size. 4676/// 4677/// @return Object value if it is VAR_STRING object, number converted to 4678/// a string for VAR_NUMBER, v: variable name for VAR_SPECIAL or NULL. 4679const char * tv_get_string_buf_chk (const typval_T * const tv ,char * const buf ) 4680FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4681{ 4682switch (tv -> v_type ) { 4683case VAR_NUMBER : 4684snprintf (buf ,NUMBUFLEN ,"%" PRIdVARNUMBER ,tv -> vval .v_number ); 4685return buf ; 4686case VAR_FLOAT : 4687vim_snprintf (buf ,NUMBUFLEN ,"%g" ,tv -> vval .v_float ); 4688return buf ; 4689case VAR_STRING : 4690if (tv -> vval .v_string != NULL ) { 4691return tv -> vval .v_string ; 4692 } 4693return "" ; 4694case VAR_BOOL : 4695STRCPY (buf ,encode_bool_var_names [tv -> vval .v_bool ]); 4696return buf ; 4697case VAR_SPECIAL : 4698STRCPY (buf ,encode_special_var_names [tv -> vval .v_special ]); 4699return buf ; 4700case VAR_PARTIAL : 4701case VAR_FUNC : 4702case VAR_LIST : 4703case VAR_DICT : 4704case VAR_BLOB : 4705case VAR_UNKNOWN : 4706emsg (_ (str_errors [tv -> v_type ])); 4707return NULL ; 4708 } 4709abort (); 4710return NULL ; 4711} 4712 4713/// Get the string value of a "stringish" Vimscript object. 4714/// 4715/// @warning For number and special values it uses a single, static buffer. It 4716/// may be used only once, next call to tv_get_string may reuse it. Use 4717/// tv_get_string_buf() if you need to use tv_get_string() output after 4718/// calling it again. 4719/// 4720/// @param[in] tv Object to get value of. 4721/// 4722/// @return Object value if it is VAR_STRING object, number converted to 4723/// a string for VAR_NUMBER, v: variable name for VAR_SPECIAL or NULL. 4724const char * tv_get_string_chk (const typval_T * const tv ) 4725FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4726{ 4727static char mybuf [NUMBUFLEN ]; 4728 4729return tv_get_string_buf_chk (tv ,mybuf ); 4730} 4731 4732/// Get the string value of a "stringish" Vimscript object. 4733/// 4734/// @warning For number and special values it uses a single, static buffer. It 4735/// may be used only once, next call to tv_get_string may reuse it. Use 4736/// tv_get_string_buf() if you need to use tv_get_string() output after 4737/// calling it again. 4738/// 4739/// @note tv_get_string_chk() and tv_get_string_buf_chk() are similar, but 4740/// return NULL on error. 4741/// 4742/// @param[in] tv Object to get value of. 4743/// 4744/// @return Object value if it is VAR_STRING object, number converted to 4745/// a string for VAR_NUMBER, v: variable name for VAR_SPECIAL or empty 4746/// string. 4747const char * tv_get_string (const typval_T * const tv ) 4748FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT 4749{ 4750static char mybuf [NUMBUFLEN ]; 4751return tv_get_string_buf ((typval_T * )tv ,mybuf ); 4752} 4753 4754/// Get the string value of a "stringish" Vimscript object. 4755/// 4756/// @note tv_get_string_chk() and tv_get_string_buf_chk() are similar, but 4757/// return NULL on error. 4758/// 4759/// @param[in] tv Object to get value of. 4760/// @param buf Buffer used to hold numbers and special variables converted to 4761/// string. When function encounters one of these stringified value 4762/// will be written to buf and buf will be returned. 4763/// 4764/// Buffer must have NUMBUFLEN size. 4765/// 4766/// @return Object value if it is VAR_STRING object, number converted to 4767/// a string for VAR_NUMBER, v: variable name for VAR_SPECIAL or empty 4768/// string. 4769const char * tv_get_string_buf (const typval_T * const tv ,char * const buf ) 4770FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT 4771{ 4772const char * const res = tv_get_string_buf_chk (tv ,buf ); 4773 4774return res != NULL ?res :"" ; 4775} 4776 4777/// Return true when "tv" is not falsy: non-zero, non-empty string, non-empty 4778/// list, etc. Mostly like what JavaScript does, except that empty list and 4779/// empty dictionary are false. 4780bool tv2bool (const typval_T * const tv ) 4781{ 4782switch (tv -> v_type ) { 4783case VAR_NUMBER : 4784return tv -> vval .v_number != 0 ; 4785case VAR_FLOAT : 4786return tv -> vval .v_float != 0.0 ; 4787case VAR_PARTIAL : 4788return tv -> vval .v_partial != NULL ; 4789case VAR_FUNC : 4790case VAR_STRING : 4791return tv -> vval .v_string != NULL && * tv -> vval .v_string != NUL ; 4792case VAR_LIST : 4793return tv -> vval .v_list != NULL && tv -> vval .v_list -> lv_len > 0 ; 4794case VAR_DICT : 4795return tv -> vval .v_dict != NULL && tv -> vval .v_dict -> dv_hashtab .ht_used > 0 ; 4796case VAR_BOOL : 4797return tv -> vval .v_bool == kBoolVarTrue ; 4798case VAR_SPECIAL : 4799return tv -> vval .v_special != kSpecialVarNull ; 4800case VAR_BLOB : 4801return tv -> vval .v_blob != NULL && tv -> vval .v_blob -> bv_ga .ga_len > 0 ; 4802case VAR_UNKNOWN : 4803break ; 4804 } 4805return false; 4806} 4807 4808/// Check that repeating "slen" items "n" times, does not 4809/// overflow the int used for the resulting length. 4810int check_repeat_count (varnumber_T slen ,varnumber_T n ) 4811{ 4812// Use a division so that the multiplication cannot overflow. 4813if (n <= (varnumber_T )INT_MAX /slen ) { 4814return OK ; 4815 } 4816 4817char buf [NUMBUFLEN ]; 4818vim_snprintf (buf ,sizeof (buf ),"%" PRId64 , (int64_t )n ); 4819semsg (_ (e_val_too_large ),buf ); 4820return FAIL ; 4821}