robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
135.5 KiB4821 linesraw
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 {
46  int item_compare_ic;
47  bool item_compare_lc;
48  bool item_compare_numeric;
49  bool item_compare_numbers;
50  bool item_compare_float;
51  const char *item_compare_func;
52  partial_T *item_compare_partial;
53  dict_T *item_compare_selfdict;
54  bool item_compare_func_err;
55  bool item_compare_keys_ready;  ///< ptrs[].key is precomputed
56} sortinfo_T;
57
58/// Structure representing one list item, used for sort array.
59typedef struct {
60  listitem_T *item;  ///< Sorted list item.
61  int 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.
65  union {
66    varnumber_T inum;  ///< for "N"
67    double 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 {
75  kDict2ListKeys,    ///< List dictionary keys.
76  kDict2ListValues,  ///< List dictionary values.
77  kDict2ListItems,   ///< 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)
135  FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC
136{
137  return 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)
150  FUNC_ATTR_NONNULL_ALL
151{
152  listitem_T *const next_item = TV_LIST_ITEM_NEXT(l, item);
153  tv_list_drop_items(l, item, item);
154  tv_clear(TV_LIST_ITEM_TV(item));
155  xfree(item);
156  return 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)
166  FUNC_ATTR_NONNULL_ALL
167{
168  lw->lw_next = l->lv_watch;
169  l->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)
179  FUNC_ATTR_NONNULL_ALL
180{
181  listwatch_T **lwp = &l->lv_watch;
182  for (listwatch_T *lw = l->lv_watch; lw != NULL; lw = lw->lw_next) {
183    if (lw == lwrem) {
184      *lwp = lw->lw_next;
185      break;
186    }
187    lwp = &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)
198  FUNC_ATTR_NONNULL_ALL
199{
200  for (listwatch_T *lw = l->lv_watch; lw != NULL; lw = lw->lw_next) {
201    if (lw->lw_item == item) {
202      lw->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)
221  FUNC_ATTR_NONNULL_RET
222{
223  list_T *const list = xcalloc(1, sizeof(list_T));
224
225  // Prepend the list to the list of lists for garbage collection.
226  if (gc_first_list != NULL) {
227    gc_first_list->lv_used_prev = list;
228  }
229  list->lv_used_prev = NULL;
230  list->lv_used_next = gc_first_list;
231  gc_first_list = list;
232  list->lua_table_ref = LUA_NOREF;
233  return 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)
240  FUNC_ATTR_NONNULL_ALL
241{
242#define SL_SIZE ARRAY_SIZE(sl->sl_items)
243  list_T *const l = &sl->sl_list;
244
245  CLEAR_POINTER(sl);
246  l->lv_first = &sl->sl_items[0];
247  l->lv_last = &sl->sl_items[SL_SIZE - 1];
248  l->lv_refcount = DO_NOT_FREE_CNT;
249  tv_list_set_lock(l, VAR_FIXED);
250  sl->sl_list.lv_len = 10;
251
252  sl->sl_items[0].li_prev = NULL;
253  sl->sl_items[0].li_next = &sl->sl_items[1];
254  sl->sl_items[SL_SIZE - 1].li_prev = &sl->sl_items[SL_SIZE - 2];
255  sl->sl_items[SL_SIZE - 1].li_next = NULL;
256
257  for (size_t i = 1; i < SL_SIZE - 1; i++) {
258    listitem_T *const li = &sl->sl_items[i];
259    li->li_prev = li - 1;
260    li->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)
269  FUNC_ATTR_NONNULL_ALL
270{
271  CLEAR_POINTER(l);
272  l->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)
279  FUNC_ATTR_NONNULL_ALL
280{
281  for (listitem_T *item = l->lv_first; item != NULL; item = l->lv_first) {
282    // Remove the item before deleting it.
283    l->lv_first = item->li_next;
284    tv_clear(&item->li_tv);
285    xfree(item);
286  }
287  l->lv_len = 0;
288  l->lv_idx_item = NULL;
289  l->lv_last = NULL;
290  assert(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)
299  FUNC_ATTR_NONNULL_ALL
300{
301  // Remove the list from the list of lists for garbage collection.
302  if (l->lv_used_prev == NULL) {
303    gc_first_list = l->lv_used_next;
304  } else {
305    l->lv_used_prev->lv_used_next = l->lv_used_next;
306  }
307  if (l->lv_used_next != NULL) {
308    l->lv_used_next->lv_used_prev = l->lv_used_prev;
309  }
310
311  NLUA_CLEAR_REF(l->lua_table_ref);
312  xfree(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)
322  FUNC_ATTR_NONNULL_ALL
323{
324  if (tv_in_free_unref_items) {
325    return;
326  }
327
328  tv_list_free_contents(l);
329  tv_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{
339  if (l != NULL && --l->lv_refcount <= 0) {
340    tv_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)
354  FUNC_ATTR_NONNULL_ALL
355{
356  // Notify watchers.
357  for (listitem_T *ip = item; ip != item2->li_next; ip = ip->li_next) {
358    l->lv_len--;
359    tv_list_watch_fix(l, ip);
360  }
361
362  if (item2->li_next == NULL) {
363    l->lv_last = item->li_prev;
364  } else {
365    item2->li_next->li_prev = item->li_prev;
366  }
367  if (item->li_prev == NULL) {
368    l->lv_first = item2->li_next;
369  } else {
370    item->li_prev->li_next = item2->li_next;
371  }
372  l->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)
377  FUNC_ATTR_NONNULL_ALL
378{
379  tv_list_drop_items(l, item, item2);
380  for (listitem_T *li = item;;) {
381    tv_clear(TV_LIST_ITEM_TV(li));
382    listitem_T *const nli = li->li_next;
383    xfree(li);
384    if (li == item2) {
385      break;
386    }
387    li = 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,
399                        list_T *const tgt_l, const int cnt)
400  FUNC_ATTR_NONNULL_ALL
401{
402  tv_list_drop_items(l, item, item2);
403  item->li_prev = tgt_l->lv_last;
404  item2->li_next = NULL;
405  if (tgt_l->lv_last == NULL) {
406    tgt_l->lv_first = item;
407  } else {
408    tgt_l->lv_last->li_next = item;
409  }
410  tgt_l->lv_last = item2;
411  tgt_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)
421  FUNC_ATTR_NONNULL_ARG(1, 2)
422{
423  if (item == NULL) {
424    // Append new item at end of list.
425    tv_list_append(l, ni);
426  } else {
427    // Insert new item before existing item.
428    ni->li_prev = item->li_prev;
429    ni->li_next = item;
430    if (item->li_prev == NULL) {
431      l->lv_first = ni;
432      l->lv_idx++;
433    } else {
434      item->li_prev->li_next = ni;
435      l->lv_idx_item = NULL;
436    }
437    item->li_prev = ni;
438    l->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{
451  listitem_T *const ni = tv_list_item_alloc();
452
453  tv_copy(tv, &ni->li_tv);
454  tv_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)
462  FUNC_ATTR_NONNULL_ALL
463{
464  if (l->lv_last == NULL) {
465    // empty list
466    l->lv_first = item;
467    l->lv_last = item;
468    item->li_prev = NULL;
469  } else {
470    l->lv_last->li_next = item;
471    item->li_prev = l->lv_last;
472    l->lv_last = item;
473  }
474  l->lv_len++;
475  item->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)
484  FUNC_ATTR_NONNULL_ALL
485{
486  listitem_T *const li = tv_list_item_alloc();
487  tv_copy(tv, TV_LIST_ITEM_TV(li));
488  tv_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)
496  FUNC_ATTR_NONNULL_ALL
497{
498  listitem_T *const li = tv_list_item_alloc();
499  *TV_LIST_ITEM_TV(li) = tv;
500  tv_list_append(l, li);
501  return 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)
509  FUNC_ATTR_NONNULL_ARG(1)
510{
511  tv_list_append_owned_tv(l, (typval_T) {
512    .v_type = VAR_LIST,
513    .v_lock = VAR_UNLOCKED,
514    .vval.v_list = itemlist,
515  });
516  tv_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)
524  FUNC_ATTR_NONNULL_ARG(1)
525{
526  tv_list_append_owned_tv(l, (typval_T) {
527    .v_type = VAR_DICT,
528    .v_lock = VAR_UNLOCKED,
529    .vval.v_dict = dict,
530  });
531  if (dict != NULL) {
532    dict->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)
544  FUNC_ATTR_NONNULL_ARG(1)
545{
546  tv_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)
564  FUNC_ATTR_NONNULL_ARG(1)
565{
566  tv_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{
580  tv_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,
600                     const int copyID)
601  FUNC_ATTR_WARN_UNUSED_RESULT
602{
603  if (orig == NULL) {
604    return NULL;
605  }
606
607  list_T *copy = tv_list_alloc(tv_list_len(orig));
608  tv_list_ref(copy);
609  if (copyID != 0) {
610    // Do this before adding the items, because one of the items may
611    // refer back to this list.
612    orig->lv_copyID = copyID;
613    orig->lv_copylist = copy;
614  }
615  TV_LIST_ITER(orig, item, {
616    if (got_int) {
617      break;
618    }
619    listitem_T *const ni = tv_list_item_alloc();
620    if (deep) {
621      if (var_item_copy(conv, TV_LIST_ITEM_TV(item), TV_LIST_ITEM_TV(ni),
622                        deep, copyID) == FAIL) {
623        xfree(ni);
624        goto tv_list_copy_error;
625      }
626    } else {
627      tv_copy(TV_LIST_ITEM_TV(item), TV_LIST_ITEM_TV(ni));
628    }
629    tv_list_append(copy, ni);
630  });
631
632  return copy;
633
634tv_list_copy_error:
635  tv_list_unref(copy);
636  return 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{
643  listitem_T *li = tv_list_find_index(l, n1);
644  if (li != NULL) {
645    return li;
646  }
647
648  if (!quiet) {
649    semsg(_(e_list_index_out_of_range_nr), (int64_t)(*n1));
650  }
651  return 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,
659                                  int *const n2, const bool quiet)
660{
661  if (*n2 < 0) {
662    listitem_T *ni = tv_list_find(l, *n2);
663    if (ni == NULL) {
664      if (!quiet) {
665        semsg(_(e_list_index_out_of_range_nr), (int64_t)(*n2));
666      }
667      return FAIL;
668    }
669    *n2 = tv_list_idx_of_item(l, ni);
670  }
671
672  // Check that n2 isn't before n1.
673  if (*n1 < 0) {
674    *n1 = tv_list_idx_of_item(l, li1);
675  }
676  if (*n2 < *n1) {
677    if (!quiet) {
678      semsg(_(e_list_index_out_of_range_nr), (int64_t)(*n2));
679    }
680    return FAIL;
681  }
682  return 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,
693                         const bool empty_idx2, const char *const op, const char *const varname)
694{
695  int idx1 = idx1_arg;
696  listitem_T *const first_li = tv_list_find_index(dest, &idx1);
697  listitem_T *src_li;
698
699  // Check whether any of the list items is locked before making any changes.
700  int idx = idx1;
701  listitem_T *dest_li = first_li;
702  for (src_li = tv_list_first(src); src_li != NULL && dest_li != NULL;) {
703    if (value_check_lock(TV_LIST_ITEM_TV(dest_li)->v_lock, varname, TV_CSTRING)) {
704      return FAIL;
705    }
706    src_li = TV_LIST_ITEM_NEXT(src, src_li);
707    if (src_li == NULL || (!empty_idx2 && idx2 == idx)) {
708      break;
709    }
710    dest_li = TV_LIST_ITEM_NEXT(dest, dest_li);
711    idx++;
712  }
713
714  // Assign the List values to the list items.
715  idx = idx1;
716  dest_li = first_li;
717  for (src_li = tv_list_first(src); src_li != NULL;) {
718    assert(dest_li != NULL);
719    if (op != NULL && *op != '=') {
720      eexe_mod_op(TV_LIST_ITEM_TV(dest_li), TV_LIST_ITEM_TV(src_li), op);
721    } else {
722      tv_clear(TV_LIST_ITEM_TV(dest_li));
723      tv_copy(TV_LIST_ITEM_TV(src_li), TV_LIST_ITEM_TV(dest_li));
724    }
725    src_li = TV_LIST_ITEM_NEXT(src, src_li);
726    if (src_li == NULL || (!empty_idx2 && idx2 == idx)) {
727      break;
728    }
729    if (TV_LIST_ITEM_NEXT(dest, dest_li) == NULL) {
730      // Need to add an empty item.
731      tv_list_append_number(dest, 0);
732      // "dest_li" may have become invalid after append, don’t use it.
733      dest_li = tv_list_last(dest);  // Valid again.
734    } else {
735      dest_li = TV_LIST_ITEM_NEXT(dest, dest_li);
736    }
737    idx++;
738  }
739  if (src_li != NULL) {
740    emsg(_("E710: List value has more items than target"));
741    return FAIL;
742  }
743  if (empty_idx2
744      ? (dest_li != NULL && TV_LIST_ITEM_NEXT(dest, dest_li) != NULL)
745      : idx != idx2) {
746    emsg(_("E711: List value has not enough items"));
747    return FAIL;
748  }
749  return 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)
761  FUNC_ATTR_NONNULL_ARG(1)
762{
763  listitem_T *item;
764  int done = 0;
765  if (maxdepth == 0) {
766    return;
767  }
768
769  if (first == NULL) {
770    item = list->lv_first;
771  } else {
772    item = first;
773  }
774
775  while (item != NULL && done < maxitems) {
776    listitem_T *next = item->li_next;
777
778    fast_breakcheck();
779    if (got_int) {
780      return;
781    }
782    if (item->li_tv.v_type == VAR_LIST) {
783      list_T *itemlist = item->li_tv.vval.v_list;
784
785      tv_list_drop_items(list, item, item);
786      tv_list_extend(list, itemlist, next);
787
788      if (maxdepth > 0) {
789        tv_list_flatten(list,
790                        item->li_prev == NULL ? list->lv_first : item->li_prev->li_next,
791                        itemlist->lv_len, maxdepth - 1);
792      }
793      tv_clear(&item->li_tv);
794      xfree(item);
795    }
796
797    done++;
798    item = 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{
808  blob_T *blob = argvars[0].vval.v_blob;
809
810  tv_list_alloc_ret(rettv, tv_blob_len(blob));
811
812  for (int i = 0; i < tv_blob_len(blob); i++) {
813    list_T *l2 = tv_list_alloc(2);
814    tv_list_append_list(rettv->vval.v_list, l2);
815    tv_list_append_number(l2, i);
816    tv_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{
823  tv_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{
830  list_T *l = argvars[0].vval.v_list;
831
832  tv_list_alloc_ret(rettv, tv_list_len(l));
833  if (l == NULL) {
834    return;  // null list behaves like an empty list
835  }
836
837  varnumber_T idx = 0;
838  TV_LIST_ITER(l, li, {
839    list_T *l2 = tv_list_alloc(2);
840    tv_list_append_list(rettv->vval.v_list, l2);
841    tv_list_append_number(l2, idx);
842    tv_list_append_tv(l2, TV_LIST_ITEM_TV(li));
843    idx++;
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{
851  const char *p = argvars[0].vval.v_string;
852
853  tv_list_alloc_ret(rettv, kListLenMayKnow);
854  if (p == NULL) {
855    return;  // null string behaves like an empty string
856  }
857
858  for (varnumber_T idx = 0; *p != NUL; idx++) {
859    int len = utfc_ptr2len(p);
860    if (len == 0) {
861      break;
862    }
863    list_T *l2 = tv_list_alloc(2);
864    tv_list_append_list(rettv->vval.v_list, l2);
865    tv_list_append_number(l2, idx);
866    tv_list_append_string(l2, p, len);
867    p += 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)
877  FUNC_ATTR_NONNULL_ARG(1)
878{
879  int todo = tv_list_len(l2);
880
881  // NULL list is equivalent to an empty list: nothing to do.
882  if (todo == 0) {
883    return;
884  }
885
886  listitem_T *const befbef = (bef == NULL ? NULL : bef->li_prev);
887  listitem_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.
890  for (listitem_T *item = tv_list_first(l2)
891       ; item != NULL && todo--
892       ; item = (item == befbef ? saved_next : item->li_next)) {
893    tv_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)
905  FUNC_ATTR_WARN_UNUSED_RESULT
906{
907  list_T *l;
908
909  tv->v_type = VAR_LIST;
910  tv->v_lock = VAR_UNLOCKED;
911  if (l1 == NULL && l2 == NULL) {
912    l = NULL;
913  } else if (l1 == NULL) {
914    l = tv_list_copy(NULL, l2, false, 0);
915  } else {
916    l = tv_list_copy(NULL, l1, false, 0);
917    if (l != NULL && l2 != NULL) {
918      tv_list_extend(l, l2, NULL);
919    }
920  }
921  if (l == NULL && !(l1 == NULL && l2 == NULL)) {
922    return FAIL;
923  }
924
925  tv->vval.v_list = l;
926  return OK;
927}
928
929static list_T *tv_list_slice(list_T *ol, varnumber_T n1, varnumber_T n2)
930{
931  list_T *l = tv_list_alloc(n2 - n1 + 1);
932  listitem_T *item = tv_list_find(ol, (int)n1);
933  for (; n1 <= n2; n1++) {
934    tv_list_append_tv(l, TV_LIST_ITEM_TV(item));
935    item = TV_LIST_ITEM_NEXT(ol, item);
936  }
937  return l;
938}
939
940int tv_list_slice_or_index(list_T *list, bool range, varnumber_T n1_arg, varnumber_T n2_arg,
941                           bool exclusive, typval_T *rettv, bool verbose)
942{
943  int len = tv_list_len(rettv->vval.v_list);
944  varnumber_T n1 = n1_arg;
945  varnumber_T n2 = n2_arg;
946
947  if (n1 < 0) {
948    n1 = len + n1;
949  }
950  if (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.
953    if (!range) {
954      if (verbose) {
955        semsg(_(e_list_index_out_of_range_nr), (int64_t)n1_arg);
956      }
957      return FAIL;
958    }
959    n1 = len;
960  }
961  if (range) {
962    if (n2 < 0) {
963      n2 = len + n2;
964    } else if (n2 >= len) {
965      n2 = len - (exclusive ? 0 : 1);
966    }
967    if (exclusive) {
968      n2--;
969    }
970    if (n2 < 0 || n2 + 1 < n1) {
971      n2 = -1;
972    }
973    list_T *l = tv_list_slice(rettv->vval.v_list, n1, n2);
974    tv_clear(rettv);
975    tv_list_set_ret(rettv, l);
976  } else {
977    // copy the item to "var1" to avoid that freeing the list makes it
978    // invalid.
979    typval_T var1;
980    tv_copy(TV_LIST_ITEM_TV(tv_list_find(rettv->vval.v_list, (int)n1)), &var1);
981    tv_clear(rettv);
982    *rettv = var1;
983  }
984  return OK;
985}
986
987typedef struct {
988  String s;
989  char *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,
1001                           garray_T *const join_gap)
1002  FUNC_ATTR_NONNULL_ALL
1003{
1004  size_t sumlen = 0;
1005  bool first = true;
1006
1007  // Stringify each item in the list.
1008  TV_LIST_ITER(l, item, {
1009    if (got_int) {
1010      break;
1011    }
1012    String s;
1013    s.data = encode_tv2echo(TV_LIST_ITEM_TV(item), &s.size);
1014    if (s.data == NULL) {
1015      return FAIL;
1016    }
1017
1018    sumlen += s.size;
1019
1020    Join *const p = GA_APPEND_VIA_PTR(Join, join_gap);
1021    p->s = s;
1022    p->tofree = s.data;
1023
1024    line_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.
1029  size_t seplen = strlen(sep);
1030  if (join_gap->ga_len >= 2) {
1031    sumlen += seplen * (size_t)(join_gap->ga_len - 1);
1032  }
1033  ga_grow(gap, (int)sumlen + 2);
1034
1035  for (int i = 0; i < join_gap->ga_len && !got_int; i++) {
1036    if (first) {
1037      first = false;
1038    } else {
1039      ga_concat_len(gap, sep, seplen);
1040    }
1041    const Join *const p = ((const Join *)join_gap->ga_data) + i;
1042
1043    if (p->s.data != NULL) {
1044      ga_concat_len(gap, p->s.data, p->s.size);
1045    }
1046    line_breakcheck();
1047  }
1048
1049  return 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)
1060  FUNC_ATTR_NONNULL_ARG(1)
1061{
1062  if (!tv_list_len(l)) {
1063    return OK;
1064  }
1065
1066  garray_T join_ga;
1067  int retval;
1068
1069  ga_init(&join_ga, (int)sizeof(Join), tv_list_len(l));
1070  retval = list_join_inner(gap, l, sep, &join_ga);
1071
1072#define FREE_JOIN_TOFREE(join) xfree((join)->tofree)
1073  GA_DEEP_CLEAR(&join_ga, Join, FREE_JOIN_TOFREE);
1074#undef FREE_JOIN_TOFREE
1075
1076  return retval;
1077}
1078
1079/// "join()" function
1080void f_join(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1081{
1082  if (argvars[0].v_type != VAR_LIST) {
1083    emsg(_(e_listreq));
1084    return;
1085  }
1086  const char *const sep = (argvars[1].v_type == VAR_UNKNOWN
1087                           ? " "
1088                           : tv_get_string_chk(&argvars[1]));
1089
1090  rettv->v_type = VAR_STRING;
1091
1092  if (sep != NULL) {
1093    garray_T ga;
1094    ga_init(&ga, (int)sizeof(char), 80);
1095    tv_list_join(&ga, argvars[0].vval.v_list, sep);
1096    ga_append(&ga, NUL);
1097    rettv->vval.v_string = ga.ga_data;
1098  } else {
1099    rettv->vval.v_string = NULL;
1100  }
1101}
1102
1103/// "list2str()" function
1104void f_list2str(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1105{
1106  garray_T ga;
1107
1108  rettv->v_type = VAR_STRING;
1109  rettv->vval.v_string = NULL;
1110  if (argvars[0].v_type != VAR_LIST) {
1111    emsg(_(e_invarg));
1112    return;
1113  }
1114
1115  list_T *const l = argvars[0].vval.v_list;
1116  if (l == NULL) {
1117    return;  // empty list results in empty string
1118  }
1119
1120  ga_init(&ga, 1, 80);
1121  char buf[MB_MAXBYTES + 1];
1122
1123  TV_LIST_ITER_CONST(l, li, {
1124    const varnumber_T n = tv_get_number(TV_LIST_ITEM_TV(li));
1125    const size_t buflen = (size_t)utf_char2bytes((int)n, buf);
1126    buf[buflen] = NUL;
1127    ga_concat_len(&ga, buf, buflen);
1128  });
1129  ga_append(&ga, NUL);
1130
1131  rettv->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{
1137  list_T *l;
1138  bool error = false;
1139
1140  if (value_check_lock(tv_list_locked((l = argvars[0].vval.v_list)),
1141                       arg_errmsg, TV_TRANSLATE)) {
1142    return;
1143  }
1144
1145  int64_t idx = tv_get_number_chk(&argvars[1], &error);
1146
1147  listitem_T *item;
1148
1149  if (error) {
1150    // Type error: do nothing, errmsg already given.
1151  } else if ((item = tv_list_find(l, (int)idx)) == NULL) {
1152    semsg(_(e_list_index_out_of_range_nr), idx);
1153  } else {
1154    if (argvars[2].v_type == VAR_UNKNOWN) {
1155      // Remove one item, return its value.
1156      tv_list_drop_items(l, item, item);
1157      *rettv = *TV_LIST_ITEM_TV(item);
1158      xfree(item);
1159    } else {
1160      listitem_T *item2;
1161      // Remove range of items, return list with values.
1162      int64_t end = tv_get_number_chk(&argvars[2], &error);
1163      if (error) {
1164        // Type error: do nothing.
1165      } else if ((item2 = tv_list_find(l, (int)end)) == NULL) {
1166        semsg(_(e_list_index_out_of_range_nr), end);
1167      } else {
1168        int cnt = 0;
1169
1170        listitem_T *li;
1171        for (li = item; li != NULL; li = TV_LIST_ITEM_NEXT(l, li)) {
1172          cnt++;
1173          if (li == item2) {
1174            break;
1175          }
1176        }
1177        if (li == NULL) {  // Didn't find "item2" after "item".
1178          emsg(_(e_invrange));
1179        } else {
1180          tv_list_move_items(l, item, item2, tv_list_alloc_ret(rettv, cnt),
1181                             cnt);
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{
1195  ListSortItem *const si1 = (ListSortItem *)s1;
1196  ListSortItem *const si2 = (ListSortItem *)s2;
1197
1198  typval_T *const tv1 = TV_LIST_ITEM_TV(si1->item);
1199  typval_T *const tv2 = TV_LIST_ITEM_TV(si2->item);
1200
1201  int res;
1202
1203  if (sortinfo->item_compare_numbers) {
1204    const varnumber_T v1 = sortinfo->item_compare_keys_ready
1205                           ? si1->key.inum : tv_get_number(tv1);
1206    const varnumber_T v2 = sortinfo->item_compare_keys_ready
1207                           ? si2->key.inum : tv_get_number(tv2);
1208
1209    res = v1 == v2 ? 0 : v1 > v2 ? 1 : -1;
1210    goto item_compare_end;
1211  }
1212
1213  if (sortinfo->item_compare_float) {
1214    const float_T v1 = sortinfo->item_compare_keys_ready
1215                       ? si1->key.fnum : tv_get_float(tv1);
1216    const float_T v2 = sortinfo->item_compare_keys_ready
1217                       ? si2->key.fnum : tv_get_float(tv2);
1218
1219    res = v1 == v2 ? 0 : v1 > v2 ? 1 : -1;
1220    goto item_compare_end;
1221  }
1222
1223  if (sortinfo->item_compare_numeric && sortinfo->item_compare_keys_ready) {
1224    double n1 = si1->key.fnum;
1225    double n2 = si2->key.fnum;
1226
1227    res = n1 == n2 ? 0 : n1 > n2 ? 1 : -1;
1228    if (res == 0 && !keep_zero) {
1229      res = si1->idx > si2->idx ? 1 : -1;
1230    }
1231    return res;
1232  }
1233
1234  char *tofree1 = NULL;
1235  char *tofree2 = NULL;
1236  char *p1;
1237  char *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.
1242  if (tv1->v_type == VAR_STRING) {
1243    if (tv2->v_type != VAR_STRING || sortinfo->item_compare_numeric) {
1244      p1 = "'";
1245    } else {
1246      p1 = tv1->vval.v_string;
1247    }
1248  } else {
1249    tofree1 = p1 = encode_tv2string(tv1, NULL);
1250  }
1251  if (tv2->v_type == VAR_STRING) {
1252    if (tv1->v_type != VAR_STRING || sortinfo->item_compare_numeric) {
1253      p2 = "'";
1254    } else {
1255      p2 = tv2->vval.v_string;
1256    }
1257  } else {
1258    tofree2 = p2 = encode_tv2string(tv2, NULL);
1259  }
1260  if (p1 == NULL) {
1261    p1 = "";
1262  }
1263  if (p2 == NULL) {
1264    p2 = "";
1265  }
1266  if (!sortinfo->item_compare_numeric) {
1267    if (sortinfo->item_compare_lc) {
1268      res = strcoll(p1, p2);
1269    } else {
1270      res = sortinfo->item_compare_ic ? STRICMP(p1, p2) : strcmp(p1, p2);
1271    }
1272  } else {
1273    double n1 = strtod(p1, &p1);
1274    double n2 = strtod(p2, &p2);
1275    res = n1 == n2 ? 0 : n1 > n2 ? 1 : -1;
1276  }
1277
1278  xfree(tofree1);
1279  xfree(tofree2);
1280
1281item_compare_end:
1282  // When the result would be zero, compare the item indexes.  Makes the
1283  // sort stable.
1284  if (res == 0 && !keep_zero) {
1285    // WARNING: When using uniq si1 and si2 are actually listitem_T **, no
1286    // indexes are there.
1287    res = si1->idx > si2->idx ? 1 : -1;
1288  }
1289  return res;
1290}
1291
1292static int item_compare_keeping_zero(const void *s1, const void *s2)
1293{
1294  return item_compare(s1, s2, true);
1295}
1296
1297static int item_compare_not_keeping_zero(const void *s1, const void *s2)
1298{
1299  return item_compare(s1, s2, false);
1300}
1301
1302static int item_compare2(const void *s1, const void *s2, bool keep_zero)
1303{
1304  typval_T rettv;
1305  typval_T argv[3];
1306  const char *func_name;
1307  partial_T *partial = sortinfo->item_compare_partial;
1308
1309  // shortcut after failure in previous call; compare all items equal
1310  if (sortinfo->item_compare_func_err) {
1311    return 0;
1312  }
1313
1314  ListSortItem *si1 = (ListSortItem *)s1;
1315  ListSortItem *si2 = (ListSortItem *)s2;
1316
1317  if (partial == NULL) {
1318    func_name = sortinfo->item_compare_func;
1319  } else {
1320    func_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.
1325  tv_copy(TV_LIST_ITEM_TV(si1->item), &argv[0]);
1326  tv_copy(TV_LIST_ITEM_TV(si2->item), &argv[1]);
1327
1328  rettv.v_type = VAR_UNKNOWN;  // tv_clear() uses this
1329  funcexe_T funcexe = FUNCEXE_INIT;
1330  funcexe.fe_evaluate = true;
1331  funcexe.fe_partial = partial;
1332  funcexe.fe_selfdict = sortinfo->item_compare_selfdict;
1333  int res = call_func(func_name, -1, &rettv, 2, argv, &funcexe);
1334  tv_clear(&argv[0]);
1335  tv_clear(&argv[1]);
1336
1337  if (res == FAIL) {
1338    // XXX: ITEM_COMPARE_FAIL is unused
1339    res = ITEM_COMPARE_FAIL;
1340    sortinfo->item_compare_func_err = true;
1341  } else {
1342    varnumber_T n = tv_get_number_chk(&rettv, &sortinfo->item_compare_func_err);
1343    res = (n > 0) ? 1 : (n < 0) ? -1 : 0;
1344  }
1345  if (sortinfo->item_compare_func_err) {
1346    res = ITEM_COMPARE_FAIL;  // return value has wrong type
1347  }
1348  tv_clear(&rettv);
1349
1350  // When the result would be zero, compare the pointers themselves.  Makes
1351  // the sort stable.
1352  if (res == 0 && !keep_zero) {
1353    // WARNING: When using uniq si1 and si2 are actually listitem_T **, no
1354    // indexes are there.
1355    res = si1->idx > si2->idx ? 1 : -1;
1356  }
1357
1358  return res;
1359}
1360
1361static int item_compare2_keeping_zero(const void *s1, const void *s2)
1362{
1363  return item_compare2(s1, s2, true);
1364}
1365
1366static int item_compare2_not_keeping_zero(const void *s1, const void *s2)
1367{
1368  return 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{
1375  if (info->item_compare_numbers) {
1376    for (int i = 0; i < len; i++) {
1377      ptrs[i].key.inum = tv_get_number(&ptrs[i].item->li_tv);
1378    }
1379  } else if (info->item_compare_float) {
1380    for (int i = 0; i < len; i++) {
1381      ptrs[i].key.fnum = tv_get_float(&ptrs[i].item->li_tv);
1382    }
1383  } else {  // info->item_compare_numeric
1384    for (int i = 0; i < len; i++) {
1385      typval_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.
1389      if (tv->v_type == VAR_STRING) {
1390        ptrs[i].key.fnum = 0.0;
1391      } else {
1392        char *p = encode_tv2string(tv, NULL);
1393        ptrs[i].key.fnum = p == NULL ? 0.0 : strtod(p, NULL);
1394        xfree(p);
1395      }
1396    }
1397  }
1398  info->item_compare_keys_ready = true;
1399}
1400
1401/// sort() List "l"
1402static void do_sort(list_T *l, sortinfo_T *info)
1403{
1404  const int len = tv_list_len(l);
1405
1406  // Make an array with each entry pointing to an item in the List.
1407  ListSortItem *ptrs = xmalloc((size_t)((unsigned)len * sizeof(ListSortItem)));
1408
1409  // f_sort(): ptrs will be the list to sort
1410  int i = 0;
1411  TV_LIST_ITER(l, li, {
1412    ptrs[i].item = li;
1413    ptrs[i].idx = i;
1414    i++;
1415  });
1416
1417  info->item_compare_func_err = false;
1418  info->item_compare_keys_ready = false;
1419
1420  if (info->item_compare_func == NULL && info->item_compare_partial == NULL
1421      && (info->item_compare_numbers || info->item_compare_float
1422          || info->item_compare_numeric)) {
1423    sort_compute_keys(ptrs, len, info);
1424  }
1425  ListSorter 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.
1431  qsort(ptrs, (size_t)len, sizeof(ListSortItem), item_compare_func);
1432  if (!info->item_compare_func_err) {
1433    // Clear the list and append the items in the sorted order.
1434    l->lv_first = NULL;
1435    l->lv_last = NULL;
1436    l->lv_idx_item = NULL;
1437    l->lv_len = 0;
1438    for (i = 0; i < len; i++) {
1439      tv_list_append(l, ptrs[i].item);
1440    }
1441  }
1442  if (info->item_compare_func_err) {
1443    emsg(_("E702: Sort compare function failed"));
1444  }
1445
1446  xfree(ptrs);
1447}
1448
1449/// uniq() List "l"
1450static void do_uniq(list_T *l, sortinfo_T *info)
1451{
1452  const int len = tv_list_len(l);
1453
1454  // Make an array with each entry pointing to an item in the List.
1455  ListSortItem *ptrs = xmalloc((size_t)((unsigned)len * sizeof(ListSortItem)));
1456
1457  // f_uniq(): ptrs will be a stack of items to remove.
1458
1459  info->item_compare_func_err = false;
1460  ListSorter 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
1465  for (listitem_T *li = TV_LIST_ITEM_NEXT(l, tv_list_first(l)); li != NULL;) {
1466    listitem_T *const prev_li = TV_LIST_ITEM_PREV(l, li);
1467    if (item_compare_func(&prev_li, &li) == 0) {
1468      li = tv_list_item_remove(l, li);
1469    } else {
1470      li = TV_LIST_ITEM_NEXT(l, li);
1471    }
1472    if (info->item_compare_func_err) {
1473      emsg(_("E882: Uniq compare function failed"));
1474      break;
1475    }
1476  }
1477
1478  xfree(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{
1484  info->item_compare_ic = false;
1485  info->item_compare_lc = false;
1486  info->item_compare_numeric = false;
1487  info->item_compare_numbers = false;
1488  info->item_compare_float = false;
1489  info->item_compare_func = NULL;
1490  info->item_compare_partial = NULL;
1491  info->item_compare_selfdict = NULL;
1492  info->item_compare_keys_ready = false;
1493
1494  if (argvars[1].v_type == VAR_UNKNOWN) {
1495    return OK;
1496  }
1497
1498  // optional second argument: {func}
1499  if (argvars[1].v_type == VAR_FUNC) {
1500    info->item_compare_func = argvars[1].vval.v_string;
1501  } else if (argvars[1].v_type == VAR_PARTIAL) {
1502    info->item_compare_partial = argvars[1].vval.v_partial;
1503  } else {
1504    bool error = false;
1505    int nr = (int)tv_get_number_chk(&argvars[1], &error);
1506    if (error) {
1507      return FAIL;  // type error; errmsg already given
1508    }
1509    if (nr == 1) {
1510      info->item_compare_ic = true;
1511    } else if (argvars[1].v_type != VAR_NUMBER) {
1512      info->item_compare_func = tv_get_string(&argvars[1]);
1513    } else if (nr != 0) {
1514      emsg(_(e_invarg));
1515      return FAIL;
1516    }
1517    if (info->item_compare_func != NULL) {
1518      if (*info->item_compare_func == NUL) {
1519        // empty string means default sort
1520        info->item_compare_func = NULL;
1521      } else if (strcmp(info->item_compare_func, "n") == 0) {
1522        info->item_compare_func = NULL;
1523        info->item_compare_numeric = true;
1524      } else if (strcmp(info->item_compare_func, "N") == 0) {
1525        info->item_compare_func = NULL;
1526        info->item_compare_numbers = true;
1527      } else if (strcmp(info->item_compare_func, "f") == 0) {
1528        info->item_compare_func = NULL;
1529        info->item_compare_float = true;
1530      } else if (strcmp(info->item_compare_func, "i") == 0) {
1531        info->item_compare_func = NULL;
1532        info->item_compare_ic = true;
1533      } else if (strcmp(info->item_compare_func, "l") == 0) {
1534        info->item_compare_func = NULL;
1535        info->item_compare_lc = true;
1536      }
1537    }
1538  }
1539
1540  if (argvars[2].v_type != VAR_UNKNOWN) {
1541    // optional third argument: {dict}
1542    if (tv_check_for_dict_arg(argvars, 2) == FAIL) {
1543      return FAIL;
1544    }
1545    info->item_compare_selfdict = argvars[2].vval.v_dict;
1546  }
1547
1548  return OK;
1549}
1550
1551/// "sort()" or "uniq()" function
1552static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort)
1553{
1554  if (argvars[0].v_type != VAR_LIST) {
1555    semsg(_(e_listarg), sort ? "sort()" : "uniq()");
1556    return;
1557  }
1558
1559  // Pointer to current info struct used in compare function. Save and restore
1560  // the current one for nested calls.
1561  sortinfo_T info;
1562  sortinfo_T *old_sortinfo = sortinfo;
1563  sortinfo = &info;
1564
1565  const char *const arg_errmsg = (sort ? N_("sort() argument") : N_("uniq() argument"));
1566  list_T *const l = argvars[0].vval.v_list;
1567  if (value_check_lock(tv_list_locked(l), arg_errmsg, TV_TRANSLATE)) {
1568    goto theend;
1569  }
1570  tv_list_set_ret(rettv, l);
1571
1572  const int len = tv_list_len(l);
1573  if (len <= 1) {
1574    goto theend;  // short list sorts pretty quickly
1575  }
1576  if (parse_sort_uniq_args(argvars, &info) == FAIL) {
1577    goto theend;
1578  }
1579
1580  if (sort) {
1581    do_sort(l, &info);
1582  } else {
1583    do_uniq(l, &info);
1584  }
1585
1586theend:
1587  sortinfo = old_sortinfo;
1588}
1589
1590/// "sort({list})" function
1591void f_sort(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1592{
1593  do_sort_uniq(argvars, rettv, true);
1594}
1595
1596/// "uniq({list})" function
1597void f_uniq(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1598{
1599  do_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)
1610  FUNC_ATTR_WARN_UNUSED_RESULT
1611{
1612  if (l1 == l2) {
1613    return true;
1614  }
1615  if (tv_list_len(l1) != tv_list_len(l2)) {
1616    return false;
1617  }
1618  if (tv_list_len(l1) == 0) {
1619    // empty and NULL list are considered equal
1620    return true;
1621  }
1622  if (l1 == NULL || l2 == NULL) {
1623    return false;
1624  }
1625
1626  listitem_T *item1 = tv_list_first(l1);
1627  listitem_T *item2 = tv_list_first(l2);
1628  for (; item1 != NULL && item2 != NULL
1629       ; (item1 = TV_LIST_ITEM_NEXT(l1, item1),
1630          item2 = TV_LIST_ITEM_NEXT(l2, item2))) {
1631    if (!tv_equal(TV_LIST_ITEM_TV(item1), TV_LIST_ITEM_TV(item2), ic)) {
1632      return false;
1633    }
1634  }
1635  assert(item1 == NULL && item2 == NULL);
1636  return 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{
1644  if (tv_list_len(l) <= 1) {
1645    return;
1646  }
1647#define SWAP(a, b) \
1648  do { \
1649    tmp = (a); \
1650    (a) = (b); \
1651    (b) = tmp; \
1652  } while (0)
1653  listitem_T *tmp;
1654
1655  SWAP(l->lv_first, l->lv_last);
1656  for (listitem_T *li = l->lv_first; li != NULL; li = li->li_next) {
1657    SWAP(li->li_next, li->li_prev);
1658  }
1659#undef SWAP
1660
1661  l->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)
1674  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
1675{
1676  STATIC_ASSERT(sizeof(n) == sizeof(l->lv_idx),
1677                "n and lv_idx sizes do not match");
1678  if (l == NULL) {
1679    return NULL;
1680  }
1681
1682  n = tv_list_uidx(l, n);
1683  if (n == -1) {
1684    return NULL;
1685  }
1686
1687  int idx;
1688  listitem_T *item;
1689
1690  // When there is a cached index may start search from there.
1691  if (l->lv_idx_item != NULL) {
1692    if (n < l->lv_idx / 2) {
1693      // Closest to the start of the list.
1694      item = l->lv_first;
1695      idx = 0;
1696    } else if (n > (l->lv_idx + l->lv_len) / 2) {
1697      // Closest to the end of the list.
1698      item = l->lv_last;
1699      idx = l->lv_len - 1;
1700    } else {
1701      // Closest to the cached index.
1702      item = l->lv_idx_item;
1703      idx = l->lv_idx;
1704    }
1705  } else {
1706    if (n < l->lv_len / 2) {
1707      // Closest to the start of the list.
1708      item = l->lv_first;
1709      idx = 0;
1710    } else {
1711      // Closest to the end of the list.
1712      item = l->lv_last;
1713      idx = l->lv_len - 1;
1714    }
1715  }
1716
1717  while (n > idx) {
1718    // Search forward.
1719    item = item->li_next;
1720    idx++;
1721  }
1722  while (n < idx) {
1723    // Search backward.
1724    item = item->li_prev;
1725    idx--;
1726  }
1727
1728  assert(idx == n);
1729  // Cache the used index.
1730  l->lv_idx = idx;
1731  l->lv_idx_item = item;
1732
1733  return 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)
1746  FUNC_ATTR_WARN_UNUSED_RESULT
1747{
1748  const listitem_T *const li = tv_list_find(l, n);
1749  if (li == NULL) {
1750    if (ret_error != NULL) {
1751      *ret_error = true;
1752    }
1753    return -1;
1754  }
1755  return 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)
1765  FUNC_ATTR_WARN_UNUSED_RESULT
1766{
1767  const listitem_T *const li = tv_list_find(l, n);
1768  if (li == NULL) {
1769    semsg(_(e_list_index_out_of_range_nr), (int64_t)n);
1770    return NULL;
1771  }
1772  return 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)
1778  FUNC_ATTR_WARN_UNUSED_RESULT
1779{
1780  listitem_T *li = tv_list_find(l, *idx);
1781  if (li != NULL) {
1782    return li;
1783  }
1784
1785  if (*idx < 0) {
1786    *idx = 0;
1787    li = tv_list_find(l, *idx);
1788  }
1789  return 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)
1799  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
1800{
1801  if (l == NULL) {
1802    return -1;
1803  }
1804  int idx = 0;
1805  TV_LIST_ITER_CONST(l, li, {
1806    if (li == item) {
1807      return idx;
1808    }
1809    idx++;
1810  });
1811  return -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)
1821  FUNC_ATTR_NONNULL_ALL
1822{
1823  callback_free(&watcher->callback);
1824  xfree(watcher->key_pattern);
1825  xfree(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,
1835                         const size_t key_pattern_len, Callback callback)
1836  FUNC_ATTR_NONNULL_ARG(2)
1837{
1838  if (dict == NULL) {
1839    return;
1840  }
1841  DictWatcher *const watcher = xmalloc(sizeof(DictWatcher));
1842  watcher->key_pattern = xmemdupz(key_pattern, key_pattern_len);
1843  watcher->key_pattern_len = key_pattern_len;
1844  watcher->callback = callback;
1845  watcher->busy = false;
1846  watcher->needs_free = false;
1847  QUEUE_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)
1857  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1858{
1859  if (cb1->type != cb2->type) {
1860    return false;
1861  }
1862  switch (cb1->type) {
1863  case kCallbackFuncref:
1864    return strequal(cb1->data.funcref, cb2->data.funcref);
1865  case kCallbackPartial:
1866    // FIXME: this is inconsistent with tv_equal but is needed for precision
1867    // maybe change dictwatcheradd to return a watcher id instead?
1868    return cb1->data.partial == cb2->data.partial;
1869  case kCallbackLua:
1870    return cb1->data.luaref == cb2->data.luaref;
1871  case kCallbackExpr:
1872    return strequal(cb1->data.expr, cb2->data.expr);
1873  case kCallbackNone:
1874    return true;
1875  }
1876  abort();
1877  return false;
1878}
1879
1880/// Unref/free callback
1881void callback_free(Callback *callback)
1882  FUNC_ATTR_NONNULL_ALL
1883{
1884  switch (callback->type) {
1885  case kCallbackFuncref:
1886    func_unref(callback->data.funcref);
1887    xfree(callback->data.funcref);
1888    break;
1889  case kCallbackPartial:
1890    partial_unref(callback->data.partial);
1891    break;
1892  case kCallbackLua:
1893    NLUA_CLEAR_REF(callback->data.luaref);
1894    break;
1895  case kCallbackExpr:
1896    xfree(callback->data.expr);
1897    break;
1898  case kCallbackNone:
1899    break;
1900  }
1901  callback->type = kCallbackNone;
1902  callback->data.funcref = NULL;
1903}
1904
1905/// Copy a callback into a typval_T.
1906void callback_put(Callback *cb, typval_T *tv)
1907  FUNC_ATTR_NONNULL_ALL
1908{
1909  switch (cb->type) {
1910  case kCallbackPartial:
1911    tv->v_type = VAR_PARTIAL;
1912    tv->vval.v_partial = cb->data.partial;
1913    cb->data.partial->pt_refcount++;
1914    break;
1915  case kCallbackFuncref:
1916    tv->v_type = VAR_FUNC;
1917    tv->vval.v_string = xstrdup(cb->data.funcref);
1918    func_ref(cb->data.funcref);
1919    break;
1920  case 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
1925  default:
1926    tv->v_type = VAR_SPECIAL;
1927    tv->vval.v_special = kSpecialVarNull;
1928    break;
1929  }
1930}
1931
1932// Copy callback from "src" to "dest", incrementing the refcounts.
1933void callback_copy(Callback *dest, Callback *src)
1934  FUNC_ATTR_NONNULL_ALL
1935{
1936  dest->type = src->type;
1937  switch (src->type) {
1938  case kCallbackPartial:
1939    dest->data.partial = src->data.partial;
1940    dest->data.partial->pt_refcount++;
1941    break;
1942  case kCallbackFuncref:
1943    dest->data.funcref = xstrdup(src->data.funcref);
1944    func_ref(src->data.funcref);
1945    break;
1946  case kCallbackLua:
1947    dest->data.luaref = api_new_luaref(src->data.luaref);
1948    break;
1949  case kCallbackExpr:
1950    dest->data.expr = xstrdup(src->data.expr);
1951    break;
1952  default:
1953    dest->data.funcref = NULL;
1954    break;
1955  }
1956}
1957
1958/// Generate a string description of a callback
1959char *callback_to_string(Callback *cb, Arena *arena)
1960{
1961  if (cb->type == kCallbackLua) {
1962    return nlua_funcref_str(cb->data.luaref, arena, true);
1963  }
1964
1965  const size_t msglen = 100;
1966  char *msg = xmallocz(msglen);
1967
1968  switch (cb->type) {
1969  case kCallbackFuncref:
1970    // TODO(tjdevries): Is this enough space for this?
1971    snprintf(msg, msglen, "<vim function: %s>", cb->data.funcref);
1972    break;
1973  case kCallbackPartial:
1974    snprintf(msg, msglen, "<vim partial: %s>", cb->data.partial->pt_name);
1975    break;
1976  default:
1977    *msg = NUL;
1978    break;
1979  }
1980  return 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,
1992                            const size_t key_pattern_len, Callback callback)
1993  FUNC_ATTR_NONNULL_ARG(2)
1994{
1995  if (dict == NULL) {
1996    return false;
1997  }
1998
1999  QUEUE *w = NULL;
2000  DictWatcher *watcher = NULL;
2001  bool matched = false;
2002  bool queue_is_busy = false;
2003  QUEUE_FOREACH(w, &dict->watchers, {
2004    watcher = tv_dict_watcher_node_data(w);
2005    if (watcher->busy) {
2006      queue_is_busy = true;
2007    }
2008    if (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) {
2011      matched = true;
2012      break;
2013    }
2014  })
2015
2016  if (!matched) {
2017    return false;
2018  }
2019
2020  if (queue_is_busy) {
2021    watcher->needs_free = true;
2022  } else {
2023    QUEUE_REMOVE(w);
2024    tv_dict_watcher_free(watcher);
2025  }
2026  return 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)
2036  FUNC_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.
2041  const size_t len = watcher->key_pattern_len;
2042  if (len && watcher->key_pattern[len - 1] == '*') {
2043    return strncmp(key, watcher->key_pattern, len - 1) == 0;
2044  }
2045  return 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,
2055                            typval_T *const oldtv)
2056  FUNC_ATTR_NONNULL_ARG(1, 2)
2057{
2058  typval_T argv[3];
2059
2060  argv[0].v_type = VAR_DICT;
2061  argv[0].v_lock = VAR_UNLOCKED;
2062  argv[0].vval.v_dict = dict;
2063  argv[1].v_type = VAR_STRING;
2064  argv[1].v_lock = VAR_UNLOCKED;
2065  argv[1].vval.v_string = xstrdup(key);
2066  argv[2].v_type = VAR_DICT;
2067  argv[2].v_lock = VAR_UNLOCKED;
2068  argv[2].vval.v_dict = tv_dict_alloc();
2069  argv[2].vval.v_dict->dv_refcount++;
2070
2071  if (newtv) {
2072    dictitem_T *const v = tv_dict_item_alloc_len(S_LEN("new"));
2073    tv_copy(newtv, &v->di_tv);
2074    tv_dict_add(argv[2].vval.v_dict, v);
2075  }
2076
2077  if (oldtv && oldtv->v_type != VAR_UNKNOWN) {
2078    dictitem_T *const v = tv_dict_item_alloc_len(S_LEN("old"));
2079    tv_copy(oldtv, &v->di_tv);
2080    tv_dict_add(argv[2].vval.v_dict, v);
2081  }
2082
2083  typval_T rettv;
2084
2085  bool any_needs_free = false;
2086  dict->dv_refcount++;
2087  QUEUE *w;
2088  QUEUE_FOREACH(w, &dict->watchers, {
2089    DictWatcher *watcher = tv_dict_watcher_node_data(w);
2090    if (!watcher->busy && tv_dict_watcher_matches(watcher, key)) {
2091      rettv = TV_INITIAL_VALUE;
2092      watcher->busy = true;
2093      callback_call(&watcher->callback, 3, argv, &rettv);
2094      watcher->busy = false;
2095      tv_clear(&rettv);
2096      if (watcher->needs_free) {
2097        any_needs_free = true;
2098      }
2099    }
2100  })
2101  if (any_needs_free) {
2102    QUEUE_FOREACH(w, &dict->watchers, {
2103      DictWatcher *watcher = tv_dict_watcher_node_data(w);
2104      if (watcher->needs_free) {
2105        QUEUE_REMOVE(w);
2106        tv_dict_watcher_free(watcher);
2107      }
2108    })
2109  }
2110  tv_dict_unref(dict);
2111
2112  for (size_t i = 1; i < ARRAY_SIZE(argv); i++) {
2113    tv_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)
2129  FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
2130  FUNC_ATTR_MALLOC
2131{
2132  // Allocating a struct smaller than its static size is UB (#37160)
2133  dictitem_T *const di = xmalloc(MAX(sizeof(dictitem_T),
2134                                     offsetof(dictitem_T, di_key) + key_len + 1));
2135  memcpy(di->di_key, key, key_len);
2136  di->di_key[key_len] = NUL;
2137  di->di_flags = DI_FLAGS_ALLOC;
2138  di->di_tv.v_lock = VAR_UNLOCKED;
2139  di->di_tv.v_type = VAR_UNKNOWN;
2140  return 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)
2152  FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
2153  FUNC_ATTR_MALLOC
2154{
2155  return 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)
2162  FUNC_ATTR_NONNULL_ALL
2163{
2164  tv_clear(&item->di_tv);
2165  if (item->di_flags & DI_FLAGS_ALLOC) {
2166    xfree(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)
2176  FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
2177{
2178  dictitem_T *const new_di = tv_dict_item_alloc(di->di_key);
2179  tv_copy(&di->di_tv, &new_di->di_tv);
2180  return 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)
2188  FUNC_ATTR_NONNULL_ALL
2189{
2190  hashitem_T *const hi = hash_find(&dict->dv_hashtab, item->di_key);
2191  if (HASHITEM_EMPTY(hi)) {
2192    semsg(_(e_intern2), "tv_dict_item_remove()");
2193  } else {
2194    hash_remove(&dict->dv_hashtab, hi);
2195  }
2196  tv_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)
2206  FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT
2207{
2208  dict_T *const d = xcalloc(1, sizeof(dict_T));
2209
2210  // Add the dict to the list of dicts for garbage collection.
2211  if (gc_first_dict != NULL) {
2212    gc_first_dict->dv_used_prev = d;
2213  }
2214  d->dv_used_next = gc_first_dict;
2215  d->dv_used_prev = NULL;
2216  gc_first_dict = d;
2217
2218  hash_init(&d->dv_hashtab);
2219  d->dv_lock = VAR_UNLOCKED;
2220  d->dv_scope = VAR_NO_SCOPE;
2221  d->dv_refcount = 0;
2222  d->dv_copyID = 0;
2223  QUEUE_INIT(&d->watchers);
2224
2225  d->lua_table_ref = LUA_NOREF;
2226
2227  return 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)
2234  FUNC_ATTR_NONNULL_ALL
2235{
2236  // Lock the hashtab, we don't want it to resize while freeing items.
2237  hash_lock(&d->dv_hashtab);
2238  assert(d->dv_hashtab.ht_locked > 0);
2239  HASHTAB_ITER(&d->dv_hashtab, hi, {
2240    // Remove the item before deleting it, just in case there is
2241    // something recursive causing trouble.
2242    dictitem_T *const di = TV_DICT_HI2DI(hi);
2243    hash_remove(&d->dv_hashtab, hi);
2244    tv_dict_item_free(di);
2245  });
2246
2247  while (!QUEUE_EMPTY(&d->watchers)) {
2248    QUEUE *w = QUEUE_HEAD(&d->watchers);
2249    QUEUE_REMOVE(w);
2250    DictWatcher *watcher = tv_dict_watcher_node_data(w);
2251    tv_dict_watcher_free(watcher);
2252  }
2253
2254  hash_clear(&d->dv_hashtab);
2255  d->dv_hashtab.ht_locked--;
2256  hash_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)
2265  FUNC_ATTR_NONNULL_ALL
2266{
2267  // Remove the dict from the list of dicts for garbage collection.
2268  if (d->dv_used_prev == NULL) {
2269    gc_first_dict = d->dv_used_next;
2270  } else {
2271    d->dv_used_prev->dv_used_next = d->dv_used_next;
2272  }
2273  if (d->dv_used_next != NULL) {
2274    d->dv_used_next->dv_used_prev = d->dv_used_prev;
2275  }
2276
2277  NLUA_CLEAR_REF(d->lua_table_ref);
2278  xfree(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)
2287  FUNC_ATTR_NONNULL_ALL
2288{
2289  if (tv_in_free_unref_items) {
2290    return;
2291  }
2292
2293  tv_dict_free_contents(d);
2294  tv_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{
2304  if (d != NULL && --d->dv_refcount <= 0) {
2305    tv_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)
2319  FUNC_ATTR_NONNULL_ARG(2) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2320{
2321  if (d == NULL) {
2322    return NULL;
2323  }
2324  hashitem_T *const hi = (len < 0
2325                          ? hash_find(&d->dv_hashtab, key)
2326                          : hash_find_len(&d->dv_hashtab, key, (size_t)len));
2327  if (HASHITEM_EMPTY(hi)) {
2328    return NULL;
2329  }
2330  return 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)
2340  FUNC_ATTR_NONNULL_ARG(2) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2341{
2342  return 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{
2353  dictitem_T *const di = tv_dict_find(d, key, -1);
2354  if (di == NULL) {
2355    return FAIL;
2356  }
2357
2358  tv_copy(&di->di_tv, rettv);
2359  return 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)
2369  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2370{
2371  return 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)
2382  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2383{
2384  dictitem_T *const di = tv_dict_find(d, key, -1);
2385  if (di == NULL) {
2386    return def;
2387  }
2388  return 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)
2399  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2400{
2401  dictitem_T *const di = tv_dict_find(d, key, -1);
2402  if (di == NULL) {
2403    return def;
2404  }
2405  return tv_get_bool(&di->di_tv);
2406}
2407
2408/// Converts a dict to an environment
2409char **tv_dict_to_env(dict_T *denv)
2410{
2411  size_t env_size = (size_t)tv_dict_len(denv);
2412
2413  size_t i = 0;
2414  char **env = NULL;
2415
2416  // + 1 for NULL
2417  env = xmalloc((env_size + 1) * sizeof(*env));
2418
2419  TV_DICT_ITER(denv, var, {
2420    const char *str = tv_get_string(&var->di_tv);
2421    assert(str);
2422    size_t len = strlen(var->di_key) + strlen(str) + strlen("=") + 1;
2423    env[i] = xmalloc(len);
2424    snprintf(env[i], len, "%s=%s", var->di_key, str);
2425    i++;
2426  });
2427
2428  // must be null terminated
2429  env[env_size] = NULL;
2430  return 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)
2444  FUNC_ATTR_WARN_UNUSED_RESULT
2445{
2446  static char numbuf[NUMBUFLEN];
2447  const char *const s = tv_dict_get_string_buf(d, key, numbuf);
2448  if (save && s != NULL) {
2449    return xstrdup(s);
2450  }
2451  return (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)
2464  FUNC_ATTR_WARN_UNUSED_RESULT
2465{
2466  const dictitem_T *const di = tv_dict_find(d, key, -1);
2467  if (di == NULL) {
2468    return NULL;
2469  }
2470  return 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,
2486                                       const ptrdiff_t key_len, char *const numbuf,
2487                                       const char *const def)
2488  FUNC_ATTR_WARN_UNUSED_RESULT
2489{
2490  const dictitem_T *const di = tv_dict_find(d, key, key_len);
2491  if (di == NULL) {
2492    return def;
2493  }
2494  return 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,
2507                          Callback *const result)
2508  FUNC_ATTR_NONNULL_ARG(2, 4) FUNC_ATTR_WARN_UNUSED_RESULT
2509{
2510  result->type = kCallbackNone;
2511
2512  dictitem_T *const di = tv_dict_find(d, key, key_len);
2513
2514  if (di == NULL) {
2515    return true;
2516  }
2517
2518  if (!tv_is_func(di->di_tv) && di->di_tv.v_type != VAR_STRING) {
2519    emsg(_("E6000: Argument is not a function or function name"));
2520    return false;
2521  }
2522
2523  typval_T tv;
2524  tv_copy(&di->di_tv, &tv);
2525  set_selfdict(&tv, d);
2526  const bool res = callback_from_typval(result, &tv);
2527  tv_clear(&tv);
2528  return 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{
2535  return (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)
2549  FUNC_ATTR_NONNULL_ALL
2550{
2551  if (tv_dict_wrong_func_name(d, &item->di_tv, item->di_key)) {
2552    return FAIL;
2553  }
2554  return 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,
2566                     list_T *const list)
2567  FUNC_ATTR_NONNULL_ALL
2568{
2569  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2570
2571  item->di_tv.v_type = VAR_LIST;
2572  item->di_tv.vval.v_list = list;
2573  if (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.
2576    item->di_tv.vval.v_list = NULL;
2577    tv_dict_item_free(item);
2578    return FAIL;
2579  }
2580  tv_list_ref(list);
2581  return 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{
2593  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2594
2595  tv_copy(tv, &item->di_tv);
2596  if (tv_dict_add(d, item) == FAIL) {
2597    tv_dict_item_free(item);
2598    return FAIL;
2599  }
2600  return 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,
2612                     dict_T *const dict)
2613  FUNC_ATTR_NONNULL_ALL
2614{
2615  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2616
2617  item->di_tv.v_type = VAR_DICT;
2618  item->di_tv.vval.v_dict = dict;
2619  if (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.
2622    item->di_tv.vval.v_dict = NULL;
2623    tv_dict_item_free(item);
2624    return FAIL;
2625  }
2626  dict->dv_refcount++;
2627  return 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,
2639                   const varnumber_T nr)
2640{
2641  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2642
2643  item->di_tv.v_type = VAR_NUMBER;
2644  item->di_tv.vval.v_number = nr;
2645  if (tv_dict_add(d, item) == FAIL) {
2646    tv_dict_item_free(item);
2647    return FAIL;
2648  }
2649  return 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,
2661                      const float_T nr)
2662{
2663  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2664
2665  item->di_tv.v_type = VAR_FLOAT;
2666  item->di_tv.vval.v_float = nr;
2667  if (tv_dict_add(d, item) == FAIL) {
2668    tv_dict_item_free(item);
2669    return FAIL;
2670  }
2671  return 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{
2684  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2685
2686  item->di_tv.v_type = VAR_BOOL;
2687  item->di_tv.vval.v_bool = val;
2688  if (tv_dict_add(d, item) == FAIL) {
2689    tv_dict_item_free(item);
2690    return FAIL;
2691  }
2692  return 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,
2699                    const char *const val)
2700  FUNC_ATTR_NONNULL_ARG(1, 2)
2701{
2702  return 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,
2715                        const char *const val, int len)
2716  FUNC_ATTR_NONNULL_ARG(1, 2)
2717{
2718  char *s = NULL;
2719  if (val != NULL) {
2720    s = (len < 0) ? xstrdup(val) : xstrndup(val, (size_t)len);
2721  }
2722  return 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,
2739                              char *const val)
2740  FUNC_ATTR_NONNULL_ARG(1, 2)
2741{
2742  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2743
2744  item->di_tv.v_type = VAR_STRING;
2745  item->di_tv.vval.v_string = val;
2746  if (tv_dict_add(d, item) == FAIL) {
2747    tv_dict_item_free(item);
2748    return FAIL;
2749  }
2750  return 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,
2762                     ufunc_T *const fp)
2763  FUNC_ATTR_NONNULL_ARG(1, 2, 4)
2764{
2765  dictitem_T *const item = tv_dict_item_alloc_len(key, key_len);
2766
2767  item->di_tv.v_type = VAR_FUNC;
2768  item->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.
2770  func_ref(item->di_tv.vval.v_string);
2771  if (tv_dict_add(d, item) == FAIL) {
2772    tv_dict_item_free(item);
2773    return FAIL;
2774  }
2775  return 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)
2784  FUNC_ATTR_NONNULL_ALL
2785{
2786  hash_lock(&d->dv_hashtab);
2787  assert(d->dv_hashtab.ht_locked > 0);
2788
2789  HASHTAB_ITER(&d->dv_hashtab, hi, {
2790    tv_dict_item_free(TV_DICT_HI2DI(hi));
2791    hash_remove(&d->dv_hashtab, hi);
2792  });
2793
2794  hash_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)
2807  FUNC_ATTR_NONNULL_ALL
2808{
2809  const bool watched = tv_dict_is_watched(d1);
2810  const char *const arg_errmsg = _("extend() argument");
2811  const size_t arg_errmsg_len = strlen(arg_errmsg);
2812
2813  if (*action == 'm') {
2814    hash_lock(&d2->dv_hashtab);  // don't rehash on hash_remove()
2815  }
2816
2817  HASHTAB_ITER(&d2->dv_hashtab, hi2, {
2818    dictitem_T *const di2 = TV_DICT_HI2DI(hi2);
2819    dictitem_T *const di1 = tv_dict_find(d1, di2->di_key, -1);
2820    // Check the key to be valid when adding to any scope.
2821    if (d1->dv_scope != VAR_NO_SCOPE && !valid_varname(di2->di_key)) {
2822      break;
2823    }
2824    if (di1 == NULL) {
2825      if (*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.
2828        dictitem_T *const new_di = di2;
2829        if (tv_dict_add(d1, new_di) == OK) {
2830          hash_remove(&d2->dv_hashtab, hi2);
2831          tv_dict_watcher_notify(d1, new_di->di_key, &new_di->di_tv, NULL);
2832        }
2833      } else {
2834        dictitem_T *const new_di = tv_dict_item_copy(di2);
2835        if (tv_dict_add(d1, new_di) == FAIL) {
2836          tv_dict_item_free(new_di);
2837        } else if (watched) {
2838          tv_dict_watcher_notify(d1, new_di->di_key, &new_di->di_tv, NULL);
2839        }
2840      }
2841    } else if (*action == 'e') {
2842      semsg(_("E737: Key already exists: %s"), di2->di_key);
2843      break;
2844    } else if (*action == 'f' && di2 != di1) {
2845      typval_T oldtv;
2846
2847      if (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)) {
2849        break;
2850      }
2851      // Disallow replacing a builtin function.
2852      if (tv_dict_wrong_func_name(d1, &di2->di_tv, di2->di_key)) {
2853        break;
2854      }
2855
2856      if (watched) {
2857        tv_copy(&di1->di_tv, &oldtv);
2858      }
2859
2860      tv_clear(&di1->di_tv);
2861      tv_copy(&di2->di_tv, &di1->di_tv);
2862
2863      if (watched) {
2864        tv_dict_watcher_notify(d1, di1->di_key, &di1->di_tv, &oldtv);
2865        tv_clear(&oldtv);
2866      }
2867    }
2868  });
2869
2870  if (*action == 'm') {
2871    hash_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)
2883  FUNC_ATTR_WARN_UNUSED_RESULT
2884{
2885  if (d1 == d2) {
2886    return true;
2887  }
2888  if (tv_dict_len(d1) != tv_dict_len(d2)) {
2889    return false;
2890  }
2891  if (tv_dict_len(d1) == 0) {
2892    // empty and NULL dicts are considered equal
2893    return true;
2894  }
2895  if (d1 == NULL || d2 == NULL) {
2896    return false;
2897  }
2898
2899  TV_DICT_ITER(d1, di1, {
2900    dictitem_T *const di2 = tv_dict_find(d2, di1->di_key, -1);
2901    if (di2 == NULL) {
2902      return false;
2903    }
2904    if (!tv_equal(&di1->di_tv, &di2->di_tv, ic)) {
2905      return false;
2906    }
2907  });
2908  return 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,
2922                     const int copyID)
2923{
2924  if (orig == NULL) {
2925    return NULL;
2926  }
2927
2928  dict_T *copy = tv_dict_alloc();
2929  if (copyID != 0) {
2930    orig->dv_copyID = copyID;
2931    orig->dv_copydict = copy;
2932  }
2933  TV_DICT_ITER(orig, di, {
2934    if (got_int) {
2935      break;
2936    }
2937    dictitem_T *new_di;
2938    if (conv == NULL || conv->vc_type == CONV_NONE) {
2939      new_di = tv_dict_item_alloc(di->di_key);
2940    } else {
2941      size_t len = strlen(di->di_key);
2942      char *const key = string_convert(conv, di->di_key, &len);
2943      if (key == NULL) {
2944        new_di = tv_dict_item_alloc_len(di->di_key, len);
2945      } else {
2946        new_di = tv_dict_item_alloc_len(key, len);
2947        xfree(key);
2948      }
2949    }
2950    if (deep) {
2951      if (var_item_copy(conv, &di->di_tv, &new_di->di_tv, deep,
2952                        copyID) == FAIL) {
2953        xfree(new_di);
2954        break;
2955      }
2956    } else {
2957      tv_copy(&di->di_tv, &new_di->di_tv);
2958    }
2959    if (tv_dict_add(copy, new_di) == FAIL) {
2960      tv_dict_item_free(new_di);
2961      break;
2962    }
2963  });
2964
2965  copy->dv_refcount++;
2966  if (got_int) {
2967    tv_dict_unref(copy);
2968    copy = NULL;
2969  }
2970
2971  return 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)
2980  FUNC_ATTR_NONNULL_ALL
2981{
2982  TV_DICT_ITER(dict, di, {
2983    di->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)
2996  FUNC_ATTR_NONNULL_RET
2997{
2998  blob_T *const blob = xcalloc(1, sizeof(blob_T));
2999  ga_init(&blob->bv_ga, 1, 100);
3000  return 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)
3007  FUNC_ATTR_NONNULL_ALL
3008{
3009  ga_clear(&b->bv_ga);
3010  xfree(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{
3020  if (b != NULL && --b->bv_refcount <= 0) {
3021    tv_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)
3034  FUNC_ATTR_WARN_UNUSED_RESULT
3035{
3036  const int len1 = tv_blob_len(b1);
3037  const int len2 = tv_blob_len(b2);
3038
3039  // empty and NULL are considered the same
3040  if (len1 == 0 && len2 == 0) {
3041    return true;
3042  }
3043  if (b1 == b2) {
3044    return true;
3045  }
3046  if (len1 != len2) {
3047    return false;
3048  }
3049
3050  for (int i = 0; i < b1->bv_ga.ga_len; i++) {
3051    if (tv_blob_get(b1, i) != tv_blob_get(b2, i)) {
3052      return false;
3053    }
3054  }
3055  return 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,
3061                         bool 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.
3065  if (n1 < 0) {
3066    n1 = len + n1;
3067    if (n1 < 0) {
3068      n1 = 0;
3069    }
3070  }
3071  if (n2 < 0) {
3072    n2 = len + n2;
3073  } else if (n2 >= len) {
3074    n2 = len - (exclusive ? 0 : 1);
3075  }
3076  if (exclusive) {
3077    n2--;
3078  }
3079  if (n1 >= len || n2 < 0 || n1 > n2) {
3080    tv_clear(rettv);
3081    rettv->v_type = VAR_BLOB;
3082    rettv->vval.v_blob = NULL;
3083  } else {
3084    blob_T *const new_blob = tv_blob_alloc();
3085    ga_grow(&new_blob->bv_ga, (int)(n2 - n1 + 1));
3086    new_blob->bv_ga.ga_len = (int)(n2 - n1 + 1);
3087    for (int i = (int)n1; i <= (int)n2; i++) {
3088      tv_blob_set(new_blob, i - (int)n1, tv_blob_get(rettv->vval.v_blob, i));
3089    }
3090    tv_clear(rettv);
3091    tv_blob_set_ret(rettv, new_blob);
3092  }
3093
3094  return 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.
3103  if (idx < 0) {
3104    idx = len + idx;
3105  }
3106  if (idx < len && idx >= 0) {
3107    const int v = (int)tv_blob_get(rettv->vval.v_blob, (int)idx);
3108    tv_clear(rettv);
3109    rettv->v_type = VAR_NUMBER;
3110    rettv->vval.v_number = v;
3111  } else {
3112    semsg(_(e_blobidx), idx);
3113    return FAIL;
3114  }
3115
3116  return OK;
3117}
3118
3119int tv_blob_slice_or_index(const blob_T *blob, bool is_range, varnumber_T n1, varnumber_T n2,
3120                           bool exclusive, typval_T *rettv)
3121{
3122  int len = tv_blob_len(rettv->vval.v_blob);
3123
3124  if (is_range) {
3125    return tv_blob_slice(blob, len, n1, n2, exclusive, rettv);
3126  } else {
3127    return 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{
3134  if (n1 < 0 || n1 > bloblen) {
3135    if (!quiet) {
3136      semsg(_(e_blobidx), n1);
3137    }
3138    return FAIL;
3139  }
3140  return 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{
3146  if (n2 < 0 || n2 >= bloblen || n2 < n1) {
3147    if (!quiet) {
3148      semsg(_(e_blobidx), n2);
3149    }
3150    return FAIL;
3151  }
3152  return 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{
3160  if (n2 - n1 + 1 != tv_blob_len(src->vval.v_blob)) {
3161    emsg(_("E972: Blob value does not have the right number of bytes"));
3162    return FAIL;
3163  }
3164
3165  for (int il = (int)n1, ir = 0; il <= (int)n2; il++) {
3166    tv_blob_set(dest, il, tv_blob_get(src->vval.v_blob, ir++));
3167  }
3168  return 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{
3175  garray_T *gap = &blob->bv_ga;
3176
3177  // Allow for appending a byte.  Setting a byte beyond
3178  // the end is an error otherwise.
3179  if (idx <= gap->ga_len) {
3180    if (idx == gap->ga_len) {
3181      ga_grow(gap, 1);
3182      gap->ga_len++;
3183    }
3184    tv_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{
3191  blob_T *const b = argvars[0].vval.v_blob;
3192
3193  if (b != NULL && value_check_lock(b->bv_lock, arg_errmsg, TV_TRANSLATE)) {
3194    return;
3195  }
3196
3197  bool error = false;
3198  int64_t idx = tv_get_number_chk(&argvars[1], &error);
3199
3200  if (!error) {
3201    const int len = tv_blob_len(b);
3202
3203    if (idx < 0) {
3204      // count from the end
3205      idx = len + idx;
3206    }
3207    if (idx < 0 || idx >= len) {
3208      semsg(_(e_blobidx), idx);
3209      return;
3210    }
3211    if (argvars[2].v_type == VAR_UNKNOWN) {
3212      // Remove one item, return its value.
3213      uint8_t *const p = (uint8_t *)b->bv_ga.ga_data;
3214      rettv->vval.v_number = (varnumber_T)(*(p + idx));
3215      memmove(p + idx, p + idx + 1, (size_t)(len - idx - 1));
3216      b->bv_ga.ga_len--;
3217    } else {
3218      // Remove range of items, return blob with values.
3219      int64_t end = tv_get_number_chk(&argvars[2], &error);
3220      if (error) {
3221        return;
3222      }
3223      if (end < 0) {
3224        // count from the end
3225        end = len + end;
3226      }
3227      if (end >= len || idx > end) {
3228        semsg(_(e_blobidx), end);
3229        return;
3230      }
3231      blob_T *const blob = tv_blob_alloc();
3232      blob->bv_ga.ga_len = (int)(end - idx + 1);
3233      ga_grow(&blob->bv_ga, (int)(end - idx + 1));
3234
3235      uint8_t *const p = (uint8_t *)b->bv_ga.ga_data;
3236      memmove(blob->bv_ga.ga_data, p + idx, (size_t)(end - idx + 1));
3237      tv_blob_set_ret(rettv, blob);
3238
3239      if (len - end - 1 > 0) {
3240        memmove(p + idx, p + end + 1, (size_t)(len - end - 1));
3241      }
3242      b->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{
3250  tv_list_alloc_ret(rettv, kListLenMayKnow);
3251
3252  if (tv_check_for_blob_arg(argvars, 0) == FAIL) {
3253    return;
3254  }
3255
3256  blob_T *const blob = argvars->vval.v_blob;
3257  list_T *const l = rettv->vval.v_list;
3258  for (int i = 0; i < tv_blob_len(blob); i++) {
3259    tv_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{
3266  blob_T *blob = tv_blob_alloc_ret(rettv);
3267
3268  if (tv_check_for_list_arg(argvars, 0) == FAIL) {
3269    return;
3270  }
3271
3272  list_T *const l = argvars->vval.v_list;
3273  if (l == NULL) {
3274    return;
3275  }
3276
3277  ga_grow(&blob->bv_ga, tv_list_len(l));
3278
3279  TV_LIST_ITER_CONST(l, li, {
3280    bool error = false;
3281    varnumber_T n = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error);
3282    if (error || n < 0 || n > 255) {
3283      if (!error) {
3284        semsg(_(e_invalid_value_for_blob_nr), (int)n);
3285      }
3286      ga_clear(&blob->bv_ga);
3287      return;
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)
3309  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
3310{
3311  list_T *const l = tv_list_alloc(len);
3312  tv_list_set_ret(ret_tv, l);
3313  ret_tv->v_lock = VAR_UNLOCKED;
3314  return l;
3315}
3316
3317dict_T *tv_dict_alloc_lock(VarLockStatus lock)
3318  FUNC_ATTR_NONNULL_RET
3319{
3320  dict_T *const d = tv_dict_alloc();
3321  d->dv_lock = lock;
3322  return 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)
3331  FUNC_ATTR_NONNULL_ALL
3332{
3333  dict_T *const d = tv_dict_alloc_lock(VAR_UNLOCKED);
3334  tv_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{
3345  if (tv_check_for_dict_arg(argvars, 0) == FAIL) {
3346    tv_list_alloc_ret(rettv, 0);
3347    return;
3348  }
3349
3350  dict_T *d = argvars[0].vval.v_dict;
3351  tv_list_alloc_ret(rettv, tv_dict_len(d));
3352  if (d == NULL) {
3353    // NULL dict behaves like an empty dict
3354    return;
3355  }
3356
3357  TV_DICT_ITER(d, di, {
3358    typval_T tv_item = { .v_lock = VAR_UNLOCKED };
3359
3360    switch (what) {
3361      case kDict2ListKeys:
3362        tv_item.v_type = VAR_STRING;
3363        tv_item.vval.v_string = xstrdup(di->di_key);
3364        break;
3365      case kDict2ListValues:
3366        tv_copy(&di->di_tv, &tv_item);
3367        break;
3368      case kDict2ListItems: {
3369        // items()
3370        list_T *const sub_l = tv_list_alloc(2);
3371        tv_item.v_type = VAR_LIST;
3372        tv_item.vval.v_list = sub_l;
3373        tv_list_ref(sub_l);
3374        tv_list_append_string(sub_l, di->di_key, -1);
3375        tv_list_append_tv(sub_l, &di->di_tv);
3376        break;
3377      }
3378    }
3379
3380    tv_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{
3387  if (argvars[0].v_type == VAR_STRING) {
3388    tv_string2items(argvars, rettv);
3389  } else if (argvars[0].v_type == VAR_LIST) {
3390    tv_list2items(argvars, rettv);
3391  } else if (argvars[0].v_type == VAR_BLOB) {
3392    tv_blob2items(argvars, rettv);
3393  } else if (argvars[0].v_type == VAR_DICT) {
3394    tv_dict2items(argvars, rettv);
3395  } else {
3396    semsg(_(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{
3403  tv_dict2list(argvars, rettv, kDict2ListKeys);
3404}
3405
3406/// "values(dict)" function
3407void f_values(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3408{
3409  tv_dict2list(argvars, rettv, kDict2ListValues);
3410}
3411
3412/// "has_key()" function
3413void f_has_key(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3414{
3415  if (tv_check_for_dict_arg(argvars, 0) == FAIL) {
3416    return;
3417  }
3418
3419  if (argvars[0].vval.v_dict == NULL) {
3420    return;
3421  }
3422
3423  rettv->vval.v_number = tv_dict_find(argvars[0].vval.v_dict,
3424                                      tv_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{
3431  dict_T *d;
3432  if (argvars[2].v_type != VAR_UNKNOWN) {
3433    semsg(_(e_toomanyarg), "remove()");
3434  } else if ((d = argvars[0].vval.v_dict) != NULL
3435             && !value_check_lock(d->dv_lock, arg_errmsg, TV_TRANSLATE)) {
3436    const char *key = tv_get_string_chk(&argvars[1]);
3437    if (key != NULL) {
3438      dictitem_T *di = tv_dict_find(d, key, -1);
3439      if (di == NULL) {
3440        semsg(_(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;
3444        di->di_tv = TV_INITIAL_VALUE;
3445        tv_dict_item_remove(d, di);
3446        if (tv_dict_is_watched(d)) {
3447          tv_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)
3460  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
3461{
3462  blob_T *const b = tv_blob_alloc();
3463  tv_blob_set_ret(ret_tv, b);
3464  return 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)
3472  FUNC_ATTR_NONNULL_ARG(2)
3473{
3474  to->v_type = VAR_BLOB;
3475  to->v_lock = VAR_UNLOCKED;
3476  if (from == NULL) {
3477    to->vval.v_blob = NULL;
3478  } else {
3479    tv_blob_alloc_ret(to);
3480    int len = from->bv_ga.ga_len;
3481
3482    if (len > 0) {
3483      to->vval.v_blob->bv_ga.ga_data = xmemdup(from->bv_ga.ga_data, (size_t)len);
3484    }
3485    to->vval.v_blob->bv_ga.ga_len = len;
3486    to->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)
3540  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ARG(1)
3541{
3542  tv->v_lock = VAR_UNLOCKED;
3543  if (tv->v_type == VAR_PARTIAL) {
3544    partial_T *const pt_ = tv->vval.v_partial;
3545    if (pt_ != NULL && pt_->pt_refcount > 1) {
3546      pt_->pt_refcount--;
3547      tv->vval.v_partial = NULL;
3548      return OK;
3549    }
3550  } else {
3551    func_unref(fun);
3552    if (fun != tv_empty_string) {
3553      xfree(fun);
3554    }
3555    tv->vval.v_string = NULL;
3556  }
3557  return 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)
3570  FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL
3571{
3572  if (tv->v_type == VAR_PARTIAL) {
3573    partial_T *const pt = tv->vval.v_partial;
3574    if (pt == NULL) {
3575      return;
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.
3579    assert(pt->pt_dict == NULL || pt->pt_dict->dv_copyID == copyID);
3580    pt->pt_dict = NULL;
3581    // As well as all arguments.
3582    pt->pt_argc = 0;
3583    assert(pt->pt_refcount <= 1);
3584    partial_unref(pt);
3585    tv->vval.v_partial = NULL;
3586    assert(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)
3599  FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ARG(2)
3600{
3601  tv_dict_unref(*dictp);
3602  *dictp = NULL;
3603  if (tv != NULL) {
3604    tv->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,
3614                                                      MPConvStackVal *const mpsv)
3615  FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_WARN_UNUSED_RESULT
3616{
3617  assert(tv != NULL);
3618  tv->v_lock = VAR_UNLOCKED;
3619  if (tv->vval.v_list->lv_refcount > 1) {
3620    tv->vval.v_list->lv_refcount--;
3621    tv->vval.v_list = NULL;
3622    mpsv->data.l.li = NULL;
3623    return OK;
3624  }
3625  return 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)
3639  FUNC_ATTR_ALWAYS_INLINE
3640{
3641  if (tv == NULL) {
3642    return;
3643  }
3644  assert(tv->v_type == VAR_LIST);
3645  list_T *const list = tv->vval.v_list;
3646  tv_list_unref(list);
3647  tv->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,
3652                                                      const void *const nodictvar,
3653                                                      MPConvStackVal *const mpsv)
3654  FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_WARN_UNUSED_RESULT
3655{
3656  if (tv != NULL) {
3657    tv->v_lock = VAR_UNLOCKED;
3658  }
3659  if ((const void *)dictp != nodictvar && (*dictp)->dv_refcount > 1) {
3660    (*dictp)->dv_refcount--;
3661    *dictp = NULL;
3662    mpsv->data.d.todo = 0;
3663    return OK;
3664  }
3665  return 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,
3683                                          const void *const nodictvar)
3684  FUNC_ATTR_ALWAYS_INLINE
3685{
3686  if ((const void *)dictp != nodictvar) {
3687    tv_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{
3742  if (tv == NULL || tv->v_type == VAR_UNKNOWN) {
3743    return;
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.
3752  const int evn_ret = encode_vim_to_nothing(NULL, tv, "tv_clear() argument");
3753  (void)evn_ret;
3754  assert(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{
3764  if (tv == NULL) {
3765    return;
3766  }
3767
3768  switch (tv->v_type) {
3769  case VAR_PARTIAL:
3770    partial_unref(tv->vval.v_partial);
3771    break;
3772  case VAR_FUNC:
3773    func_unref(tv->vval.v_string);
3774    FALLTHROUGH;
3775  case VAR_STRING:
3776    xfree(tv->vval.v_string);
3777    break;
3778  case VAR_BLOB:
3779    tv_blob_unref(tv->vval.v_blob);
3780    break;
3781  case VAR_LIST:
3782    tv_list_unref(tv->vval.v_list);
3783    break;
3784  case VAR_DICT:
3785    tv_dict_unref(tv->vval.v_dict);
3786    break;
3787  case VAR_BOOL:
3788  case VAR_SPECIAL:
3789  case VAR_NUMBER:
3790  case VAR_FLOAT:
3791  case VAR_UNKNOWN:
3792    break;
3793  }
3794  xfree(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{
3811  to->v_type = from->v_type;
3812  to->v_lock = VAR_UNLOCKED;
3813  memmove(&to->vval, &from->vval, sizeof(to->vval));
3814  switch (from->v_type) {
3815  case VAR_NUMBER:
3816  case VAR_FLOAT:
3817  case VAR_BOOL:
3818  case VAR_SPECIAL:
3819    break;
3820  case VAR_STRING:
3821  case VAR_FUNC:
3822    if (from->vval.v_string != NULL) {
3823      to->vval.v_string = xstrdup(from->vval.v_string);
3824      if (from->v_type == VAR_FUNC) {
3825        func_ref(to->vval.v_string);
3826      }
3827    }
3828    break;
3829  case VAR_PARTIAL:
3830    if (to->vval.v_partial != NULL) {
3831      to->vval.v_partial->pt_refcount++;
3832    }
3833    break;
3834  case VAR_BLOB:
3835    if (from->vval.v_blob != NULL) {
3836      to->vval.v_blob->bv_refcount++;
3837    }
3838    break;
3839  case VAR_LIST:
3840    tv_list_ref(to->vval.v_list);
3841    break;
3842  case VAR_DICT:
3843    if (from->vval.v_dict != NULL) {
3844      to->vval.v_dict->dv_refcount++;
3845    }
3846    break;
3847  case VAR_UNKNOWN:
3848    semsg(_(e_intern2), "tv_copy(UNKNOWN)");
3849    break;
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)
3863  FUNC_ATTR_NONNULL_ALL
3864{
3865  // TODO(ZyX-I): Make this not recursive
3866  static int recurse = 0;
3867
3868  if (recurse >= DICT_MAXNEST) {
3869    emsg(_(e_variable_nested_too_deep_for_unlock));
3870    return;
3871  }
3872  if (deep == 0) {
3873    return;
3874  }
3875  recurse++;
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)
3886  CHANGE_LOCK(lock, tv->v_lock);
3887
3888  switch (tv->v_type) {
3889  case VAR_BLOB: {
3890    blob_T *const b = tv->vval.v_blob;
3891    if (b != NULL && !(check_refcount && b->bv_refcount > 1)) {
3892      CHANGE_LOCK(lock, b->bv_lock);
3893    }
3894    break;
3895  }
3896  case VAR_LIST: {
3897    list_T *const l = tv->vval.v_list;
3898    if (l != NULL && !(check_refcount && l->lv_refcount > 1)) {
3899      CHANGE_LOCK(lock, l->lv_lock);
3900      if (deep < 0 || deep > 1) {
3901        // Recursive: lock/unlock the items the List contains.
3902        TV_LIST_ITER(l, li, {
3903            tv_item_lock(TV_LIST_ITEM_TV(li), deep - 1, lock, check_refcount);
3904          });
3905      }
3906    }
3907    break;
3908  }
3909  case VAR_DICT: {
3910    dict_T *const d = tv->vval.v_dict;
3911    if (d != NULL && !(check_refcount && d->dv_refcount > 1)) {
3912      CHANGE_LOCK(lock, d->dv_lock);
3913      if (deep < 0 || deep > 1) {
3914        // recursive: lock/unlock the items the List contains
3915        TV_DICT_ITER(d, di, {
3916            tv_item_lock(&di->di_tv, deep - 1, lock, check_refcount);
3917          });
3918      }
3919    }
3920    break;
3921  }
3922  case VAR_NUMBER:
3923  case VAR_FLOAT:
3924  case VAR_STRING:
3925  case VAR_FUNC:
3926  case VAR_PARTIAL:
3927  case VAR_BOOL:
3928  case VAR_SPECIAL:
3929    break;
3930  case VAR_UNKNOWN:
3931    abort();
3932  }
3933#undef CHANGE_LOCK
3934  recurse--;
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)
3945  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3946{
3947  return ((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)
3974  FUNC_ATTR_WARN_UNUSED_RESULT
3975{
3976  VarLockStatus lock = VAR_UNLOCKED;
3977
3978  switch (tv->v_type) {
3979  case VAR_BLOB:
3980    if (tv->vval.v_blob != NULL) {
3981      lock = tv->vval.v_blob->bv_lock;
3982    }
3983    break;
3984  case VAR_LIST:
3985    if (tv->vval.v_list != NULL) {
3986      lock = tv->vval.v_list->lv_lock;
3987    }
3988    break;
3989  case VAR_DICT:
3990    if (tv->vval.v_dict != NULL) {
3991      lock = tv->vval.v_dict->dv_lock;
3992    }
3993    break;
3994  default:
3995    break;
3996  }
3997  return 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{
4004  const char *error_message = NULL;
4005  switch (lock) {
4006  case VAR_UNLOCKED:
4007    return false;
4008  case VAR_LOCKED:
4009    error_message = name == NULL ? N_(e_value_is_locked)
4010                                 : N_(e_value_is_locked_str);
4011    break;
4012  case VAR_FIXED:
4013    error_message = name == NULL ? N_(e_cannot_change_value)
4014                                 : N_(e_cannot_change_value_of_str);
4015    break;
4016  }
4017  assert(error_message != NULL);
4018
4019  if (name == NULL) {
4020    emsg(_(error_message));
4021  } else {
4022    if (name_len == TV_TRANSLATE) {
4023      name = _(name);
4024      name_len = strlen(name);
4025    } else if (name_len == TV_CSTRING) {
4026      name_len = strlen(name);
4027    }
4028    semsg(_(error_message), (int)name_len, name);
4029  }
4030
4031  return 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)
4051  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
4052{
4053  // TODO(ZyX-I): Make this not recursive
4054  static int recursive_cnt = 0;  // Catch recursive loops.
4055
4056  if (!(tv_is_func(*tv1) && tv_is_func(*tv2)) && tv1->v_type != tv2->v_type) {
4057    return 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.
4066  if (recursive_cnt == 0) {
4067    tv_equal_recurse_limit = 1000;
4068  }
4069  if (recursive_cnt >= tv_equal_recurse_limit) {
4070    tv_equal_recurse_limit--;
4071    return true;
4072  }
4073
4074  switch (tv1->v_type) {
4075  case VAR_LIST: {
4076    recursive_cnt++;
4077    const bool r = tv_list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
4078    recursive_cnt--;
4079    return r;
4080  }
4081  case VAR_DICT: {
4082    recursive_cnt++;
4083    const bool r = tv_dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
4084    recursive_cnt--;
4085    return r;
4086  }
4087  case VAR_PARTIAL:
4088  case VAR_FUNC: {
4089    if ((tv1->v_type == VAR_PARTIAL && tv1->vval.v_partial == NULL)
4090        || (tv2->v_type == VAR_PARTIAL && tv2->vval.v_partial == NULL)) {
4091      return false;
4092    }
4093    recursive_cnt++;
4094    const bool r = func_equal(tv1, tv2, ic);
4095    recursive_cnt--;
4096    return r;
4097  }
4098  case VAR_BLOB:
4099    return tv_blob_equal(tv1->vval.v_blob, tv2->vval.v_blob);
4100  case VAR_NUMBER:
4101    return tv1->vval.v_number == tv2->vval.v_number;
4102  case VAR_FLOAT:
4103    return tv1->vval.v_float == tv2->vval.v_float;
4104  case VAR_STRING: {
4105    char buf1[NUMBUFLEN];
4106    char buf2[NUMBUFLEN];
4107    const char *s1 = tv_get_string_buf(tv1, buf1);
4108    const char *s2 = tv_get_string_buf(tv2, buf2);
4109    return mb_strcmp_ic(ic, s1, s2) == 0;
4110  }
4111  case VAR_BOOL:
4112    return tv1->vval.v_bool == tv2->vval.v_bool;
4113  case VAR_SPECIAL:
4114    return tv1->vval.v_special == tv2->vval.v_special;
4115  case 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.
4118    return false;
4119  }
4120
4121  abort();
4122  return 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)
4137  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
4138{
4139  switch (tv->v_type) {
4140  case VAR_NUMBER:
4141  case VAR_STRING:
4142    return true;
4143  case VAR_FLOAT:
4144    emsg(_("E805: Expected a Number or a String, Float found"));
4145    return false;
4146  case VAR_PARTIAL:
4147  case VAR_FUNC:
4148    emsg(_("E703: Expected a Number or a String, Funcref found"));
4149    return false;
4150  case VAR_LIST:
4151    emsg(_("E745: Expected a Number or a String, List found"));
4152    return false;
4153  case VAR_DICT:
4154    emsg(_("E728: Expected a Number or a String, Dictionary found"));
4155    return false;
4156  case VAR_BLOB:
4157    emsg(_("E974: Expected a Number or a String, Blob found"));
4158    return false;
4159  case VAR_BOOL:
4160    emsg(_("E5299: Expected a Number or a String, Boolean found"));
4161    return false;
4162  case VAR_SPECIAL:
4163    emsg(_("E5300: Expected a Number or a String"));
4164    return false;
4165  case VAR_UNKNOWN:
4166    semsg(_(e_intern2), "tv_check_str_or_nr(UNKNOWN)");
4167    return false;
4168  }
4169  abort();
4170  return 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)
4196  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4197{
4198  switch (tv->v_type) {
4199  case VAR_NUMBER:
4200  case VAR_BOOL:
4201  case VAR_SPECIAL:
4202  case VAR_STRING:
4203    return true;
4204  case VAR_FUNC:
4205  case VAR_PARTIAL:
4206  case VAR_LIST:
4207  case VAR_DICT:
4208  case VAR_FLOAT:
4209  case VAR_BLOB:
4210  case VAR_UNKNOWN:
4211    emsg(_(num_errors[tv->v_type]));
4212    return false;
4213  }
4214  abort();
4215  return 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)
4240  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4241{
4242  switch (tv->v_type) {
4243  case VAR_NUMBER:
4244  case VAR_BOOL:
4245  case VAR_SPECIAL:
4246  case VAR_STRING:
4247  case VAR_FLOAT:
4248    return true;
4249  case VAR_PARTIAL:
4250  case VAR_FUNC:
4251  case VAR_LIST:
4252  case VAR_DICT:
4253  case VAR_BLOB:
4254  case VAR_UNKNOWN:
4255    emsg(_(str_errors[tv->v_type]));
4256    return false;
4257  }
4258  abort();
4259  return 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)
4274  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4275{
4276  bool error = false;
4277  return 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)
4295  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
4296{
4297  switch (tv->v_type) {
4298  case VAR_FUNC:
4299  case VAR_PARTIAL:
4300  case VAR_LIST:
4301  case VAR_DICT:
4302  case VAR_BLOB:
4303  case VAR_FLOAT:
4304    emsg(_(num_errors[tv->v_type]));
4305    break;
4306  case VAR_NUMBER:
4307    return tv->vval.v_number;
4308  case VAR_STRING: {
4309    varnumber_T n = 0;
4310    if (tv->vval.v_string != NULL) {
4311      vim_str2nr(tv->vval.v_string, NULL, NULL, STR2NR_ALL, &n, NULL, 0, false, NULL);
4312    }
4313    return n;
4314  }
4315  case VAR_BOOL:
4316    return tv->vval.v_bool == kBoolVarTrue ? 1 : 0;
4317  case VAR_SPECIAL:
4318    return 0;
4319  case VAR_UNKNOWN:
4320    semsg(_(e_intern2), "tv_get_number(UNKNOWN)");
4321    break;
4322  }
4323  if (ret_error != NULL) {
4324    *ret_error = true;
4325  }
4326  return (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)
4339  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4340{
4341  return tv_get_number_chk(tv, NULL);
4342}
4343
4344varnumber_T tv_get_bool_chk(const typval_T *const tv, bool *const ret_error)
4345  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
4346{
4347  return 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)
4358  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4359{
4360  const int did_emsg_before = did_emsg;
4361  linenr_T lnum = (linenr_T)tv_get_number_chk(tv, NULL);
4362  if (lnum <= 0 && did_emsg_before == did_emsg && tv->v_type != VAR_NUMBER) {
4363    int fnum;
4364    // No valid number, try using same function as line() does.
4365    pos_T *const fp = var2fpos(tv, true, &fnum, false, curwin);
4366    if (fp != NULL) {
4367      lnum = fp->lnum;
4368    }
4369  }
4370  return 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)
4384  FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT
4385{
4386  if (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) {
4391    return buf->b_ml.ml_line_count;
4392  }
4393  return (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)
4404  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4405{
4406  switch (tv->v_type) {
4407  case VAR_NUMBER:
4408    return (float_T)(tv->vval.v_number);
4409  case VAR_FLOAT:
4410    return tv->vval.v_float;
4411  case VAR_PARTIAL:
4412  case VAR_FUNC:
4413    emsg(_("E891: Using a Funcref as a Float"));
4414    break;
4415  case VAR_STRING:
4416    emsg(_("E892: Using a String as a Float"));
4417    break;
4418  case VAR_LIST:
4419    emsg(_("E893: Using a List as a Float"));
4420    break;
4421  case VAR_DICT:
4422    emsg(_("E894: Using a Dictionary as a Float"));
4423    break;
4424  case VAR_BOOL:
4425    emsg(_("E362: Using a boolean value as a Float"));
4426    break;
4427  case VAR_SPECIAL:
4428    emsg(_("E907: Using a special value as a Float"));
4429    break;
4430  case VAR_BLOB:
4431    emsg(_("E975: Using a Blob as a Float"));
4432    break;
4433  case VAR_UNKNOWN:
4434    semsg(_(e_intern2), "tv_get_float(UNKNOWN)");
4435    break;
4436  }
4437  return 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)
4442  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4443{
4444  if (args[idx].v_type != VAR_STRING) {
4445    semsg(_(e_string_required_for_argument_nr), idx + 1);
4446    return FAIL;
4447  }
4448  return 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)
4453  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4454{
4455  if (tv_check_for_string_arg(args, idx) == FAIL) {
4456    return FAIL;
4457  }
4458  if (args[idx].vval.v_string == NULL || *args[idx].vval.v_string == NUL) {
4459    semsg(_(e_non_empty_string_required_for_argument_nr), idx + 1);
4460    return FAIL;
4461  }
4462  return 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)
4467  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4468{
4469  return (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)
4475  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4476{
4477  if (args[idx].v_type != VAR_NUMBER) {
4478    semsg(_(e_number_required_for_argument_nr), idx + 1);
4479    return FAIL;
4480  }
4481  return 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)
4486  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4487{
4488  return (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)
4494  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4495{
4496  if (args[idx].v_type != VAR_FLOAT && args[idx].v_type != VAR_NUMBER) {
4497    semsg(_(e_float_or_number_required_for_argument_nr), idx + 1);
4498    return FAIL;
4499  }
4500  return 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)
4505  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4506{
4507  if (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))) {
4511    semsg(_(e_bool_required_for_argument_nr), idx + 1);
4512    return FAIL;
4513  }
4514  return 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)
4520  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4521{
4522  if (args[idx].v_type == VAR_UNKNOWN) {
4523    return OK;
4524  }
4525  return 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)
4530  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4531{
4532  if (args[idx].v_type != VAR_BLOB) {
4533    semsg(_(e_blob_required_for_argument_nr), idx + 1);
4534    return FAIL;
4535  }
4536  return 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)
4541  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4542{
4543  if (args[idx].v_type != VAR_LIST) {
4544    semsg(_(e_list_required_for_argument_nr), idx + 1);
4545    return FAIL;
4546  }
4547  return 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)
4552  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4553{
4554  if (args[idx].v_type != VAR_DICT) {
4555    semsg(_(e_dict_required_for_argument_nr), idx + 1);
4556    return FAIL;
4557  }
4558  return 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)
4563  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4564{
4565  if (tv_check_for_dict_arg(args, idx) == FAIL) {
4566    return FAIL;
4567  }
4568  if (args[idx].vval.v_dict == NULL) {
4569    semsg(_(e_non_null_dict_required_for_argument_nr), idx + 1);
4570    return FAIL;
4571  }
4572  return 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)
4577  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4578{
4579  return (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)
4586  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4587{
4588  if (args[idx].v_type != VAR_STRING && args[idx].v_type != VAR_NUMBER) {
4589    semsg(_(e_string_or_number_required_for_argument_nr), idx + 1);
4590    return FAIL;
4591  }
4592  return 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)
4598  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4599{
4600  return 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)
4606  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4607{
4608  return 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)
4613  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4614{
4615  if (args[idx].v_type != VAR_STRING && args[idx].v_type != VAR_LIST) {
4616    semsg(_(e_string_or_list_required_for_argument_nr), idx + 1);
4617    return FAIL;
4618  }
4619  return 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)
4624  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4625{
4626  if (args[idx].v_type != VAR_STRING
4627      && args[idx].v_type != VAR_LIST
4628      && args[idx].v_type != VAR_BLOB) {
4629    semsg(_(e_string_list_or_blob_required_for_argument_nr), idx + 1);
4630    return FAIL;
4631  }
4632  return 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)
4637  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4638{
4639  return (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)
4646  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4647{
4648  if (args[idx].v_type != VAR_PARTIAL
4649      && args[idx].v_type != VAR_FUNC
4650      && args[idx].v_type != VAR_STRING) {
4651    semsg(_(e_string_or_function_required_for_argument_nr), idx + 1);
4652    return FAIL;
4653  }
4654  return 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)
4659  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
4660{
4661  if (args[idx].v_type != VAR_LIST && args[idx].v_type != VAR_BLOB) {
4662    semsg(_(e_list_or_blob_required_for_argument_nr), idx + 1);
4663    return FAIL;
4664  }
4665  return 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)
4680  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4681{
4682  switch (tv->v_type) {
4683  case VAR_NUMBER:
4684    snprintf(buf, NUMBUFLEN, "%" PRIdVARNUMBER, tv->vval.v_number);
4685    return buf;
4686  case VAR_FLOAT:
4687    vim_snprintf(buf, NUMBUFLEN, "%g", tv->vval.v_float);
4688    return buf;
4689  case VAR_STRING:
4690    if (tv->vval.v_string != NULL) {
4691      return tv->vval.v_string;
4692    }
4693    return "";
4694  case VAR_BOOL:
4695    STRCPY(buf, encode_bool_var_names[tv->vval.v_bool]);
4696    return buf;
4697  case VAR_SPECIAL:
4698    STRCPY(buf, encode_special_var_names[tv->vval.v_special]);
4699    return buf;
4700  case VAR_PARTIAL:
4701  case VAR_FUNC:
4702  case VAR_LIST:
4703  case VAR_DICT:
4704  case VAR_BLOB:
4705  case VAR_UNKNOWN:
4706    emsg(_(str_errors[tv->v_type]));
4707    return NULL;
4708  }
4709  abort();
4710  return 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)
4725  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4726{
4727  static char mybuf[NUMBUFLEN];
4728
4729  return 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)
4748  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT
4749{
4750  static char mybuf[NUMBUFLEN];
4751  return 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)
4770  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT
4771{
4772  const char *const res = tv_get_string_buf_chk(tv, buf);
4773
4774  return 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{
4782  switch (tv->v_type) {
4783  case VAR_NUMBER:
4784    return tv->vval.v_number != 0;
4785  case VAR_FLOAT:
4786    return tv->vval.v_float != 0.0;
4787  case VAR_PARTIAL:
4788    return tv->vval.v_partial != NULL;
4789  case VAR_FUNC:
4790  case VAR_STRING:
4791    return tv->vval.v_string != NULL && *tv->vval.v_string != NUL;
4792  case VAR_LIST:
4793    return tv->vval.v_list != NULL && tv->vval.v_list->lv_len > 0;
4794  case VAR_DICT:
4795    return tv->vval.v_dict != NULL && tv->vval.v_dict->dv_hashtab.ht_used > 0;
4796  case VAR_BOOL:
4797    return tv->vval.v_bool == kBoolVarTrue;
4798  case VAR_SPECIAL:
4799    return tv->vval.v_special != kSpecialVarNull;
4800  case VAR_BLOB:
4801    return tv->vval.v_blob != NULL && tv->vval.v_blob->bv_ga.ga_len > 0;
4802  case VAR_UNKNOWN:
4803    break;
4804  }
4805  return 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.
4813  if (n <= (varnumber_T)INT_MAX / slen) {
4814    return OK;
4815  }
4816
4817  char buf[NUMBUFLEN];
4818  vim_snprintf(buf, sizeof(buf), "%" PRId64, (int64_t)n);
4819  semsg(_(e_val_too_large), buf);
4820  return FAIL;
4821}