robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

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