robin/laufey

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

bfredlMerge pull request #39736 from bfredl/odod8275b7b491

master
32.8 KiB841 linesraw
1// uncrustify:off
2
3/// @file eval/typval_encode.c.h
4///
5/// Contains set of macros used to convert (possibly recursive) typval_T into
6/// something else. For these macros to work the following macros must be
7/// defined:
8
9/// @def TYPVAL_ENCODE_CHECK_BEFORE
10/// @brief Macro used before any specific CONV function
11///
12/// can be used for a common check, like flushing a buffer if necessary
13
14/// @def TYPVAL_ENCODE_CONV_NIL
15/// @brief Macros used to convert NIL value
16///
17/// Is called both for special dictionary (unless #TYPVAL_ENCODE_ALLOW_SPECIALS
18/// is false) and `v:null`.
19///
20/// @param  tv  Pointer to typval where value is stored. May not be NULL. May
21///             point to special dictionary.
22
23/// @def TYPVAL_ENCODE_CONV_BOOL
24/// @brief Macros used to convert boolean value
25///
26/// Is called both for special dictionary (unless #TYPVAL_ENCODE_ALLOW_SPECIALS
27/// is false) and `v:true`/`v:false`.
28///
29/// @param  tv  Pointer to typval where value is stored. May not be NULL. May
30///             point to a special dictionary.
31/// @param  num  Boolean value to convert. Value is an expression which
32///              evaluates to some integer.
33
34/// @def TYPVAL_ENCODE_CONV_NUMBER
35/// @brief Macros used to convert integer
36///
37/// @param  tv  Pointer to typval where value is stored. May not be NULL. May
38///             point to a special dictionary.
39/// @param  num  Integer to convert, must accept both varnumber_T and int64_t.
40
41/// @def TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER
42/// @brief Macros used to convert unsigned integer
43///
44/// Not used if #TYPVAL_ENCODE_ALLOW_SPECIALS is false, but still must be
45/// defined.
46///
47/// @param  tv  Pointer to typval where value is stored. May not be NULL. Points
48///             to a special dictionary.
49/// @param  num  Integer to convert, must accept uint64_t.
50
51/// @def TYPVAL_ENCODE_CONV_FLOAT
52/// @brief Macros used to convert floating-point number
53///
54/// @param  tv  Pointer to typval where value is stored. May not be NULL. May
55///             point to a special dictionary.
56/// @param  flt  Number to convert, must accept float_T.
57
58/// @def TYPVAL_ENCODE_CONV_STRING
59/// @brief Macros used to convert plain string
60///
61/// Is used to convert VAR_STRING objects as well as BIN strings represented as
62/// special dictionary.
63///
64/// @param  tv  Pointer to typval where value is stored. May not be NULL. May
65///             point to a special dictionary.
66/// @param  buf  String to convert. Is a char[] buffer, not NUL-terminated.
67/// @param  len  String length.
68
69/// @def TYPVAL_ENCODE_CONV_STR_STRING
70/// @brief Like #TYPVAL_ENCODE_CONV_STRING, but for STR strings
71///
72/// Is used to convert dictionary keys and STR strings represented as special
73/// dictionaries.
74///
75/// @param  tv  Pointer to typval where value is stored. May be NULL. May
76///             point to a special dictionary.
77/// @param  buf  String to convert. Is a char[] buffer, not NUL-terminated.
78/// @param  len  String length.
79
80/// @def TYPVAL_ENCODE_CONV_EXT_STRING
81/// @brief Macros used to convert EXT string
82///
83/// Is used to convert EXT strings represented as special dictionaries. Never
84/// actually used if #TYPVAL_ENCODE_ALLOW_SPECIALS is false, but still must be
85/// defined.
86///
87/// @param  tv  Pointer to typval where value is stored. May not be NULL. Points
88///             to a special dictionary.
89/// @param  buf  String to convert. Is a char[] buffer, not NUL-terminated.
90/// @param  len  String length.
91/// @param  type  EXT type.
92
93/// @def TYPVAL_ENCODE_CONV_BLOB
94/// @brief Macros used to convert a blob
95///
96/// @param  tv  Pointer to typval where value is stored. May not be NULL.
97/// @param  blob  Pointer to the blob to convert.
98/// @param  len  Blob length.
99
100/// @def TYPVAL_ENCODE_CONV_FUNC_START
101/// @brief Macros used when starting to convert a funcref or a partial
102///
103/// @param  tv  Pointer to typval where value is stored. May not be NULL.
104/// @param  fun  Function name. May be NULL.
105/// @param  prefix  Prefix for converting to a string.
106
107/// @def TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS
108/// @brief Macros used before starting to convert partial arguments
109///
110/// @param  tv  Pointer to typval where value is stored. May not be NULL.
111/// @param  len  Number of arguments. Zero for absent arguments or when
112///              converting a funcref.
113
114/// @def TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF
115/// @brief Macros used before starting to convert self dictionary
116///
117/// @param  tv  Pointer to typval where value is stored. May not be NULL.
118/// @param  len  Number of arguments. May be zero for empty dictionary or -1 for
119///              missing self dictionary, also when converting function
120///              reference.
121
122/// @def TYPVAL_ENCODE_CONV_FUNC_END
123/// @brief Macros used after converting a funcref or a partial
124///
125/// @param  tv  Pointer to typval where value is stored. May not be NULL.
126
127/// @def TYPVAL_ENCODE_CONV_EMPTY_LIST
128/// @brief Macros used to convert an empty list
129///
130/// @param  tv  Pointer to typval where value is stored. May not be NULL.
131
132/// @def TYPVAL_ENCODE_CONV_EMPTY_DICT
133/// @brief Macros used to convert an empty dictionary
134///
135/// @param  tv  Pointer to typval where value is stored. May be NULL. May
136///             point to a special dictionary.
137/// @param  dict  Converted dictionary, lvalue or #TYPVAL_ENCODE_NODICT_VAR
138///               (for dictionaries represented as special lists).
139
140/// @def TYPVAL_ENCODE_CONV_LIST_START
141/// @brief Macros used before starting to convert non-empty list
142///
143/// @param  tv  Pointer to typval where value is stored. May be NULL. May
144///             point to a special dictionary.
145/// @param  len  List length. Is an expression which evaluates to an integer.
146
147/// @def TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START
148/// @brief Macros used after pushing list onto the stack
149///
150/// Only used for real list_T* lists, not for special dictionaries or partial
151/// arguments.
152///
153/// @param  tv  Pointer to typval where value is stored. May be NULL. May
154///             point to a special dictionary.
155/// @param  mpsv  Pushed MPConvStackVal value.
156
157/// @def TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS
158/// @brief Macros used after finishing converting non-last list item
159///
160/// @param  tv  Pointer to typval where list is stored. May be NULL.
161
162/// @def TYPVAL_ENCODE_CONV_LIST_END
163/// @brief Macros used after converting non-empty list
164///
165/// @param  tv  Pointer to typval where list is stored. May be NULL.
166
167/// @def TYPVAL_ENCODE_CONV_DICT_START
168/// @brief Macros used before starting to convert non-empty dictionary
169///
170/// Only used for real dict_T* dictionaries, not for special dictionaries. Also
171/// used for partial self dictionary.
172///
173/// @param  tv  Pointer to typval where dictionary is stored. May be NULL. May
174///             point to a special dictionary.
175/// @param  dict  Converted dictionary, lvalue or #TYPVAL_ENCODE_NODICT_VAR
176///               (for dictionaries represented as special lists).
177/// @param  len  Dict length. Is an expression which evaluates to an integer.
178
179/// @def TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START
180/// @brief Macros used after pushing dictionary onto the stack
181///
182/// @param  tv  Pointer to typval where dictionary is stored. May be NULL.
183///             May not point to a special dictionary.
184/// @param  dict  Converted dictionary, lvalue.
185/// @param  mpsv  Pushed MPConvStackVal value.
186
187/// @def TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK
188/// @brief Macros used to check special dictionary key
189///
190/// @param  label  Label for goto in case check was not successful.
191/// @param  key  typval_T key to check.
192
193/// @def TYPVAL_ENCODE_CONV_DICT_AFTER_KEY
194/// @brief Macros used after finishing converting dictionary key
195///
196/// @param  tv  Pointer to typval where dictionary is stored. May be NULL. May
197///             point to a special dictionary.
198/// @param  dict  Converted dictionary, lvalue or #TYPVAL_ENCODE_NODICT_VAR
199///               (for dictionaries represented as special lists).
200
201/// @def TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS
202/// @brief Macros used after finishing converting non-last dictionary value
203///
204/// @param  tv  Pointer to typval where dictionary is stored. May be NULL. May
205///             point to a special dictionary.
206/// @param  dict  Converted dictionary, lvalue or #TYPVAL_ENCODE_NODICT_VAR
207///               (for dictionaries represented as special lists).
208
209/// @def TYPVAL_ENCODE_CONV_DICT_END
210/// @brief Macros used after converting non-empty dictionary
211///
212/// @param  tv  Pointer to typval where dictionary is stored. May be NULL. May
213///             point to a special dictionary.
214/// @param  dict  Converted dictionary, lvalue or #TYPVAL_ENCODE_NODICT_VAR
215///               (for dictionaries represented as special lists).
216
217/// @def TYPVAL_ENCODE_CONV_RECURSE
218/// @brief Macros used when self-containing container is detected
219///
220/// @param  val  Container for which this situation was detected.
221/// @param  conv_type  Type of the stack entry, @see MPConvStackValType.
222
223/// @def TYPVAL_ENCODE_ALLOW_SPECIALS
224/// @brief Macros that specifies whether special dictionaries are special
225///
226/// Must be something that evaluates to boolean, most likely `true` or `false`.
227/// If it is false then special dictionaries are not treated specially.
228
229/// @def TYPVAL_ENCODE_SCOPE
230/// @brief Scope of the main function: either nothing or `static`
231
232/// @def TYPVAL_ENCODE_NAME
233/// @brief Name of the target converter
234///
235/// After including this file it will define function
236/// `encode_vim_to_{TYPVAL_ENCODE_NAME}` with scope #TYPVAL_ENCODE_SCOPE and
237/// static functions `_typval_encode_{TYPVAL_ENCODE_NAME}_convert_one_value` and
238/// `_typval_encode_{TYPVAL_ENCODE_NAME}_check_self_reference`.
239
240/// @def TYPVAL_ENCODE_FIRST_ARG_TYPE
241/// @brief Type of the first argument, which will be used to return the results
242///
243/// Is expected to be a pointer type.
244
245/// @def TYPVAL_ENCODE_FIRST_ARG_NAME
246/// @brief Name of the first argument
247///
248/// This name will only be used by one of the above macros which are defined by
249/// the caller. Functions defined here do not use first argument directly.
250#include <assert.h>
251#include <inttypes.h>
252#include <stddef.h>
253
254#include "klib/kvec.h"
255#include "nvim/eval.h"
256#include "nvim/eval/encode.h"
257#include "nvim/eval/typval.h"
258#include "nvim/eval/typval_encode.h"
259#include "nvim/eval/vars.h"
260#include "nvim/func_attr.h"
261
262/// Dummy variable used because some macros need lvalue
263///
264/// Must not be written to, if needed one must check that address of the
265/// macros argument is (not) equal to `&TYPVAL_ENCODE_NODICT_VAR`.
266const dict_T *const TYPVAL_ENCODE_NODICT_VAR = NULL;
267
268static inline int TYPVAL_ENCODE_CHECK_SELF_REFERENCE(
269                                                      TYPVAL_ENCODE_FIRST_ARG_TYPE TYPVAL_ENCODE_FIRST_ARG_NAME,
270                                                      void *const val, int *const val_copyID,
271                                                      const MPConvStack *const mpstack, const int copyID,
272                                                      const MPConvStackValType conv_type,
273                                                      const char *const objname)
274  REAL_FATTR_NONNULL_ARG(2, 3, 4, 7) REAL_FATTR_WARN_UNUSED_RESULT
275  REAL_FATTR_ALWAYS_INLINE;
276
277/// Function for checking whether container references itself
278///
279/// @param  TYPVAL_ENCODE_FIRST_ARG_NAME  First argument.
280/// @param[in,out]  val  Container to check.
281/// @param  val_copyID  Pointer to the container attribute that holds copyID.
282///                     After checking whether value of this attribute is
283///                     copyID (variable) it is set to copyID.
284/// @param[in]  mpstack  Stack with values to convert. Read-only, used for error
285///                      reporting.
286/// @param[in]  copyID  CopyID used by the caller.
287/// @param[in]  conv_type  Type of the conversion, @see MPConvStackValType.
288/// @param[in]  objname  Object name, used for error reporting.
289///
290/// @return NOTDONE in case of success, what to return in case of failure.
291static inline int TYPVAL_ENCODE_CHECK_SELF_REFERENCE(
292                                                     TYPVAL_ENCODE_FIRST_ARG_TYPE TYPVAL_ENCODE_FIRST_ARG_NAME, void *const val, int *const val_copyID,
293                                                     const MPConvStack *const mpstack, const int copyID, const MPConvStackValType conv_type,
294                                                     const char *const objname)
295{
296  if (*val_copyID == copyID) {
297    TYPVAL_ENCODE_CONV_RECURSE(val, conv_type);
298    return OK;
299  }
300  *val_copyID = copyID;
301  return NOTDONE;
302}
303
304static int TYPVAL_ENCODE_CONVERT_ONE_VALUE(
305                                            TYPVAL_ENCODE_FIRST_ARG_TYPE TYPVAL_ENCODE_FIRST_ARG_NAME,
306                                            MPConvStack *const mpstack, MPConvStackVal *const cur_mpsv,
307                                            typval_T *const tv, const int copyID,
308                                            const char *const objname)
309  REAL_FATTR_NONNULL_ARG(2, 4, 6) REAL_FATTR_WARN_UNUSED_RESULT;
310
311/// Convert single value
312///
313/// Only scalar values are converted immediately, everything else is pushed onto
314/// the stack.
315///
316/// @param  TYPVAL_ENCODE_FIRST_ARG_NAME  First argument, defined by the
317///                                       includer. Only meaningful to macros
318///                                       defined by the includer.
319/// @param  mpstack  Stack with values to convert. Values which are not
320///                  converted completely by this function (i.e.
321///                  non-scalars) are pushed here.
322/// @param  cur_mpsv  Currently converted value from stack.
323/// @param  tv  Converted value.
324/// @param[in]  copyID  CopyID.
325/// @param[in]  objname  Object name, used for error reporting.
326///
327/// @return OK in case of success, FAIL in case of failure.
328static int TYPVAL_ENCODE_CONVERT_ONE_VALUE(
329                                           TYPVAL_ENCODE_FIRST_ARG_TYPE TYPVAL_ENCODE_FIRST_ARG_NAME, MPConvStack *const mpstack,
330                                           MPConvStackVal *const cur_mpsv, typval_T *const tv, const int copyID, const char *const objname)
331{
332  TYPVAL_ENCODE_CHECK_BEFORE;
333  switch (tv->v_type) {
334  case VAR_STRING:
335    TYPVAL_ENCODE_CONV_STRING(tv, tv->vval.v_string, tv_strlen(tv));
336    break;
337  case VAR_NUMBER:
338    TYPVAL_ENCODE_CONV_NUMBER(tv, tv->vval.v_number);
339    break;
340  case VAR_FLOAT:
341    TYPVAL_ENCODE_CONV_FLOAT(tv, tv->vval.v_float);
342    break;
343  case VAR_BLOB:
344    TYPVAL_ENCODE_CONV_BLOB(tv, tv->vval.v_blob,
345                            tv_blob_len(tv->vval.v_blob));
346    break;
347  case VAR_FUNC:
348    TYPVAL_ENCODE_CONV_FUNC_START(tv, tv->vval.v_string, "");
349    TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS(tv, 0);
350    TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF(tv, -1);
351    TYPVAL_ENCODE_CONV_FUNC_END(tv);
352    break;
353  case VAR_PARTIAL: {
354    partial_T *const pt = tv->vval.v_partial;
355    char *const fun = pt == NULL ? NULL : partial_name(pt);
356    // When using uf_name prepend "g:" for a global function.
357    const char *const prefix = fun != NULL && pt != NULL && pt->pt_name == NULL
358                               && ASCII_ISUPPER(fun[0]) ? "g:" : "";
359    (void)prefix;
360    TYPVAL_ENCODE_CONV_FUNC_START(tv, fun, prefix);
361    kvi_push(*mpstack, ((MPConvStackVal) {
362        .type = kMPConvPartial,
363        .tv = tv,
364        .saved_copyID = copyID - 1,
365        .data = {
366          .p = {
367            .stage = kMPConvPartialArgs,
368            .pt = tv->vval.v_partial,
369          },
370        },
371    }));
372    break;
373  }
374  case VAR_LIST: {
375    if (tv->vval.v_list == NULL || tv_list_len(tv->vval.v_list) == 0) {
376      TYPVAL_ENCODE_CONV_EMPTY_LIST(tv);
377      break;
378    }
379    const int saved_copyID = tv_list_copyid(tv->vval.v_list);
380    TYPVAL_ENCODE_DO_CHECK_SELF_REFERENCE(tv->vval.v_list, lv_copyID, copyID,
381                                          kMPConvList);
382    TYPVAL_ENCODE_CONV_LIST_START(tv, tv_list_len(tv->vval.v_list));
383    assert(saved_copyID != copyID);
384    kvi_push(*mpstack, ((MPConvStackVal) {
385        .type = kMPConvList,
386        .tv = tv,
387        .saved_copyID = saved_copyID,
388        .data = {
389          .l = {
390            .list = tv->vval.v_list,
391            .li = tv_list_first(tv->vval.v_list),
392          },
393        },
394    }));
395    TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START(tv, kv_last(*mpstack));
396    break;
397  }
398  case VAR_BOOL:
399    switch (tv->vval.v_bool) {
400    case kBoolVarTrue:
401    case kBoolVarFalse:
402      TYPVAL_ENCODE_CONV_BOOL(tv, tv->vval.v_bool == kBoolVarTrue);
403      break;
404    }
405    break;
406  case VAR_SPECIAL:
407    switch (tv->vval.v_special) {
408    case kSpecialVarNull:
409      TYPVAL_ENCODE_CONV_NIL(tv);
410      break;
411    }
412    break;
413  case VAR_DICT: {
414    if (tv->vval.v_dict == NULL
415        || tv->vval.v_dict->dv_hashtab.ht_used == 0) {
416      TYPVAL_ENCODE_CONV_EMPTY_DICT(tv, tv->vval.v_dict);
417      break;
418    }
419    const dictitem_T *type_di;
420    const dictitem_T *val_di;
421    if (TYPVAL_ENCODE_ALLOW_SPECIALS
422        && tv->vval.v_dict->dv_hashtab.ht_used == 2
423        && (type_di = tv_dict_find(tv->vval.v_dict, S_LEN("_TYPE"))) != NULL
424        && type_di->di_tv.v_type == VAR_LIST
425        && (val_di = tv_dict_find(tv->vval.v_dict, S_LEN("_VAL"))) != NULL) {
426      size_t i;
427      for (i = 0; i < ARRAY_SIZE(eval_msgpack_type_lists); i++) {
428        if (type_di->di_tv.vval.v_list == eval_msgpack_type_lists[i]) {
429          break;
430        }
431      }
432      TYPVAL_ENCODE_CHECK_BEFORE;
433      if (i == ARRAY_SIZE(eval_msgpack_type_lists)) {
434        goto _convert_one_value_regular_dict;
435      }
436      switch ((MessagePackType)i) {
437      case kMPNil:
438        TYPVAL_ENCODE_CONV_NIL(tv);
439        break;
440      case kMPBoolean:
441        if (val_di->di_tv.v_type != VAR_NUMBER) {
442          goto _convert_one_value_regular_dict;
443        }
444        TYPVAL_ENCODE_CONV_BOOL(tv, val_di->di_tv.vval.v_number);
445        break;
446      case kMPInteger: {
447        const list_T *val_list;
448        varnumber_T sign;
449        varnumber_T highest_bits;
450        varnumber_T high_bits;
451        varnumber_T low_bits;
452        // List of 4 integers; first is signed (should be 1 or -1, but
453        // this is not checked), second is unsigned and have at most
454        // one (sign is -1) or two (sign is 1) non-zero bits (number of
455        // bits is not checked), other unsigned and have at most 31
456        // non-zero bits (number of bits is not checked).
457        if (val_di->di_tv.v_type != VAR_LIST
458            || tv_list_len(val_list = val_di->di_tv.vval.v_list) != 4) {
459          goto _convert_one_value_regular_dict;
460        }
461
462        const listitem_T *const sign_li = tv_list_first(val_list);
463        if (TV_LIST_ITEM_TV(sign_li)->v_type != VAR_NUMBER
464            || (sign = TV_LIST_ITEM_TV(sign_li)->vval.v_number) == 0) {
465          goto _convert_one_value_regular_dict;
466        }
467
468        const listitem_T *const highest_bits_li = (
469                                                   TV_LIST_ITEM_NEXT(val_list, sign_li));
470        if (TV_LIST_ITEM_TV(highest_bits_li)->v_type != VAR_NUMBER
471            || ((highest_bits = TV_LIST_ITEM_TV(highest_bits_li)->vval.v_number)
472                < 0)) {
473          goto _convert_one_value_regular_dict;
474        }
475
476        const listitem_T *const high_bits_li =  (
477                                                 TV_LIST_ITEM_NEXT(val_list, highest_bits_li));
478        if (TV_LIST_ITEM_TV(high_bits_li)->v_type != VAR_NUMBER
479            || ((high_bits = TV_LIST_ITEM_TV(high_bits_li)->vval.v_number)
480                < 0)) {
481          goto _convert_one_value_regular_dict;
482        }
483
484        const listitem_T *const low_bits_li = tv_list_last(val_list);
485        if (TV_LIST_ITEM_TV(low_bits_li)->v_type != VAR_NUMBER
486            || ((low_bits = TV_LIST_ITEM_TV(low_bits_li)->vval.v_number)
487                < 0)) {
488          goto _convert_one_value_regular_dict;
489        }
490
491        const uint64_t number = ((((uint64_t)highest_bits) << 62)
492                                 | (((uint64_t)high_bits) << 31)
493                                 | (uint64_t)low_bits);
494        if (sign > 0) {
495          TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER(tv, number);
496        } else {
497          TYPVAL_ENCODE_CONV_NUMBER(tv, -number);
498        }
499        break;
500      }
501      case kMPFloat:
502        if (val_di->di_tv.v_type != VAR_FLOAT) {
503          goto _convert_one_value_regular_dict;
504        }
505        TYPVAL_ENCODE_CONV_FLOAT(tv, val_di->di_tv.vval.v_float);
506        break;
507      case kMPString: {
508        if (val_di->di_tv.v_type != VAR_LIST) {
509          goto _convert_one_value_regular_dict;
510        }
511        size_t len;
512        char *buf;
513        if (!encode_vim_list_to_buf(val_di->di_tv.vval.v_list, &len,
514                                    &buf)) {
515          goto _convert_one_value_regular_dict;
516        }
517        TYPVAL_ENCODE_CONV_STR_STRING(tv, buf, len);
518        xfree(buf);
519        break;
520      }
521      case kMPArray: {
522        if (val_di->di_tv.v_type != VAR_LIST) {
523          goto _convert_one_value_regular_dict;
524        }
525        const int saved_copyID = tv_list_copyid(val_di->di_tv.vval.v_list);
526        TYPVAL_ENCODE_DO_CHECK_SELF_REFERENCE(val_di->di_tv.vval.v_list,
527                                              lv_copyID, copyID,
528                                              kMPConvList);
529        TYPVAL_ENCODE_CONV_LIST_START(tv, tv_list_len(val_di->di_tv.vval.v_list));
530        assert(saved_copyID != copyID && saved_copyID != copyID - 1);
531        kvi_push(*mpstack, ((MPConvStackVal) {
532              .tv = tv,
533              .type = kMPConvList,
534              .saved_copyID = saved_copyID,
535              .data = {
536                .l = {
537                  .list = val_di->di_tv.vval.v_list,
538                  .li = tv_list_first(val_di->di_tv.vval.v_list),
539                },
540              },
541        }));
542        break;
543      }
544      case kMPMap: {
545        if (val_di->di_tv.v_type != VAR_LIST) {
546          goto _convert_one_value_regular_dict;
547        }
548        list_T *const val_list = val_di->di_tv.vval.v_list;
549        if (val_list == NULL || tv_list_len(val_list) == 0) {
550          TYPVAL_ENCODE_CONV_EMPTY_DICT(tv, TYPVAL_ENCODE_NODICT_VAR);
551          break;
552        }
553        TV_LIST_ITER_CONST(val_list, li, {
554              if (TV_LIST_ITEM_TV(li)->v_type != VAR_LIST
555                  || tv_list_len(TV_LIST_ITEM_TV(li)->vval.v_list) != 2) {
556                goto _convert_one_value_regular_dict;
557              }
558            });
559        const int saved_copyID = tv_list_copyid(val_di->di_tv.vval.v_list);
560        TYPVAL_ENCODE_DO_CHECK_SELF_REFERENCE(val_list, lv_copyID, copyID,
561                                              kMPConvPairs);
562        TYPVAL_ENCODE_CONV_DICT_START(tv, TYPVAL_ENCODE_NODICT_VAR,
563                                      tv_list_len(val_list));
564        assert(saved_copyID != copyID && saved_copyID != copyID - 1);
565        kvi_push(*mpstack, ((MPConvStackVal) {
566              .tv = tv,
567              .type = kMPConvPairs,
568              .saved_copyID = saved_copyID,
569              .data = {
570                .l = {
571                  .list = val_list,
572                  .li = tv_list_first(val_list),
573                },
574              },
575        }));
576        break;
577      }
578      case kMPExt: {
579        const list_T *val_list;
580        varnumber_T type;
581        if (val_di->di_tv.v_type != VAR_LIST
582            || tv_list_len((val_list = val_di->di_tv.vval.v_list)) != 2
583            || (TV_LIST_ITEM_TV(tv_list_first(val_list))->v_type
584                != VAR_NUMBER)
585            || ((type = TV_LIST_ITEM_TV(tv_list_first(val_list))->vval.v_number)
586                > INT8_MAX)
587            || type < INT8_MIN
588            || (TV_LIST_ITEM_TV(tv_list_last(val_list))->v_type
589                != VAR_LIST)) {
590          goto _convert_one_value_regular_dict;
591        }
592        size_t len;
593        char *buf;
594        if (!(
595              encode_vim_list_to_buf(TV_LIST_ITEM_TV(tv_list_last(val_list))->vval.v_list, &len,
596                                     &buf))) {
597          goto _convert_one_value_regular_dict;
598        }
599        TYPVAL_ENCODE_CONV_EXT_STRING(tv, buf, len, type);
600        xfree(buf);
601        break;
602      }
603      }
604      break;
605    }
606_convert_one_value_regular_dict: {}
607    const int saved_copyID = tv->vval.v_dict->dv_copyID;
608    TYPVAL_ENCODE_DO_CHECK_SELF_REFERENCE(tv->vval.v_dict, dv_copyID, copyID,
609                                          kMPConvDict);
610    TYPVAL_ENCODE_CONV_DICT_START(tv, tv->vval.v_dict,
611                                  tv->vval.v_dict->dv_hashtab.ht_used);
612    assert(saved_copyID != copyID);
613    kvi_push(*mpstack, ((MPConvStackVal) {
614        .tv = tv,
615        .type = kMPConvDict,
616        .saved_copyID = saved_copyID,
617        .data = {
618          .d = {
619            .dict = tv->vval.v_dict,
620            .dictp = &tv->vval.v_dict,
621            .hi = tv->vval.v_dict->dv_hashtab.ht_array,
622            .todo = tv->vval.v_dict->dv_hashtab.ht_used,
623          },
624        },
625    }));
626    TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START(tv, tv->vval.v_dict,
627                                             kv_last(*mpstack));
628    break;
629  }
630  case VAR_UNKNOWN:
631    internal_error(STR(TYPVAL_ENCODE_CONVERT_ONE_VALUE) "()");
632    return FAIL;
633  }
634typval_encode_stop_converting_one_item:
635  return OK;
636  // Prevent “unused label” warnings.
637  goto typval_encode_stop_converting_one_item;
638}
639
640TYPVAL_ENCODE_SCOPE int TYPVAL_ENCODE_ENCODE(
641                                              TYPVAL_ENCODE_FIRST_ARG_TYPE TYPVAL_ENCODE_FIRST_ARG_NAME,
642                                              typval_T *const tv, const char *const objname)
643  REAL_FATTR_NONNULL_ARG(2, 3) REAL_FATTR_WARN_UNUSED_RESULT;
644
645/// Convert the whole typval
646///
647/// @param  TYPVAL_ENCODE_FIRST_ARG_NAME  First argument, defined by the
648///                                       includer. Only meaningful to macros
649///                                       defined by the includer.
650/// @param  top_tv  Converted value.
651/// @param[in]  objname  Object name, used for error reporting.
652///
653/// @return OK in case of success, FAIL in case of failure.
654TYPVAL_ENCODE_SCOPE int TYPVAL_ENCODE_ENCODE(
655                                             TYPVAL_ENCODE_FIRST_ARG_TYPE TYPVAL_ENCODE_FIRST_ARG_NAME, typval_T *const top_tv,
656                                             const char *const objname)
657{
658  const int copyID = get_copyID();
659  MPConvStack mpstack;
660  kvi_init(mpstack);
661  if (TYPVAL_ENCODE_CONVERT_ONE_VALUE(TYPVAL_ENCODE_FIRST_ARG_NAME, &mpstack,
662                                      NULL,
663                                      top_tv, copyID, objname)
664      == FAIL) {
665    goto encode_vim_to__error_ret;
666  }
667/// Label common for this and convert_one_value functions, used for escaping
668/// from macros like TYPVAL_ENCODE_CONV_DICT_START.
669typval_encode_stop_converting_one_item:
670  while (kv_size(mpstack)) {
671    MPConvStackVal *cur_mpsv = &kv_last(mpstack);
672    typval_T *tv = NULL;
673    switch (cur_mpsv->type) {
674    case kMPConvDict: {
675      if (!cur_mpsv->data.d.todo) {
676        (void)kv_pop(mpstack);
677        cur_mpsv->data.d.dict->dv_copyID = cur_mpsv->saved_copyID;
678        TYPVAL_ENCODE_CONV_DICT_END(cur_mpsv->tv, *cur_mpsv->data.d.dictp);
679        continue;
680      } else if (cur_mpsv->data.d.todo
681                 != cur_mpsv->data.d.dict->dv_hashtab.ht_used) {
682        TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS(cur_mpsv->tv,
683                                              *cur_mpsv->data.d.dictp);
684      }
685      while (HASHITEM_EMPTY(cur_mpsv->data.d.hi)) {
686        cur_mpsv->data.d.hi++;
687      }
688      dictitem_T *const di = TV_DICT_HI2DI(cur_mpsv->data.d.hi);
689      cur_mpsv->data.d.todo--;
690      cur_mpsv->data.d.hi++;
691      TYPVAL_ENCODE_CONV_STR_STRING(NULL, &di->di_key[0],
692                                    strlen((char *)&di->di_key[0]));
693      TYPVAL_ENCODE_CONV_DICT_AFTER_KEY(cur_mpsv->tv,
694                                        *cur_mpsv->data.d.dictp);
695      tv = &di->di_tv;
696      break;
697    }
698    case kMPConvList:
699      if (cur_mpsv->data.l.li == NULL) {
700        (void)kv_pop(mpstack);
701        tv_list_set_copyid(cur_mpsv->data.l.list, cur_mpsv->saved_copyID);
702        TYPVAL_ENCODE_CONV_LIST_END(cur_mpsv->tv);
703        continue;
704      } else if (cur_mpsv->data.l.li
705                 != tv_list_first(cur_mpsv->data.l.list)) {
706        TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS(cur_mpsv->tv);
707      }
708      tv = TV_LIST_ITEM_TV(cur_mpsv->data.l.li);
709      cur_mpsv->data.l.li = TV_LIST_ITEM_NEXT(cur_mpsv->data.l.list,
710                                              cur_mpsv->data.l.li);
711      break;
712    case kMPConvPairs: {
713      if (cur_mpsv->data.l.li == NULL) {
714        (void)kv_pop(mpstack);
715        tv_list_set_copyid(cur_mpsv->data.l.list, cur_mpsv->saved_copyID);
716        TYPVAL_ENCODE_CONV_DICT_END(cur_mpsv->tv, TYPVAL_ENCODE_NODICT_VAR);
717        continue;
718      } else if (cur_mpsv->data.l.li
719                 != tv_list_first(cur_mpsv->data.l.list)) {
720        TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS(cur_mpsv->tv, TYPVAL_ENCODE_NODICT_VAR);
721      }
722      const list_T *const kv_pair = (
723                                     TV_LIST_ITEM_TV(cur_mpsv->data.l.li)->vval.v_list);
724      TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK(encode_vim_to__error_ret,
725                                           *TV_LIST_ITEM_TV(tv_list_first(kv_pair)));
726      if (
727          TYPVAL_ENCODE_CONVERT_ONE_VALUE(TYPVAL_ENCODE_FIRST_ARG_NAME, &mpstack, cur_mpsv,
728                                          TV_LIST_ITEM_TV(tv_list_first(kv_pair)), copyID, objname)
729          == FAIL) {
730        goto encode_vim_to__error_ret;
731      }
732      TYPVAL_ENCODE_CONV_DICT_AFTER_KEY(cur_mpsv->tv,
733                                        TYPVAL_ENCODE_NODICT_VAR);
734      tv = TV_LIST_ITEM_TV(tv_list_last(kv_pair));
735      cur_mpsv->data.l.li = TV_LIST_ITEM_NEXT(cur_mpsv->data.l.list,
736                                              cur_mpsv->data.l.li);
737      break;
738    }
739    case kMPConvPartial: {
740      partial_T *const pt = cur_mpsv->data.p.pt;
741      tv = cur_mpsv->tv;
742      (void)tv;
743      switch (cur_mpsv->data.p.stage) {
744      case kMPConvPartialArgs:
745        TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS(tv,
746                                            pt == NULL ? 0 : pt->pt_argc);
747        cur_mpsv->data.p.stage = kMPConvPartialSelf;
748        if (pt != NULL && pt->pt_argc > 0) {
749          TYPVAL_ENCODE_CONV_LIST_START(NULL, pt->pt_argc);
750          kvi_push(mpstack, ((MPConvStackVal) {
751              .type = kMPConvPartialList,
752              .tv = NULL,
753              .saved_copyID = copyID - 1,
754              .data = {
755                .a = {
756                  .arg = pt->pt_argv,
757                  .argv = pt->pt_argv,
758                  .todo = (size_t)pt->pt_argc,
759                },
760              },
761          }));
762        }
763        break;
764      case kMPConvPartialSelf: {
765        cur_mpsv->data.p.stage = kMPConvPartialEnd;
766        dict_T *const dict = pt == NULL ? NULL : pt->pt_dict;
767        if (dict != NULL) {
768          TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF(tv, dict->dv_hashtab.ht_used);
769          if (dict->dv_hashtab.ht_used == 0) {
770            TYPVAL_ENCODE_CONV_EMPTY_DICT(NULL, pt->pt_dict);
771            continue;
772          }
773          const int saved_copyID = dict->dv_copyID;
774          const int te_csr_ret = TYPVAL_ENCODE_CHECK_SELF_REFERENCE(TYPVAL_ENCODE_FIRST_ARG_NAME,
775                                                                    dict, &dict->dv_copyID,
776                                                                    &mpstack, copyID, kMPConvDict,
777                                                                    objname);
778          if (te_csr_ret != NOTDONE) {
779            if (te_csr_ret == FAIL) {
780              goto encode_vim_to__error_ret;
781            } else {
782              continue;
783            }
784          }
785          TYPVAL_ENCODE_CONV_DICT_START(NULL, pt->pt_dict,
786                                        dict->dv_hashtab.ht_used);
787          assert(saved_copyID != copyID && saved_copyID != copyID - 1);
788          kvi_push(mpstack, ((MPConvStackVal) {
789                .type = kMPConvDict,
790                .tv = NULL,
791                .saved_copyID = saved_copyID,
792                .data = {
793                  .d = {
794                    .dict = dict,
795                    .dictp = &pt->pt_dict,
796                    .hi = dict->dv_hashtab.ht_array,
797                    .todo = dict->dv_hashtab.ht_used,
798                  },
799                },
800          }));
801          TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START(NULL, pt->pt_dict,
802                                                   kv_last(mpstack));
803        } else {
804          TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF(tv, -1);
805        }
806        break;
807      }
808      case kMPConvPartialEnd:
809        TYPVAL_ENCODE_CONV_FUNC_END(tv);
810        (void)kv_pop(mpstack);
811        break;
812      }
813      continue;
814    }
815    case kMPConvPartialList:
816      if (!cur_mpsv->data.a.todo) {
817        (void)kv_pop(mpstack);
818        TYPVAL_ENCODE_CONV_LIST_END(NULL);
819        continue;
820      } else if (cur_mpsv->data.a.argv != cur_mpsv->data.a.arg) {
821        TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS(NULL);
822      }
823      tv = cur_mpsv->data.a.arg++;
824      cur_mpsv->data.a.todo--;
825      break;
826    }
827    assert(tv != NULL);
828    if (TYPVAL_ENCODE_CONVERT_ONE_VALUE(TYPVAL_ENCODE_FIRST_ARG_NAME, &mpstack,
829                                        cur_mpsv, tv, copyID, objname)
830        == FAIL) {
831      goto encode_vim_to__error_ret;
832    }
833  }
834  kvi_destroy(mpstack);
835  return OK;
836encode_vim_to__error_ret:
837  kvi_destroy(mpstack);
838  return FAIL;
839  // Prevent “unused label” warnings.
840  goto typval_encode_stop_converting_one_item;
841}