xref: /vim-8.2.3635/src/vim9type.c (revision ae0f151d)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * vim9type.c: handling of types
12  */
13 
14 #define USING_FLOAT_STUFF
15 #include "vim.h"
16 
17 #if defined(FEAT_EVAL) || defined(PROTO)
18 
19 #ifdef VMS
20 # include <float.h>
21 #endif
22 
23 /*
24  * Allocate memory for a type_T and add the pointer to type_gap, so that it can
25  * be easily freed later.
26  */
27     type_T *
28 get_type_ptr(garray_T *type_gap)
29 {
30     type_T *type;
31 
32     if (ga_grow(type_gap, 1) == FAIL)
33 	return NULL;
34     type = ALLOC_CLEAR_ONE(type_T);
35     if (type != NULL)
36     {
37 	((type_T **)type_gap->ga_data)[type_gap->ga_len] = type;
38 	++type_gap->ga_len;
39     }
40     return type;
41 }
42 
43     void
44 clear_type_list(garray_T *gap)
45 {
46     while (gap->ga_len > 0)
47 	vim_free(((type_T **)gap->ga_data)[--gap->ga_len]);
48     ga_clear(gap);
49 }
50 
51 /*
52  * Take a type that is using entries in a growarray and turn it into a type
53  * with allocated entries.
54  */
55     type_T *
56 alloc_type(type_T *type)
57 {
58     type_T *ret;
59 
60     if (type == NULL)
61 	return NULL;
62 
63     // A fixed type never contains allocated types, return as-is.
64     if (type->tt_flags & TTFLAG_STATIC)
65 	return type;
66 
67     ret = ALLOC_ONE(type_T);
68     *ret = *type;
69 
70     if (ret->tt_member != NULL)
71 	ret->tt_member = alloc_type(ret->tt_member);
72     if (type->tt_args != NULL)
73     {
74 	int i;
75 
76 	ret->tt_args = ALLOC_MULT(type_T *, type->tt_argcount);
77 	if (ret->tt_args != NULL)
78 	    for (i = 0; i < type->tt_argcount; ++i)
79 		ret->tt_args[i] = alloc_type(type->tt_args[i]);
80     }
81 
82     return ret;
83 }
84 
85 /*
86  * Free a type that was created with alloc_type().
87  */
88     void
89 free_type(type_T *type)
90 {
91     int i;
92 
93     if (type == NULL || (type->tt_flags & TTFLAG_STATIC))
94 	return;
95     if (type->tt_args != NULL)
96     {
97 	for (i = 0; i < type->tt_argcount; ++i)
98 	    free_type(type->tt_args[i]);
99 	vim_free(type->tt_args);
100     }
101     free_type(type->tt_member);
102     vim_free(type);
103 }
104 
105     type_T *
106 get_list_type(type_T *member_type, garray_T *type_gap)
107 {
108     type_T *type;
109 
110     // recognize commonly used types
111     if (member_type == NULL || member_type->tt_type == VAR_ANY)
112 	return &t_list_any;
113     if (member_type->tt_type == VAR_VOID
114 	    || member_type->tt_type == VAR_UNKNOWN)
115 	return &t_list_empty;
116     if (member_type->tt_type == VAR_BOOL)
117 	return &t_list_bool;
118     if (member_type->tt_type == VAR_NUMBER)
119 	return &t_list_number;
120     if (member_type->tt_type == VAR_STRING)
121 	return &t_list_string;
122 
123     // Not a common type, create a new entry.
124     type = get_type_ptr(type_gap);
125     if (type == NULL)
126 	return &t_any;
127     type->tt_type = VAR_LIST;
128     type->tt_member = member_type;
129     type->tt_argcount = 0;
130     type->tt_args = NULL;
131     return type;
132 }
133 
134     type_T *
135 get_dict_type(type_T *member_type, garray_T *type_gap)
136 {
137     type_T *type;
138 
139     // recognize commonly used types
140     if (member_type == NULL || member_type->tt_type == VAR_ANY)
141 	return &t_dict_any;
142     if (member_type->tt_type == VAR_VOID
143 	    || member_type->tt_type == VAR_UNKNOWN)
144 	return &t_dict_empty;
145     if (member_type->tt_type == VAR_BOOL)
146 	return &t_dict_bool;
147     if (member_type->tt_type == VAR_NUMBER)
148 	return &t_dict_number;
149     if (member_type->tt_type == VAR_STRING)
150 	return &t_dict_string;
151 
152     // Not a common type, create a new entry.
153     type = get_type_ptr(type_gap);
154     if (type == NULL)
155 	return &t_any;
156     type->tt_type = VAR_DICT;
157     type->tt_member = member_type;
158     type->tt_argcount = 0;
159     type->tt_args = NULL;
160     return type;
161 }
162 
163 /*
164  * Allocate a new type for a function.
165  */
166     type_T *
167 alloc_func_type(type_T *ret_type, int argcount, garray_T *type_gap)
168 {
169     type_T *type = get_type_ptr(type_gap);
170 
171     if (type == NULL)
172 	return &t_any;
173     type->tt_type = VAR_FUNC;
174     type->tt_member = ret_type;
175     type->tt_argcount = argcount;
176     type->tt_args = NULL;
177     return type;
178 }
179 
180 /*
181  * Get a function type, based on the return type "ret_type".
182  * If "argcount" is -1 or 0 a predefined type can be used.
183  * If "argcount" > 0 always create a new type, so that arguments can be added.
184  */
185     type_T *
186 get_func_type(type_T *ret_type, int argcount, garray_T *type_gap)
187 {
188     // recognize commonly used types
189     if (argcount <= 0)
190     {
191 	if (ret_type == &t_unknown)
192 	{
193 	    // (argcount == 0) is not possible
194 	    return &t_func_unknown;
195 	}
196 	if (ret_type == &t_void)
197 	{
198 	    if (argcount == 0)
199 		return &t_func_0_void;
200 	    else
201 		return &t_func_void;
202 	}
203 	if (ret_type == &t_any)
204 	{
205 	    if (argcount == 0)
206 		return &t_func_0_any;
207 	    else
208 		return &t_func_any;
209 	}
210 	if (ret_type == &t_number)
211 	{
212 	    if (argcount == 0)
213 		return &t_func_0_number;
214 	    else
215 		return &t_func_number;
216 	}
217 	if (ret_type == &t_string)
218 	{
219 	    if (argcount == 0)
220 		return &t_func_0_string;
221 	    else
222 		return &t_func_string;
223 	}
224     }
225 
226     return alloc_func_type(ret_type, argcount, type_gap);
227 }
228 
229 /*
230  * For a function type, reserve space for "argcount" argument types (including
231  * vararg).
232  */
233     int
234 func_type_add_arg_types(
235 	type_T	    *functype,
236 	int	    argcount,
237 	garray_T    *type_gap)
238 {
239     // To make it easy to free the space needed for the argument types, add the
240     // pointer to type_gap.
241     if (ga_grow(type_gap, 1) == FAIL)
242 	return FAIL;
243     functype->tt_args = ALLOC_CLEAR_MULT(type_T *, argcount);
244     if (functype->tt_args == NULL)
245 	return FAIL;
246     ((type_T **)type_gap->ga_data)[type_gap->ga_len] =
247 						     (void *)functype->tt_args;
248     ++type_gap->ga_len;
249     return OK;
250 }
251 
252 /*
253  * Get a type_T for a typval_T.
254  * "type_gap" is used to temporarily create types in.
255  */
256     static type_T *
257 typval2type_int(typval_T *tv, int copyID, garray_T *type_gap)
258 {
259     type_T  *type;
260     type_T  *member_type = &t_any;
261     int	    argcount = 0;
262 
263     if (tv->v_type == VAR_NUMBER)
264 	return &t_number;
265     if (tv->v_type == VAR_BOOL)
266 	return &t_bool;
267     if (tv->v_type == VAR_STRING)
268 	return &t_string;
269 
270     if (tv->v_type == VAR_LIST)
271     {
272 	list_T	    *l = tv->vval.v_list;
273 	listitem_T  *li;
274 
275 	if (l == NULL || l->lv_first == NULL)
276 	    return &t_list_empty;
277 	if (l->lv_first == &range_list_item)
278 	    return &t_list_number;
279 	if (l->lv_copyID == copyID)
280 	    // avoid recursion
281 	    return &t_list_any;
282 	l->lv_copyID = copyID;
283 
284 	// Use the common type of all members.
285 	member_type = typval2type(&l->lv_first->li_tv, copyID, type_gap);
286 	for (li = l->lv_first->li_next; li != NULL; li = li->li_next)
287 	    common_type(typval2type(&li->li_tv, copyID, type_gap),
288 					  member_type, &member_type, type_gap);
289 	return get_list_type(member_type, type_gap);
290     }
291 
292     if (tv->v_type == VAR_DICT)
293     {
294 	dict_iterator_T iter;
295 	typval_T	*value;
296 	dict_T		*d = tv->vval.v_dict;
297 
298 	if (d == NULL || d->dv_hashtab.ht_used == 0)
299 	    return &t_dict_empty;
300 	if (d->dv_copyID == copyID)
301 	    // avoid recursion
302 	    return &t_dict_any;
303 	d->dv_copyID = copyID;
304 
305 	// Use the common type of all values.
306 	dict_iterate_start(tv, &iter);
307 	dict_iterate_next(&iter, &value);
308 	member_type = typval2type(value, copyID, type_gap);
309 	while (dict_iterate_next(&iter, &value) != NULL)
310 	    common_type(typval2type(value, copyID, type_gap),
311 					  member_type, &member_type, type_gap);
312 	return get_dict_type(member_type, type_gap);
313     }
314 
315     if (tv->v_type == VAR_FUNC || tv->v_type == VAR_PARTIAL)
316     {
317 	char_u	*name = NULL;
318 	ufunc_T *ufunc = NULL;
319 
320 	if (tv->v_type == VAR_PARTIAL)
321 	{
322 	    if (tv->vval.v_partial->pt_func != NULL)
323 		ufunc = tv->vval.v_partial->pt_func;
324 	    else
325 		name = tv->vval.v_partial->pt_name;
326 	}
327 	else
328 	    name = tv->vval.v_string;
329 	if (name != NULL)
330 	{
331 	    int idx = find_internal_func(name);
332 
333 	    if (idx >= 0)
334 	    {
335 		// TODO: get actual arg count and types
336 		argcount = -1;
337 		member_type = internal_func_ret_type(idx, 0, NULL);
338 	    }
339 	    else
340 		ufunc = find_func(name, FALSE, NULL);
341 	}
342 	if (ufunc != NULL)
343 	{
344 	    // May need to get the argument types from default values by
345 	    // compiling the function.
346 	    if (ufunc->uf_def_status == UF_TO_BE_COMPILED
347 			    && compile_def_function(ufunc, TRUE, FALSE, NULL)
348 								       == FAIL)
349 		return NULL;
350 	    if (ufunc->uf_func_type == NULL)
351 		set_function_type(ufunc);
352 	    if (ufunc->uf_func_type != NULL)
353 		return ufunc->uf_func_type;
354 	}
355     }
356 
357     type = get_type_ptr(type_gap);
358     if (type == NULL)
359 	return NULL;
360     type->tt_type = tv->v_type;
361     type->tt_argcount = argcount;
362     type->tt_member = member_type;
363 
364     return type;
365 }
366 
367 /*
368  * Return TRUE if "tv" is not a bool but should be converted to bool.
369  */
370     int
371 need_convert_to_bool(type_T *type, typval_T *tv)
372 {
373     return type != NULL && type == &t_bool && tv->v_type != VAR_BOOL
374 	    && (tv->v_type == VAR_NUMBER
375 		       && (tv->vval.v_number == 0 || tv->vval.v_number == 1));
376 }
377 
378 /*
379  * Get a type_T for a typval_T.
380  * "type_list" is used to temporarily create types in.
381  */
382     type_T *
383 typval2type(typval_T *tv, int copyID, garray_T *type_gap)
384 {
385     type_T *type = typval2type_int(tv, copyID, type_gap);
386 
387     if (type != NULL && type != &t_bool
388 	    && (tv->v_type == VAR_NUMBER
389 		    && (tv->vval.v_number == 0 || tv->vval.v_number == 1)))
390 	// Number 0 and 1 and expression with "&&" or "||" can also be used for
391 	// bool.
392 	type = &t_number_bool;
393     return type;
394 }
395 
396 /*
397  * Get a type_T for a typval_T, used for v: variables.
398  * "type_list" is used to temporarily create types in.
399  */
400     type_T *
401 typval2type_vimvar(typval_T *tv, garray_T *type_gap)
402 {
403     if (tv->v_type == VAR_LIST)  // e.g. for v:oldfiles
404 	return &t_list_string;
405     if (tv->v_type == VAR_DICT)  // e.g. for v:completed_item
406 	return &t_dict_any;
407     return typval2type(tv, get_copyID(), type_gap);
408 }
409 
410     int
411 check_typval_arg_type(type_T *expected, typval_T *actual_tv, int arg_idx)
412 {
413     where_T	where;
414 
415     where.wt_index = arg_idx;
416     where.wt_variable = FALSE;
417     return check_typval_type(expected, actual_tv, where);
418 }
419 
420 /*
421  * Return FAIL if "expected" and "actual" don't match.
422  * When "argidx" > 0 it is included in the error message.
423  */
424     int
425 check_typval_type(type_T *expected, typval_T *actual_tv, where_T where)
426 {
427     garray_T	type_list;
428     type_T	*actual_type;
429     int		res = FAIL;
430 
431     ga_init2(&type_list, sizeof(type_T *), 10);
432     actual_type = typval2type(actual_tv, get_copyID(), &type_list);
433     if (actual_type != NULL)
434 	res = check_type(expected, actual_type, TRUE, where);
435     clear_type_list(&type_list);
436     return res;
437 }
438 
439     void
440 type_mismatch(type_T *expected, type_T *actual)
441 {
442     arg_type_mismatch(expected, actual, 0);
443 }
444 
445     void
446 arg_type_mismatch(type_T *expected, type_T *actual, int arg_idx)
447 {
448     where_T	where;
449 
450     where.wt_index = arg_idx;
451     where.wt_variable = FALSE;
452     type_mismatch_where(expected, actual, where);
453 }
454 
455     void
456 type_mismatch_where(type_T *expected, type_T *actual, where_T where)
457 {
458     char *tofree1, *tofree2;
459     char *typename1 = type_name(expected, &tofree1);
460     char *typename2 = type_name(actual, &tofree2);
461 
462     if (where.wt_index > 0)
463     {
464 	semsg(_(where.wt_variable
465 			? e_variable_nr_type_mismatch_expected_str_but_got_str
466 			: e_argument_nr_type_mismatch_expected_str_but_got_str),
467 					 where.wt_index, typename1, typename2);
468     }
469     else
470 	semsg(_(e_type_mismatch_expected_str_but_got_str),
471 							 typename1, typename2);
472     vim_free(tofree1);
473     vim_free(tofree2);
474 }
475 
476 /*
477  * Check if the expected and actual types match.
478  * Does not allow for assigning "any" to a specific type.
479  * When "argidx" > 0 it is included in the error message.
480  */
481     int
482 check_type(type_T *expected, type_T *actual, int give_msg, where_T where)
483 {
484     int ret = OK;
485 
486     // When expected is "unknown" we accept any actual type.
487     // When expected is "any" we accept any actual type except "void".
488     if (expected->tt_type != VAR_UNKNOWN
489 	    && !(expected->tt_type == VAR_ANY && actual->tt_type != VAR_VOID))
490 
491     {
492 	// tt_type should match, except that a "partial" can be assigned to a
493 	// variable with type "func".
494 	if (!(expected->tt_type == actual->tt_type
495 		    || (expected->tt_type == VAR_FUNC
496 					   && actual->tt_type == VAR_PARTIAL)))
497 	{
498 	    if (expected->tt_type == VAR_BOOL
499 					&& (actual->tt_flags & TTFLAG_BOOL_OK))
500 		// Using number 0 or 1 for bool is OK.
501 		return OK;
502 	    if (give_msg)
503 		type_mismatch_where(expected, actual, where);
504 	    return FAIL;
505 	}
506 	if (expected->tt_type == VAR_DICT || expected->tt_type == VAR_LIST)
507 	{
508 	    // "unknown" is used for an empty list or dict
509 	    if (actual->tt_member != &t_unknown)
510 		ret = check_type(expected->tt_member, actual->tt_member,
511 								 FALSE, where);
512 	}
513 	else if (expected->tt_type == VAR_FUNC)
514 	{
515 	    // If the return type is unknown it can be anything, including
516 	    // nothing, thus there is no point in checking.
517 	    if (expected->tt_member != &t_unknown
518 					    && actual->tt_member != &t_unknown)
519 		ret = check_type(expected->tt_member, actual->tt_member,
520 								 FALSE, where);
521 	    if (ret == OK && expected->tt_argcount != -1
522 		    && actual->tt_argcount != -1
523 		    && (actual->tt_argcount < expected->tt_min_argcount
524 			|| actual->tt_argcount > expected->tt_argcount))
525 		ret = FAIL;
526 	    if (ret == OK && expected->tt_args != NULL
527 						    && actual->tt_args != NULL)
528 	    {
529 		int i;
530 
531 		for (i = 0; i < expected->tt_argcount; ++i)
532 		    // Allow for using "any" argument type, lambda's have them.
533 		    if (actual->tt_args[i] != &t_any && check_type(
534 			    expected->tt_args[i], actual->tt_args[i], FALSE,
535 								where) == FAIL)
536 		    {
537 			ret = FAIL;
538 			break;
539 		    }
540 	    }
541 	}
542 	if (ret == FAIL && give_msg)
543 	    type_mismatch_where(expected, actual, where);
544     }
545     return ret;
546 }
547 
548 /*
549  * Check that the arguments of "type" match "argvars[argcount]".
550  * Return OK/FAIL.
551  */
552     int
553 check_argument_types(
554 	type_T	    *type,
555 	typval_T    *argvars,
556 	int	    argcount,
557 	char_u	    *name)
558 {
559     int	    varargs = (type->tt_flags & TTFLAG_VARARGS) ? 1 : 0;
560     int	    i;
561 
562     if (type->tt_type != VAR_FUNC && type->tt_type != VAR_PARTIAL)
563 	return OK;  // just in case
564     if (argcount < type->tt_min_argcount - varargs)
565     {
566 	semsg(_(e_toofewarg), name);
567 	return FAIL;
568     }
569     if (!varargs && type->tt_argcount >= 0 && argcount > type->tt_argcount)
570     {
571 	semsg(_(e_toomanyarg), name);
572 	return FAIL;
573     }
574     if (type->tt_args == NULL)
575 	return OK;  // cannot check
576 
577 
578     for (i = 0; i < argcount; ++i)
579     {
580 	type_T	*expected;
581 
582 	if (varargs && i >= type->tt_argcount - 1)
583 	    expected = type->tt_args[type->tt_argcount - 1]->tt_member;
584 	else
585 	    expected = type->tt_args[i];
586 	if (check_typval_arg_type(expected, &argvars[i], i + 1) == FAIL)
587 	    return FAIL;
588     }
589     return OK;
590 }
591 
592 /*
593  * Skip over a type definition and return a pointer to just after it.
594  * When "optional" is TRUE then a leading "?" is accepted.
595  */
596     char_u *
597 skip_type(char_u *start, int optional)
598 {
599     char_u *p = start;
600 
601     if (optional && *p == '?')
602 	++p;
603     while (ASCII_ISALNUM(*p) || *p == '_')
604 	++p;
605 
606     // Skip over "<type>"; this is permissive about white space.
607     if (*skipwhite(p) == '<')
608     {
609 	p = skipwhite(p);
610 	p = skip_type(skipwhite(p + 1), FALSE);
611 	p = skipwhite(p);
612 	if (*p == '>')
613 	    ++p;
614     }
615     else if ((*p == '(' || (*p == ':' && VIM_ISWHITE(p[1])))
616 					     && STRNCMP("func", start, 4) == 0)
617     {
618 	if (*p == '(')
619 	{
620 	    // handle func(args): type
621 	    ++p;
622 	    while (*p != ')' && *p != NUL)
623 	    {
624 		char_u *sp = p;
625 
626 		if (STRNCMP(p, "...", 3) == 0)
627 		    p += 3;
628 		p = skip_type(p, TRUE);
629 		if (p == sp)
630 		    return p;  // syntax error
631 		if (*p == ',')
632 		    p = skipwhite(p + 1);
633 	    }
634 	    if (*p == ')')
635 	    {
636 		if (p[1] == ':')
637 		    p = skip_type(skipwhite(p + 2), FALSE);
638 		else
639 		    ++p;
640 	    }
641 	}
642 	else
643 	{
644 	    // handle func: return_type
645 	    p = skip_type(skipwhite(p + 1), FALSE);
646 	}
647     }
648 
649     return p;
650 }
651 
652 /*
653  * Parse the member type: "<type>" and return "type" with the member set.
654  * Use "type_gap" if a new type needs to be added.
655  * Returns NULL in case of failure.
656  */
657     static type_T *
658 parse_type_member(
659 	char_u	    **arg,
660 	type_T	    *type,
661 	garray_T    *type_gap,
662 	int	    give_error)
663 {
664     type_T  *member_type;
665     int	    prev_called_emsg = called_emsg;
666 
667     if (**arg != '<')
668     {
669 	if (give_error)
670 	{
671 	    if (*skipwhite(*arg) == '<')
672 		semsg(_(e_no_white_space_allowed_before_str_str), "<", *arg);
673 	    else
674 		emsg(_(e_missing_type));
675 	}
676 	return NULL;
677     }
678     *arg = skipwhite(*arg + 1);
679 
680     member_type = parse_type(arg, type_gap, give_error);
681     if (member_type == NULL)
682 	return NULL;
683 
684     *arg = skipwhite(*arg);
685     if (**arg != '>' && called_emsg == prev_called_emsg)
686     {
687 	if (give_error)
688 	    emsg(_(e_missing_gt_after_type));
689 	return NULL;
690     }
691     ++*arg;
692 
693     if (type->tt_type == VAR_LIST)
694 	return get_list_type(member_type, type_gap);
695     return get_dict_type(member_type, type_gap);
696 }
697 
698 /*
699  * Parse a type at "arg" and advance over it.
700  * When "give_error" is TRUE give error messages, otherwise be quiet.
701  * Return NULL for failure.
702  */
703     type_T *
704 parse_type(char_u **arg, garray_T *type_gap, int give_error)
705 {
706     char_u  *p = *arg;
707     size_t  len;
708 
709     // skip over the first word
710     while (ASCII_ISALNUM(*p) || *p == '_')
711 	++p;
712     len = p - *arg;
713 
714     switch (**arg)
715     {
716 	case 'a':
717 	    if (len == 3 && STRNCMP(*arg, "any", len) == 0)
718 	    {
719 		*arg += len;
720 		return &t_any;
721 	    }
722 	    break;
723 	case 'b':
724 	    if (len == 4 && STRNCMP(*arg, "bool", len) == 0)
725 	    {
726 		*arg += len;
727 		return &t_bool;
728 	    }
729 	    if (len == 4 && STRNCMP(*arg, "blob", len) == 0)
730 	    {
731 		*arg += len;
732 		return &t_blob;
733 	    }
734 	    break;
735 	case 'c':
736 	    if (len == 7 && STRNCMP(*arg, "channel", len) == 0)
737 	    {
738 		*arg += len;
739 		return &t_channel;
740 	    }
741 	    break;
742 	case 'd':
743 	    if (len == 4 && STRNCMP(*arg, "dict", len) == 0)
744 	    {
745 		*arg += len;
746 		return parse_type_member(arg, &t_dict_any,
747 							 type_gap, give_error);
748 	    }
749 	    break;
750 	case 'f':
751 	    if (len == 5 && STRNCMP(*arg, "float", len) == 0)
752 	    {
753 #ifdef FEAT_FLOAT
754 		*arg += len;
755 		return &t_float;
756 #else
757 		if (give_error)
758 		    emsg(_(e_this_vim_is_not_compiled_with_float_support));
759 		return NULL;
760 #endif
761 	    }
762 	    if (len == 4 && STRNCMP(*arg, "func", len) == 0)
763 	    {
764 		type_T  *type;
765 		type_T  *ret_type = &t_unknown;
766 		int	argcount = -1;
767 		int	flags = 0;
768 		int	first_optional = -1;
769 		type_T	*arg_type[MAX_FUNC_ARGS + 1];
770 
771 		// func({type}, ...{type}): {type}
772 		*arg += len;
773 		if (**arg == '(')
774 		{
775 		    // "func" may or may not return a value, "func()" does
776 		    // not return a value.
777 		    ret_type = &t_void;
778 
779 		    p = ++*arg;
780 		    argcount = 0;
781 		    while (*p != NUL && *p != ')')
782 		    {
783 			if (*p == '?')
784 			{
785 			    if (first_optional == -1)
786 				first_optional = argcount;
787 			    ++p;
788 			}
789 			else if (STRNCMP(p, "...", 3) == 0)
790 			{
791 			    flags |= TTFLAG_VARARGS;
792 			    p += 3;
793 			}
794 			else if (first_optional != -1)
795 			{
796 			    if (give_error)
797 				emsg(_(e_mandatory_argument_after_optional_argument));
798 			    return NULL;
799 			}
800 
801 			type = parse_type(&p, type_gap, give_error);
802 			if (type == NULL)
803 			    return NULL;
804 			arg_type[argcount++] = type;
805 
806 			// Nothing comes after "...{type}".
807 			if (flags & TTFLAG_VARARGS)
808 			    break;
809 
810 			if (*p != ',' && *skipwhite(p) == ',')
811 			{
812 			    if (give_error)
813 				semsg(_(e_no_white_space_allowed_before_str_str),
814 								       ",", p);
815 			    return NULL;
816 			}
817 			if (*p == ',')
818 			{
819 			    ++p;
820 			    if (!VIM_ISWHITE(*p))
821 			    {
822 				if (give_error)
823 				    semsg(_(e_white_space_required_after_str_str),
824 								   ",", p - 1);
825 				return NULL;
826 			    }
827 			}
828 			p = skipwhite(p);
829 			if (argcount == MAX_FUNC_ARGS)
830 			{
831 			    if (give_error)
832 				emsg(_(e_too_many_argument_types));
833 			    return NULL;
834 			}
835 		    }
836 
837 		    p = skipwhite(p);
838 		    if (*p != ')')
839 		    {
840 			if (give_error)
841 			    emsg(_(e_missing_close));
842 			return NULL;
843 		    }
844 		    *arg = p + 1;
845 		}
846 		if (**arg == ':')
847 		{
848 		    // parse return type
849 		    ++*arg;
850 		    if (!VIM_ISWHITE(**arg) && give_error)
851 			semsg(_(e_white_space_required_after_str_str),
852 								":", *arg - 1);
853 		    *arg = skipwhite(*arg);
854 		    ret_type = parse_type(arg, type_gap, give_error);
855 		    if (ret_type == NULL)
856 			return NULL;
857 		}
858 		if (flags == 0 && first_optional == -1 && argcount <= 0)
859 		    type = get_func_type(ret_type, argcount, type_gap);
860 		else
861 		{
862 		    type = alloc_func_type(ret_type, argcount, type_gap);
863 		    type->tt_flags = flags;
864 		    if (argcount > 0)
865 		    {
866 			type->tt_argcount = argcount;
867 			type->tt_min_argcount = first_optional == -1
868 						   ? argcount : first_optional;
869 			if (func_type_add_arg_types(type, argcount,
870 							     type_gap) == FAIL)
871 			    return NULL;
872 			mch_memmove(type->tt_args, arg_type,
873 						  sizeof(type_T *) * argcount);
874 		    }
875 		}
876 		return type;
877 	    }
878 	    break;
879 	case 'j':
880 	    if (len == 3 && STRNCMP(*arg, "job", len) == 0)
881 	    {
882 		*arg += len;
883 		return &t_job;
884 	    }
885 	    break;
886 	case 'l':
887 	    if (len == 4 && STRNCMP(*arg, "list", len) == 0)
888 	    {
889 		*arg += len;
890 		return parse_type_member(arg, &t_list_any,
891 							 type_gap, give_error);
892 	    }
893 	    break;
894 	case 'n':
895 	    if (len == 6 && STRNCMP(*arg, "number", len) == 0)
896 	    {
897 		*arg += len;
898 		return &t_number;
899 	    }
900 	    break;
901 	case 's':
902 	    if (len == 6 && STRNCMP(*arg, "string", len) == 0)
903 	    {
904 		*arg += len;
905 		return &t_string;
906 	    }
907 	    break;
908 	case 'v':
909 	    if (len == 4 && STRNCMP(*arg, "void", len) == 0)
910 	    {
911 		*arg += len;
912 		return &t_void;
913 	    }
914 	    break;
915     }
916 
917     if (give_error)
918 	semsg(_(e_type_not_recognized_str), *arg);
919     return NULL;
920 }
921 
922 /*
923  * Check if "type1" and "type2" are exactly the same.
924  */
925     int
926 equal_type(type_T *type1, type_T *type2)
927 {
928     int i;
929 
930     if (type1 == NULL || type2 == NULL)
931 	return FALSE;
932     if (type1->tt_type != type2->tt_type)
933 	return FALSE;
934     switch (type1->tt_type)
935     {
936 	case VAR_UNKNOWN:
937 	case VAR_ANY:
938 	case VAR_VOID:
939 	case VAR_SPECIAL:
940 	case VAR_BOOL:
941 	case VAR_NUMBER:
942 	case VAR_FLOAT:
943 	case VAR_STRING:
944 	case VAR_BLOB:
945 	case VAR_JOB:
946 	case VAR_CHANNEL:
947 	    break;  // not composite is always OK
948 	case VAR_LIST:
949 	case VAR_DICT:
950 	    return equal_type(type1->tt_member, type2->tt_member);
951 	case VAR_FUNC:
952 	case VAR_PARTIAL:
953 	    if (!equal_type(type1->tt_member, type2->tt_member)
954 		    || type1->tt_argcount != type2->tt_argcount)
955 		return FALSE;
956 	    if (type1->tt_argcount < 0
957 			   || type1->tt_args == NULL || type2->tt_args == NULL)
958 		return TRUE;
959 	    for (i = 0; i < type1->tt_argcount; ++i)
960 		if (!equal_type(type1->tt_args[i], type2->tt_args[i]))
961 		    return FALSE;
962 	    return TRUE;
963     }
964     return TRUE;
965 }
966 
967 /*
968  * Find the common type of "type1" and "type2" and put it in "dest".
969  * "type2" and "dest" may be the same.
970  */
971     void
972 common_type(type_T *type1, type_T *type2, type_T **dest, garray_T *type_gap)
973 {
974     if (equal_type(type1, type2))
975     {
976 	*dest = type1;
977 	return;
978     }
979 
980     // If either is VAR_UNKNOWN use the other type.  An empty list/dict has no
981     // specific type.
982     if (type1 == NULL || type1->tt_type == VAR_UNKNOWN)
983     {
984 	*dest = type2;
985 	return;
986     }
987     if (type2 == NULL || type2->tt_type == VAR_UNKNOWN)
988     {
989 	*dest = type1;
990 	return;
991     }
992 
993     if (type1->tt_type == type2->tt_type)
994     {
995 	if (type1->tt_type == VAR_LIST || type2->tt_type == VAR_DICT)
996 	{
997 	    type_T *common;
998 
999 	    common_type(type1->tt_member, type2->tt_member, &common, type_gap);
1000 	    if (type1->tt_type == VAR_LIST)
1001 		*dest = get_list_type(common, type_gap);
1002 	    else
1003 		*dest = get_dict_type(common, type_gap);
1004 	    return;
1005 	}
1006 	if (type1->tt_type == VAR_FUNC)
1007 	{
1008 	    type_T *common;
1009 
1010 	    common_type(type1->tt_member, type2->tt_member, &common, type_gap);
1011 	    if (type1->tt_argcount == type2->tt_argcount
1012 						    && type1->tt_argcount >= 0)
1013 	    {
1014 		int argcount = type1->tt_argcount;
1015 		int i;
1016 
1017 		*dest = alloc_func_type(common, argcount, type_gap);
1018 		if (type1->tt_args != NULL && type2->tt_args != NULL)
1019 		{
1020 		    if (func_type_add_arg_types(*dest, argcount,
1021 							     type_gap) == OK)
1022 			for (i = 0; i < argcount; ++i)
1023 			    common_type(type1->tt_args[i], type2->tt_args[i],
1024 					       &(*dest)->tt_args[i], type_gap);
1025 		}
1026 	    }
1027 	    else
1028 		*dest = alloc_func_type(common, -1, type_gap);
1029 	    // Use the minimum of min_argcount.
1030 	    (*dest)->tt_min_argcount =
1031 			type1->tt_min_argcount < type2->tt_min_argcount
1032 			     ? type1->tt_min_argcount : type2->tt_min_argcount;
1033 	    return;
1034 	}
1035     }
1036 
1037     *dest = &t_any;
1038 }
1039 
1040 /*
1041  * Get the member type of a dict or list from the items on the stack.
1042  * "stack_top" points just after the last type on the type stack.
1043  * For a list "skip" is 1, for a dict "skip" is 2, keys are skipped.
1044  * Returns &t_void for an empty list or dict.
1045  * Otherwise finds the common type of all items.
1046  */
1047     type_T *
1048 get_member_type_from_stack(
1049 	type_T	    **stack_top,
1050 	int	    count,
1051 	int	    skip,
1052 	garray_T    *type_gap)
1053 {
1054     int	    i;
1055     type_T  *result;
1056     type_T  *type;
1057 
1058     // Use "any" for an empty list or dict.
1059     if (count == 0)
1060 	return &t_unknown;
1061 
1062     // Use the first value type for the list member type, then find the common
1063     // type from following items.
1064     result = *(stack_top -(count * skip) + skip - 1);
1065     for (i = 1; i < count; ++i)
1066     {
1067 	if (result == &t_any)
1068 	    break;  // won't get more common
1069 	type = *(stack_top -((count - i) * skip) + skip - 1);
1070 	common_type(type, result, &result, type_gap);
1071     }
1072 
1073     return result;
1074 }
1075 
1076     char *
1077 vartype_name(vartype_T type)
1078 {
1079     switch (type)
1080     {
1081 	case VAR_UNKNOWN: break;
1082 	case VAR_ANY: return "any";
1083 	case VAR_VOID: return "void";
1084 	case VAR_SPECIAL: return "special";
1085 	case VAR_BOOL: return "bool";
1086 	case VAR_NUMBER: return "number";
1087 	case VAR_FLOAT: return "float";
1088 	case VAR_STRING: return "string";
1089 	case VAR_BLOB: return "blob";
1090 	case VAR_JOB: return "job";
1091 	case VAR_CHANNEL: return "channel";
1092 	case VAR_LIST: return "list";
1093 	case VAR_DICT: return "dict";
1094 
1095 	case VAR_FUNC:
1096 	case VAR_PARTIAL: return "func";
1097     }
1098     return "unknown";
1099 }
1100 
1101 /*
1102  * Return the name of a type.
1103  * The result may be in allocated memory, in which case "tofree" is set.
1104  */
1105     char *
1106 type_name(type_T *type, char **tofree)
1107 {
1108     char *name;
1109 
1110     *tofree = NULL;
1111     if (type == NULL)
1112 	return "[unknown]";
1113     name = vartype_name(type->tt_type);
1114     if (type->tt_type == VAR_LIST || type->tt_type == VAR_DICT)
1115     {
1116 	char *member_free;
1117 	char *member_name = type_name(type->tt_member, &member_free);
1118 	size_t len;
1119 
1120 	len = STRLEN(name) + STRLEN(member_name) + 3;
1121 	*tofree = alloc(len);
1122 	if (*tofree != NULL)
1123 	{
1124 	    vim_snprintf(*tofree, len, "%s<%s>", name, member_name);
1125 	    vim_free(member_free);
1126 	    return *tofree;
1127 	}
1128     }
1129     if (type->tt_type == VAR_FUNC)
1130     {
1131 	garray_T    ga;
1132 	int	    i;
1133 	int	    varargs = (type->tt_flags & TTFLAG_VARARGS) ? 1 : 0;
1134 
1135 	ga_init2(&ga, 1, 100);
1136 	if (ga_grow(&ga, 20) == FAIL)
1137 	    return "[unknown]";
1138 	STRCPY(ga.ga_data, "func(");
1139 	ga.ga_len += 5;
1140 
1141 	for (i = 0; i < type->tt_argcount; ++i)
1142 	{
1143 	    char *arg_free;
1144 	    char *arg_type;
1145 	    int  len;
1146 
1147 	    if (type->tt_args == NULL)
1148 		arg_type = "[unknown]";
1149 	    else
1150 		arg_type = type_name(type->tt_args[i], &arg_free);
1151 	    if (i > 0)
1152 	    {
1153 		STRCPY((char *)ga.ga_data + ga.ga_len, ", ");
1154 		ga.ga_len += 2;
1155 	    }
1156 	    len = (int)STRLEN(arg_type);
1157 	    if (ga_grow(&ga, len + 8) == FAIL)
1158 	    {
1159 		vim_free(arg_free);
1160 		ga_clear(&ga);
1161 		return "[unknown]";
1162 	    }
1163 	    if (varargs && i == type->tt_argcount - 1)
1164 		ga_concat(&ga, (char_u *)"...");
1165 	    else if (i >= type->tt_min_argcount)
1166 		*((char *)ga.ga_data + ga.ga_len++) = '?';
1167 	    ga_concat(&ga, (char_u *)arg_type);
1168 	    vim_free(arg_free);
1169 	}
1170 	if (type->tt_argcount < 0)
1171 	    // any number of arguments
1172 	    ga_concat(&ga, (char_u *)"...");
1173 
1174 	if (type->tt_member == &t_void)
1175 	    STRCPY((char *)ga.ga_data + ga.ga_len, ")");
1176 	else
1177 	{
1178 	    char *ret_free;
1179 	    char *ret_name = type_name(type->tt_member, &ret_free);
1180 	    int  len;
1181 
1182 	    len = (int)STRLEN(ret_name) + 4;
1183 	    if (ga_grow(&ga, len) == FAIL)
1184 	    {
1185 		vim_free(ret_free);
1186 		ga_clear(&ga);
1187 		return "[unknown]";
1188 	    }
1189 	    STRCPY((char *)ga.ga_data + ga.ga_len, "): ");
1190 	    STRCPY((char *)ga.ga_data + ga.ga_len + 3, ret_name);
1191 	    vim_free(ret_free);
1192 	}
1193 	*tofree = ga.ga_data;
1194 	return ga.ga_data;
1195     }
1196 
1197     return name;
1198 }
1199 
1200 /*
1201  * "typename(expr)" function
1202  */
1203     void
1204 f_typename(typval_T *argvars, typval_T *rettv)
1205 {
1206     garray_T	type_list;
1207     type_T	*type;
1208     char	*tofree;
1209     char	*name;
1210 
1211     rettv->v_type = VAR_STRING;
1212     ga_init2(&type_list, sizeof(type_T *), 10);
1213     type = typval2type(argvars, get_copyID(), &type_list);
1214     name = type_name(type, &tofree);
1215     if (tofree != NULL)
1216 	rettv->vval.v_string = (char_u *)tofree;
1217     else
1218     {
1219 	rettv->vval.v_string = vim_strsave((char_u *)name);
1220 	vim_free(tofree);
1221     }
1222     clear_type_list(&type_list);
1223 }
1224 
1225 #endif // FEAT_EVAL
1226