xref: /vim-8.2.3635/src/vim9script.c (revision 53f7fccc)
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  * vim9script.c: :vim9script, :import, :export and friends
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_EVAL)
17 # include "vim9.h"
18 #endif
19 
20 /*
21  * Return TRUE when currently using Vim9 script syntax.
22  * Does not go up the stack, a ":function" inside vim9script uses legacy
23  * syntax.
24  */
25     int
26 in_vim9script(void)
27 {
28     // "sc_version" is also set when compiling a ":def" function in legacy
29     // script.
30     return (current_sctx.sc_version == SCRIPT_VERSION_VIM9
31 					 || (cmdmod.cmod_flags & CMOD_VIM9CMD))
32 		&& !(cmdmod.cmod_flags & CMOD_LEGACY);
33 }
34 
35 #if defined(FEAT_EVAL) || defined(PROTO)
36 /*
37  * Return TRUE if the current script is Vim9 script.
38  * This also returns TRUE in a legacy function in a Vim9 script.
39  */
40     int
41 current_script_is_vim9(void)
42 {
43     return SCRIPT_ID_VALID(current_sctx.sc_sid)
44 	    && SCRIPT_ITEM(current_sctx.sc_sid)->sn_version
45 						       == SCRIPT_VERSION_VIM9;
46 }
47 #endif
48 
49 /*
50  * ":vim9script".
51  */
52     void
53 ex_vim9script(exarg_T *eap UNUSED)
54 {
55 #ifdef FEAT_EVAL
56     int		    sid = current_sctx.sc_sid;
57     scriptitem_T    *si;
58 
59     if (!getline_equal(eap->getline, eap->cookie, getsourceline))
60     {
61 	emsg(_(e_vim9script_can_only_be_used_in_script));
62 	return;
63     }
64 
65     si = SCRIPT_ITEM(sid);
66     if (si->sn_state == SN_STATE_HAD_COMMAND)
67     {
68 	emsg(_(e_vim9script_must_be_first_command_in_script));
69 	return;
70     }
71     if (!IS_WHITE_OR_NUL(*eap->arg) && STRCMP(eap->arg, "noclear") != 0)
72     {
73 	semsg(_(e_invarg2), eap->arg);
74 	return;
75     }
76     if (si->sn_state == SN_STATE_RELOAD && IS_WHITE_OR_NUL(*eap->arg))
77     {
78 	hashtab_T	*ht = &SCRIPT_VARS(sid);
79 
80 	// Reloading a script without the "noclear" argument: clear
81 	// script-local variables and functions.
82 	hashtab_free_contents(ht);
83 	hash_init(ht);
84 	delete_script_functions(sid);
85 
86 	// old imports and script variables are no longer valid
87 	free_imports_and_script_vars(sid);
88     }
89     si->sn_state = SN_STATE_HAD_COMMAND;
90 
91     current_sctx.sc_version = SCRIPT_VERSION_VIM9;
92     si->sn_version = SCRIPT_VERSION_VIM9;
93 
94     if (STRCMP(p_cpo, CPO_VIM) != 0)
95     {
96 	si->sn_save_cpo = vim_strsave(p_cpo);
97 	set_option_value((char_u *)"cpo", 0L, (char_u *)CPO_VIM, OPT_NO_REDRAW);
98     }
99 #else
100     // No check for this being the first command, it doesn't matter.
101     current_sctx.sc_version = SCRIPT_VERSION_VIM9;
102 #endif
103 }
104 
105 /*
106  * When in Vim9 script give an error and return FAIL.
107  */
108     int
109 not_in_vim9(exarg_T *eap)
110 {
111     if (in_vim9script())
112 	switch (eap->cmdidx)
113 	{
114 	    case CMD_k:
115 		if (eap->addr_count > 0)
116 		{
117 		    emsg(_(e_norange));
118 		    return FAIL;
119 		}
120 		// FALLTHROUGH
121 	    case CMD_append:
122 	    case CMD_change:
123 	    case CMD_insert:
124 	    case CMD_open:
125 	    case CMD_t:
126 	    case CMD_xit:
127 		semsg(_(e_command_not_supported_in_vim9_script_missing_var_str), eap->cmd);
128 		return FAIL;
129 	    default: break;
130 	}
131     return OK;
132 }
133 
134 /*
135  * Give an error message if "p" points at "#{" and return TRUE.
136  * This avoids that using a legacy style #{} dictionary leads to difficult to
137  * understand errors.
138  */
139     int
140 vim9_bad_comment(char_u *p)
141 {
142     if (p[0] == '#' && p[1] == '{' && p[2] != '{')
143     {
144 	emsg(_(e_cannot_use_hash_curly_to_start_comment));
145 	return TRUE;
146     }
147     return FALSE;
148 }
149 
150 /*
151  * Return TRUE if "p" points at a "#" not followed by one '{'.
152  * Does not check for white space.
153  */
154     int
155 vim9_comment_start(char_u *p)
156 {
157     return p[0] == '#' && (p[1] != '{' || p[2] == '{');
158 }
159 
160 #if defined(FEAT_EVAL) || defined(PROTO)
161 
162 /*
163  * "++nr" and "--nr" commands.
164  */
165     void
166 ex_incdec(exarg_T *eap)
167 {
168     char_u	*cmd = eap->cmd;
169     char_u	*nextcmd = eap->nextcmd;
170     size_t	len = STRLEN(eap->cmd) + 8;
171 
172     if (VIM_ISWHITE(cmd[2]))
173     {
174 	semsg(_(e_no_white_space_allowed_after_str_str),
175 			 eap->cmdidx == CMD_increment ? "++" : "--", eap->cmd);
176 	return;
177     }
178 
179     // This works like "nr += 1" or "nr -= 1".
180     // Add a '|' to avoid looking in the next line.
181     eap->cmd = alloc(len);
182     if (eap->cmd == NULL)
183 	return;
184     vim_snprintf((char *)eap->cmd, len, "%s %c= 1 |", cmd + 2,
185 				     eap->cmdidx == CMD_increment ? '+' : '-');
186     eap->arg = eap->cmd;
187     eap->cmdidx = CMD_var;
188     eap->nextcmd = NULL;
189     ex_let(eap);
190     vim_free(eap->cmd);
191     eap->cmd = cmd;
192     eap->nextcmd = nextcmd;
193 }
194 
195 /*
196  * ":export let Name: type"
197  * ":export const Name: type"
198  * ":export def Name(..."
199  * ":export class Name ..."
200  */
201     void
202 ex_export(exarg_T *eap)
203 {
204     if (!in_vim9script())
205     {
206 	emsg(_(e_export_can_only_be_used_in_vim9script));
207 	return;
208     }
209 
210     eap->cmd = eap->arg;
211     (void)find_ex_command(eap, NULL, lookup_scriptitem, NULL);
212     switch (eap->cmdidx)
213     {
214 	case CMD_let:
215 	case CMD_var:
216 	case CMD_final:
217 	case CMD_const:
218 	case CMD_def:
219 	// case CMD_class:
220 	    is_export = TRUE;
221 	    do_cmdline(eap->cmd, eap->getline, eap->cookie,
222 						DOCMD_VERBOSE + DOCMD_NOWAIT);
223 
224 	    // The command will reset "is_export" when exporting an item.
225 	    if (is_export)
226 	    {
227 		emsg(_(e_export_with_invalid_argument));
228 		is_export = FALSE;
229 	    }
230 	    break;
231 	default:
232 	    emsg(_(e_invalid_command_after_export));
233 	    break;
234     }
235 }
236 
237 /*
238  * Add a new imported item entry to the current script.
239  */
240     static imported_T *
241 new_imported(garray_T *gap)
242 {
243     if (ga_grow(gap, 1) == OK)
244 	return ((imported_T *)gap->ga_data + gap->ga_len++);
245     return NULL;
246 }
247 
248 /*
249  * Free all imported items in script "sid".
250  */
251     void
252 free_imports_and_script_vars(int sid)
253 {
254     scriptitem_T    *si = SCRIPT_ITEM(sid);
255     int		    idx;
256 
257     for (idx = 0; idx < si->sn_imports.ga_len; ++idx)
258     {
259 	imported_T *imp = ((imported_T *)si->sn_imports.ga_data) + idx;
260 
261 	vim_free(imp->imp_name);
262     }
263     ga_clear(&si->sn_imports);
264 
265     free_all_script_vars(si);
266 
267     clear_type_list(&si->sn_type_list);
268 }
269 
270 /*
271  * Mark all imports as possible to redefine.  Used when a script is loaded
272  * again but not cleared.
273  */
274     void
275 mark_imports_for_reload(int sid)
276 {
277     scriptitem_T    *si = SCRIPT_ITEM(sid);
278     int		    idx;
279 
280     for (idx = 0; idx < si->sn_imports.ga_len; ++idx)
281     {
282 	imported_T *imp = ((imported_T *)si->sn_imports.ga_data) + idx;
283 
284 	imp->imp_flags |= IMP_FLAGS_RELOAD;
285     }
286 }
287 
288 /*
289  * ":import Item from 'filename'"
290  * ":import Item as Alias from 'filename'"
291  * ":import {Item} from 'filename'".
292  * ":import {Item as Alias} from 'filename'"
293  * ":import {Item, Item} from 'filename'"
294  * ":import {Item, Item as Alias} from 'filename'"
295  *
296  * ":import * as Name from 'filename'"
297  */
298     void
299 ex_import(exarg_T *eap)
300 {
301     char_u	*cmd_end;
302     evalarg_T	evalarg;
303 
304     if (!getline_equal(eap->getline, eap->cookie, getsourceline))
305     {
306 	emsg(_(e_import_can_only_be_used_in_script));
307 	return;
308     }
309     fill_evalarg_from_eap(&evalarg, eap, eap->skip);
310 
311     cmd_end = handle_import(eap->arg, NULL, current_sctx.sc_sid,
312 							       &evalarg, NULL);
313     if (cmd_end != NULL)
314 	eap->nextcmd = check_nextcmd(cmd_end);
315     clear_evalarg(&evalarg, eap);
316 }
317 
318 /*
319  * Find an exported item in "sid" matching the name at "*argp".
320  * When it is a variable return the index.
321  * When it is a user function return "*ufunc".
322  * When not found returns -1 and "*ufunc" is NULL.
323  */
324     int
325 find_exported(
326 	int	    sid,
327 	char_u	    *name,
328 	ufunc_T	    **ufunc,
329 	type_T	    **type,
330 	cctx_T	    *cctx,
331 	int	    verbose)
332 {
333     int		idx = -1;
334     svar_T	*sv;
335     scriptitem_T *script = SCRIPT_ITEM(sid);
336 
337     // Find name in "script".
338     idx = get_script_item_idx(sid, name, 0, cctx);
339     if (idx >= 0)
340     {
341 	sv = ((svar_T *)script->sn_var_vals.ga_data) + idx;
342 	if (!sv->sv_export)
343 	{
344 	    if (verbose)
345 		semsg(_(e_item_not_exported_in_script_str), name);
346 	    return -1;
347 	}
348 	*type = sv->sv_type;
349 	*ufunc = NULL;
350     }
351     else
352     {
353 	char_u	buffer[200];
354 	char_u	*funcname;
355 
356 	// it could be a user function.
357 	if (STRLEN(name) < sizeof(buffer) - 15)
358 	    funcname = buffer;
359 	else
360 	{
361 	    funcname = alloc(STRLEN(name) + 15);
362 	    if (funcname == NULL)
363 		return -1;
364 	}
365 	funcname[0] = K_SPECIAL;
366 	funcname[1] = KS_EXTRA;
367 	funcname[2] = (int)KE_SNR;
368 	sprintf((char *)funcname + 3, "%ld_%s", (long)sid, name);
369 	*ufunc = find_func(funcname, FALSE, NULL);
370 	if (funcname != buffer)
371 	    vim_free(funcname);
372 
373 	if (*ufunc == NULL)
374 	{
375 	    if (verbose)
376 		semsg(_(e_item_not_found_in_script_str), name);
377 	    return -1;
378 	}
379 	else if (((*ufunc)->uf_flags & FC_EXPORT) == 0)
380 	{
381 	    if (verbose)
382 		semsg(_(e_item_not_exported_in_script_str), name);
383 	    *ufunc = NULL;
384 	    return -1;
385 	}
386     }
387 
388     return idx;
389 }
390 
391 /*
392  * Handle an ":import" command and add the resulting imported_T to "gap", when
393  * not NULL, or script "import_sid" sn_imports.
394  * "cctx" is NULL at the script level.
395  * Returns a pointer to after the command or NULL in case of failure
396  */
397     char_u *
398 handle_import(
399 	char_u	    *arg_start,
400 	garray_T    *gap,
401 	int	    import_sid,
402 	evalarg_T   *evalarg,
403 	void	    *cctx)
404 {
405     char_u	*arg = arg_start;
406     char_u	*cmd_end = NULL;
407     int		ret = FAIL;
408     typval_T	tv;
409     int		sid = -1;
410     int		res;
411     int		mult = FALSE;
412     garray_T	names;
413     garray_T	as_names;
414 
415     tv.v_type = VAR_UNKNOWN;
416     ga_init2(&names, sizeof(char_u *), 10);
417     ga_init2(&as_names, sizeof(char_u *), 10);
418     if (*arg == '{')
419     {
420 	// "import {item, item} from ..."
421 	mult = TRUE;
422 	arg = skipwhite_and_linebreak(arg + 1, evalarg);
423     }
424 
425     for (;;)
426     {
427 	char_u	    *p = arg;
428 	int	    had_comma = FALSE;
429 	char_u	    *as_name = NULL;
430 
431 	// accept "*" or "Name"
432 	if (!mult && arg[0] == '*' && IS_WHITE_OR_NUL(arg[1]))
433 	    ++arg;
434 	else
435 	    while (eval_isnamec(*arg))
436 		++arg;
437 	if (p == arg)
438 	    break;
439 	if (ga_grow(&names, 1) == FAIL || ga_grow(&as_names, 1) == FAIL)
440 	    goto erret;
441 	((char_u **)names.ga_data)[names.ga_len] = vim_strnsave(p, arg - p);
442 	++names.ga_len;
443 
444 	arg = skipwhite_and_linebreak(arg, evalarg);
445 	if (STRNCMP("as", arg, 2) == 0 && IS_WHITE_OR_NUL(arg[2]))
446 	{
447 	    // skip over "as Name "; no line break allowed after "as"
448 	    arg = skipwhite(arg + 2);
449 	    p = arg;
450 	    if (eval_isnamec1(*arg))
451 		while (eval_isnamec(*arg))
452 		    ++arg;
453 	    if (check_defined(p, arg - p, cctx, FALSE) == FAIL)
454 		goto erret;
455 	    as_name = vim_strnsave(p, arg - p);
456 	    arg = skipwhite_and_linebreak(arg, evalarg);
457 	}
458 	else if (*arg_start == '*')
459 	{
460 	    emsg(_(e_missing_as_after_star));
461 	    goto erret;
462 	}
463 	// without "as Name" the as_names entry is NULL
464 	((char_u **)as_names.ga_data)[as_names.ga_len] = as_name;
465 	++as_names.ga_len;
466 
467 	if (!mult)
468 	    break;
469 	if (*arg == ',')
470 	{
471 	    had_comma = TRUE;
472 	    ++arg;
473 	}
474 	arg = skipwhite_and_linebreak(arg, evalarg);
475 	if (*arg == '}')
476 	{
477 	    ++arg;
478 	    break;
479 	}
480 	if (!had_comma)
481 	{
482 	    emsg(_(e_missing_comma_in_import));
483 	    goto erret;
484 	}
485     }
486     arg = skipwhite_and_linebreak(arg, evalarg);
487 
488     if (names.ga_len == 0)
489     {
490 	emsg(_(e_syntax_error_in_import));
491 	goto erret;
492     }
493 
494     if (STRNCMP("from", arg, 4) != 0 || !IS_WHITE_OR_NUL(arg[4]))
495     {
496 	emsg(_(e_missing_from));
497 	goto erret;
498     }
499 
500     // The name of the file can be an expression, which must evaluate to a
501     // string.
502     arg = skipwhite_and_linebreak(arg + 4, evalarg);
503     ret = eval0(arg, &tv, NULL, evalarg);
504     if (ret == FAIL)
505 	goto erret;
506     if (tv.v_type != VAR_STRING
507 		       || tv.vval.v_string == NULL || *tv.vval.v_string == NUL)
508     {
509 	emsg(_(e_invalid_string_after_from));
510 	goto erret;
511     }
512     cmd_end = arg;
513 
514     /*
515      * find script file
516      */
517     if (*tv.vval.v_string == '.')
518     {
519 	size_t		len;
520 	scriptitem_T	*si = SCRIPT_ITEM(current_sctx.sc_sid);
521 	char_u		*tail = gettail(si->sn_name);
522 	char_u		*from_name;
523 
524 	// Relative to current script: "./name.vim", "../../name.vim".
525 	len = STRLEN(si->sn_name) - STRLEN(tail) + STRLEN(tv.vval.v_string) + 2;
526 	from_name = alloc((int)len);
527 	if (from_name == NULL)
528 	    goto erret;
529 	vim_strncpy(from_name, si->sn_name, tail - si->sn_name);
530 	add_pathsep(from_name);
531 	STRCAT(from_name, tv.vval.v_string);
532 	simplify_filename(from_name);
533 
534 	res = do_source(from_name, FALSE, DOSO_NONE, &sid);
535 	vim_free(from_name);
536     }
537     else if (mch_isFullName(tv.vval.v_string))
538     {
539 	// Absolute path: "/tmp/name.vim"
540 	res = do_source(tv.vval.v_string, FALSE, DOSO_NONE, &sid);
541     }
542     else
543     {
544 	size_t	    len = 7 + STRLEN(tv.vval.v_string) + 1;
545 	char_u	    *from_name;
546 
547 	// Find file in "import" subdirs in 'runtimepath'.
548 	from_name = alloc((int)len);
549 	if (from_name == NULL)
550 	{
551 	    goto erret;
552 	}
553 	vim_snprintf((char *)from_name, len, "import/%s", tv.vval.v_string);
554 	res = source_in_path(p_rtp, from_name, DIP_NOAFTER, &sid);
555 	vim_free(from_name);
556     }
557 
558     if (res == FAIL || sid <= 0)
559     {
560 	semsg(_(e_could_not_import_str), tv.vval.v_string);
561 	goto erret;
562     }
563 
564     if (*arg_start == '*')
565     {
566 	imported_T  *imported;
567 	char_u	    *as_name = ((char_u **)as_names.ga_data)[0];
568 
569 	// "import * as That"
570 	imported = find_imported(as_name, STRLEN(as_name), cctx);
571 	if (imported != NULL && imported->imp_sid == sid)
572 	{
573 	    if (imported->imp_flags & IMP_FLAGS_RELOAD)
574 		// import already defined on a previous script load
575 		imported->imp_flags &= ~IMP_FLAGS_RELOAD;
576 	    else
577 	    {
578 		semsg(_(e_name_already_defined_str), as_name);
579 		goto erret;
580 	    }
581 	}
582 
583 	imported = new_imported(gap != NULL ? gap
584 					: &SCRIPT_ITEM(import_sid)->sn_imports);
585 	if (imported == NULL)
586 	    goto erret;
587 	imported->imp_name = as_name;
588 	((char_u **)as_names.ga_data)[0] = NULL;
589 	imported->imp_sid = sid;
590 	imported->imp_flags = IMP_FLAGS_STAR;
591     }
592     else
593     {
594 	int i;
595 
596 	arg = arg_start;
597 	if (*arg == '{')
598 	    arg = skipwhite(arg + 1);
599 	for (i = 0; i < names.ga_len; ++i)
600 	{
601 	    char_u	*name = ((char_u **)names.ga_data)[i];
602 	    char_u	*as_name = ((char_u **)as_names.ga_data)[i];
603 	    size_t	len = STRLEN(name);
604 	    int		idx;
605 	    imported_T	*imported;
606 	    ufunc_T	*ufunc = NULL;
607 	    type_T	*type;
608 
609 	    idx = find_exported(sid, name, &ufunc, &type, cctx, TRUE);
610 
611 	    if (idx < 0 && ufunc == NULL)
612 		goto erret;
613 
614 	    // If already imported with the same properties and the
615 	    // IMP_FLAGS_RELOAD set then we keep that entry.  Otherwise create
616 	    // a new one (and give an error for an existing import).
617 	    imported = find_imported(name, len, cctx);
618 	    if (imported != NULL
619 		    && (imported->imp_flags & IMP_FLAGS_RELOAD)
620 		    && imported->imp_sid == sid
621 		    && (idx >= 0
622 			? (equal_type(imported->imp_type, type)
623 			    && imported->imp_var_vals_idx == idx)
624 			: (equal_type(imported->imp_type, ufunc->uf_func_type)
625 			    && STRCMP(imported->imp_funcname,
626 							ufunc->uf_name) == 0)))
627 	    {
628 		imported->imp_flags &= ~IMP_FLAGS_RELOAD;
629 	    }
630 	    else
631 	    {
632 		if (as_name == NULL
633 			      && check_defined(name, len, cctx, FALSE) == FAIL)
634 		    goto erret;
635 
636 		imported = new_imported(gap != NULL ? gap
637 				       : &SCRIPT_ITEM(import_sid)->sn_imports);
638 		if (imported == NULL)
639 		    goto erret;
640 
641 		if (as_name == NULL)
642 		{
643 		    imported->imp_name = name;
644 		    ((char_u **)names.ga_data)[i] = NULL;
645 		}
646 		else
647 		{
648 		    // "import This as That ..."
649 		    imported->imp_name = as_name;
650 		    ((char_u **)as_names.ga_data)[i] = NULL;
651 		}
652 		imported->imp_sid = sid;
653 		if (idx >= 0)
654 		{
655 		    imported->imp_type = type;
656 		    imported->imp_var_vals_idx = idx;
657 		}
658 		else
659 		{
660 		    imported->imp_type = ufunc->uf_func_type;
661 		    imported->imp_funcname = ufunc->uf_name;
662 		}
663 	    }
664 	}
665     }
666 erret:
667     clear_tv(&tv);
668     ga_clear_strings(&names);
669     ga_clear_strings(&as_names);
670     return cmd_end;
671 }
672 
673 /*
674  * Declare a script-local variable without init: "let var: type".
675  * "const" is an error since the value is missing.
676  * Returns a pointer to after the type.
677  */
678     char_u *
679 vim9_declare_scriptvar(exarg_T *eap, char_u *arg)
680 {
681     char_u	    *p;
682     char_u	    *name;
683     scriptitem_T    *si = SCRIPT_ITEM(current_sctx.sc_sid);
684     type_T	    *type;
685     typval_T	    init_tv;
686 
687     if (eap->cmdidx == CMD_final || eap->cmdidx == CMD_const)
688     {
689 	if (eap->cmdidx == CMD_final)
690 	    emsg(_(e_final_requires_a_value));
691 	else
692 	    emsg(_(e_const_requires_a_value));
693 	return arg + STRLEN(arg);
694     }
695 
696     // Check for valid starting character.
697     if (!eval_isnamec1(*arg))
698     {
699 	semsg(_(e_invarg2), arg);
700 	return arg + STRLEN(arg);
701     }
702 
703     for (p = arg + 1; *p != NUL && eval_isnamec(*p); MB_PTR_ADV(p))
704 	if (*p == ':' && (VIM_ISWHITE(p[1]) || p != arg + 1))
705 	    break;
706 
707     if (*p != ':')
708     {
709 	emsg(_(e_type_or_initialization_required));
710 	return arg + STRLEN(arg);
711     }
712     if (!VIM_ISWHITE(p[1]))
713     {
714 	semsg(_(e_white_space_required_after_str_str), ":", p);
715 	return arg + STRLEN(arg);
716     }
717     name = vim_strnsave(arg, p - arg);
718 
719     // parse type, check for reserved name
720     p = skipwhite(p + 1);
721     type = parse_type(&p, &si->sn_type_list, TRUE);
722     if (type == NULL || check_reserved_name(name) == FAIL)
723     {
724 	vim_free(name);
725 	return p;
726     }
727 
728     // Create the variable with 0/NULL value.
729     CLEAR_FIELD(init_tv);
730     if (type->tt_type == VAR_ANY)
731 	// A variable of type "any" is not possible, just use zero instead
732 	init_tv.v_type = VAR_NUMBER;
733     else
734 	init_tv.v_type = type->tt_type;
735     set_var_const(name, type, &init_tv, FALSE, 0, 0);
736 
737     vim_free(name);
738     return p;
739 }
740 
741 /*
742  * Vim9 part of adding a script variable: add it to sn_all_vars (lookup by name
743  * with a hashtable) and sn_var_vals (lookup by index).
744  * When "create" is TRUE this is a new variable, otherwise find and update an
745  * existing variable.
746  * "flags" can have ASSIGN_FINAL or ASSIGN_CONST.
747  * When "*type" is NULL use "tv" for the type and update "*type".  If
748  * "do_member" is TRUE also use the member type, otherwise use "any".
749  */
750     void
751 update_vim9_script_var(
752 	int	    create,
753 	dictitem_T  *di,
754 	int	    flags,
755 	typval_T    *tv,
756 	type_T	    **type,
757 	int	    do_member)
758 {
759     scriptitem_T    *si = SCRIPT_ITEM(current_sctx.sc_sid);
760     hashitem_T	    *hi;
761     svar_T	    *sv = NULL;
762 
763     if (create)
764     {
765 	sallvar_T   *newsav;
766 	sallvar_T   *sav = NULL;
767 
768 	// Store a pointer to the typval_T, so that it can be found by index
769 	// instead of using a hastab lookup.
770 	if (ga_grow(&si->sn_var_vals, 1) == FAIL)
771 	    return;
772 
773 	hi = hash_find(&si->sn_all_vars.dv_hashtab, di->di_key);
774 	if (!HASHITEM_EMPTY(hi))
775 	{
776 	    // Variable with this name exists, either in this block or in
777 	    // another block.
778 	    for (sav = HI2SAV(hi); ; sav = sav->sav_next)
779 	    {
780 		if (sav->sav_block_id == si->sn_current_block_id)
781 		{
782 		    // variable defined in a loop, re-use the entry
783 		    sv = ((svar_T *)si->sn_var_vals.ga_data)
784 						       + sav->sav_var_vals_idx;
785 		    // unhide the variable
786 		    if (sv->sv_tv == &sav->sav_tv)
787 		    {
788 			clear_tv(&sav->sav_tv);
789 			sv->sv_tv = &di->di_tv;
790 			sav->sav_di = di;
791 		    }
792 		    break;
793 		}
794 		if (sav->sav_next == NULL)
795 		    break;
796 	    }
797 	}
798 
799 	if (sv == NULL)
800 	{
801 	    // Variable not defined or not defined in current block: Add a
802 	    // svar_T and create a new sallvar_T.
803 	    sv = ((svar_T *)si->sn_var_vals.ga_data) + si->sn_var_vals.ga_len;
804 	    newsav = (sallvar_T *)alloc_clear(
805 				       sizeof(sallvar_T) + STRLEN(di->di_key));
806 	    if (newsav == NULL)
807 		return;
808 
809 	    sv->sv_tv = &di->di_tv;
810 	    sv->sv_const = (flags & ASSIGN_FINAL) ? ASSIGN_FINAL
811 				   : (flags & ASSIGN_CONST) ? ASSIGN_CONST : 0;
812 	    sv->sv_export = is_export;
813 	    newsav->sav_var_vals_idx = si->sn_var_vals.ga_len;
814 	    ++si->sn_var_vals.ga_len;
815 	    STRCPY(&newsav->sav_key, di->di_key);
816 	    sv->sv_name = newsav->sav_key;
817 	    newsav->sav_di = di;
818 	    newsav->sav_block_id = si->sn_current_block_id;
819 
820 	    if (HASHITEM_EMPTY(hi))
821 		// new variable name
822 		hash_add(&si->sn_all_vars.dv_hashtab, newsav->sav_key);
823 	    else if (sav != NULL)
824 		// existing name in a new block, append to the list
825 		sav->sav_next = newsav;
826 	}
827     }
828     else
829     {
830 	sv = find_typval_in_script(&di->di_tv);
831     }
832     if (sv != NULL)
833     {
834 	if (*type == NULL)
835 	    *type = typval2type(tv, get_copyID(), &si->sn_type_list, do_member);
836 	sv->sv_type = *type;
837     }
838 
839     // let ex_export() know the export worked.
840     is_export = FALSE;
841 }
842 
843 /*
844  * Hide a script variable when leaving a block.
845  * "idx" is de index in sn_var_vals.
846  * When "func_defined" is non-zero then a function was defined in this block,
847  * the variable may be accessed by it.  Otherwise the variable can be cleared.
848  */
849     void
850 hide_script_var(scriptitem_T *si, int idx, int func_defined)
851 {
852     svar_T	*sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
853     hashtab_T	*script_ht = get_script_local_ht();
854     hashtab_T	*all_ht = &si->sn_all_vars.dv_hashtab;
855     hashitem_T	*script_hi;
856     hashitem_T	*all_hi;
857 
858     // Remove a variable declared inside the block, if it still exists.
859     // If it was added in a nested block it will already have been removed.
860     // The typval is moved into the sallvar_T.
861     script_hi = hash_find(script_ht, sv->sv_name);
862     all_hi = hash_find(all_ht, sv->sv_name);
863     if (!HASHITEM_EMPTY(script_hi) && !HASHITEM_EMPTY(all_hi))
864     {
865 	dictitem_T	*di = HI2DI(script_hi);
866 	sallvar_T	*sav = HI2SAV(all_hi);
867 	sallvar_T	*sav_prev = NULL;
868 
869 	// There can be multiple entries with the same name in different
870 	// blocks, find the right one.
871 	while (sav != NULL && sav->sav_var_vals_idx != idx)
872 	{
873 	    sav_prev = sav;
874 	    sav = sav->sav_next;
875 	}
876 	if (sav != NULL)
877 	{
878 	    if (func_defined)
879 	    {
880 		// move the typval from the dictitem to the sallvar
881 		sav->sav_tv = di->di_tv;
882 		di->di_tv.v_type = VAR_UNKNOWN;
883 		sav->sav_flags = di->di_flags;
884 		sav->sav_di = NULL;
885 		sv->sv_tv = &sav->sav_tv;
886 	    }
887 	    else
888 	    {
889 		if (sav_prev == NULL)
890 		    hash_remove(all_ht, all_hi);
891 		else
892 		    sav_prev->sav_next = sav->sav_next;
893 		sv->sv_name = NULL;
894 		vim_free(sav);
895 	    }
896 	    delete_var(script_ht, script_hi);
897 	}
898     }
899 }
900 
901 /*
902  * Free the script variables from "sn_all_vars".
903  */
904     void
905 free_all_script_vars(scriptitem_T *si)
906 {
907     int		todo;
908     hashtab_T	*ht = &si->sn_all_vars.dv_hashtab;
909     hashitem_T	*hi;
910     sallvar_T	*sav;
911     sallvar_T	*sav_next;
912 
913     hash_lock(ht);
914     todo = (int)ht->ht_used;
915     for (hi = ht->ht_array; todo > 0; ++hi)
916     {
917 	if (!HASHITEM_EMPTY(hi))
918 	{
919 	    --todo;
920 
921 	    // Free the variable.  Don't remove it from the hashtab, ht_array
922 	    // might change then.  hash_clear() takes care of it later.
923 	    sav = HI2SAV(hi);
924 	    while (sav != NULL)
925 	    {
926 		sav_next = sav->sav_next;
927 		if (sav->sav_di == NULL)
928 		    clear_tv(&sav->sav_tv);
929 		vim_free(sav);
930 		sav = sav_next;
931 	    }
932 	}
933     }
934     hash_clear(ht);
935     hash_init(ht);
936 
937     ga_clear(&si->sn_var_vals);
938 
939     // existing commands using script variable indexes are no longer valid
940     si->sn_script_seq = current_sctx.sc_seq;
941 }
942 
943 /*
944  * Find the script-local variable that links to "dest".
945  * Returns NULL if not found and give an internal error.
946  */
947     svar_T *
948 find_typval_in_script(typval_T *dest)
949 {
950     scriptitem_T    *si = SCRIPT_ITEM(current_sctx.sc_sid);
951     int		    idx;
952 
953     if (si->sn_version != SCRIPT_VERSION_VIM9)
954 	// legacy script doesn't store variable types
955 	return NULL;
956 
957     // Find the svar_T in sn_var_vals.
958     for (idx = 0; idx < si->sn_var_vals.ga_len; ++idx)
959     {
960 	svar_T    *sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
961 
962 	// If "sv_name" is NULL the variable was hidden when leaving a block,
963 	// don't check "sv_tv" then, it might be used for another variable now.
964 	if (sv->sv_name != NULL && sv->sv_tv == dest)
965 	    return sv;
966     }
967     iemsg("find_typval_in_script(): not found");
968     return NULL;
969 }
970 
971 /*
972  * Check if the type of script variable "dest" allows assigning "value".
973  * If needed convert "value" to a bool.
974  */
975     int
976 check_script_var_type(
977 	typval_T    *dest,
978 	typval_T    *value,
979 	char_u	    *name,
980 	where_T	    where)
981 {
982     svar_T  *sv = find_typval_in_script(dest);
983     int	    ret;
984 
985     if (sv != NULL)
986     {
987 	if (sv->sv_const != 0)
988 	{
989 	    semsg(_(e_cannot_change_readonly_variable_str), name);
990 	    return FAIL;
991 	}
992 	ret = check_typval_type(sv->sv_type, value, where);
993 	if (ret == OK && need_convert_to_bool(sv->sv_type, value))
994 	{
995 	    int	val = tv2bool(value);
996 
997 	    clear_tv(value);
998 	    value->v_type = VAR_BOOL;
999 	    value->v_lock = 0;
1000 	    value->vval.v_number = val ? VVAL_TRUE : VVAL_FALSE;
1001 	}
1002 	return ret;
1003     }
1004 
1005     return OK; // not really
1006 }
1007 
1008 // words that cannot be used as a variable
1009 static char *reserved[] = {
1010     "true",
1011     "false",
1012     "null",
1013     "this",
1014     NULL
1015 };
1016 
1017     int
1018 check_reserved_name(char_u *name)
1019 {
1020     int idx;
1021 
1022     for (idx = 0; reserved[idx] != NULL; ++idx)
1023 	if (STRCMP(reserved[idx], name) == 0)
1024 	{
1025 	    semsg(_(e_cannot_use_reserved_name), name);
1026 	    return FAIL;
1027 	}
1028     return OK;
1029 }
1030 
1031 #endif // FEAT_EVAL
1032