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