xref: /vim-8.2.3635/src/ex_eval.c (revision abcbb0e9)
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  * ex_eval.c: functions for Ex command line for the +eval feature.
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_EVAL) || defined(PROTO)
17 
18 static char	*get_end_emsg(cstack_T *cstack);
19 
20 /*
21  * Exception handling terms:
22  *
23  *	:try		":try" command		\
24  *	    ...		try block		|
25  *	:catch RE	":catch" command	|
26  *	    ...		catch clause		|- try conditional
27  *	:finally	":finally" command	|
28  *	    ...		finally clause		|
29  *	:endtry		":endtry" command	/
30  *
31  * The try conditional may have any number of catch clauses and at most one
32  * finally clause.  A ":throw" command can be inside the try block, a catch
33  * clause, the finally clause, or in a function called or script sourced from
34  * there or even outside the try conditional.  Try conditionals may be nested.
35  */
36 
37 /*
38  * Configuration whether an exception is thrown on error or interrupt.  When
39  * the preprocessor macros below evaluate to FALSE, an error (did_emsg) or
40  * interrupt (got_int) under an active try conditional terminates the script
41  * after the non-active finally clauses of all active try conditionals have been
42  * executed.  Otherwise, errors and/or interrupts are converted into catchable
43  * exceptions (did_throw additionally set), which terminate the script only if
44  * not caught.  For user exceptions, only did_throw is set.  (Note: got_int can
45  * be set asynchronously afterwards by a SIGINT, so did_throw && got_int is not
46  * a reliant test that the exception currently being thrown is an interrupt
47  * exception.  Similarly, did_emsg can be set afterwards on an error in an
48  * (unskipped) conditional command inside an inactive conditional, so did_throw
49  * && did_emsg is not a reliant test that the exception currently being thrown
50  * is an error exception.)  -  The macros can be defined as expressions checking
51  * for a variable that is allowed to be changed during execution of a script.
52  */
53 #if 0
54 // Expressions used for testing during the development phase.
55 # define THROW_ON_ERROR		(!eval_to_number("$VIMNOERRTHROW"))
56 # define THROW_ON_INTERRUPT	(!eval_to_number("$VIMNOINTTHROW"))
57 # define THROW_TEST
58 #else
59 // Values used for the Vim release.
60 # define THROW_ON_ERROR		TRUE
61 # define THROW_ON_ERROR_TRUE
62 # define THROW_ON_INTERRUPT	TRUE
63 # define THROW_ON_INTERRUPT_TRUE
64 #endif
65 
66 /*
67  * When several errors appear in a row, setting "force_abort" is delayed until
68  * the failing command returned.  "cause_abort" is set to TRUE meanwhile, in
69  * order to indicate that situation.  This is useful when "force_abort" was set
70  * during execution of a function call from an expression: the aborting of the
71  * expression evaluation is done without producing any error messages, but all
72  * error messages on parsing errors during the expression evaluation are given
73  * (even if a try conditional is active).
74  */
75 static int cause_abort = FALSE;
76 
77 /*
78  * Return TRUE when immediately aborting on error, or when an interrupt
79  * occurred or an exception was thrown but not caught.  Use for ":{range}call"
80  * to check whether an aborted function that does not handle a range itself
81  * should be called again for the next line in the range.  Also used for
82  * cancelling expression evaluation after a function call caused an immediate
83  * abort.  Note that the first emsg() call temporarily resets "force_abort"
84  * until the throw point for error messages has been reached.  That is, during
85  * cancellation of an expression evaluation after an aborting function call or
86  * due to a parsing error, aborting() always returns the same value.
87  * "got_int" is also set by calling interrupt().
88  */
89     int
90 aborting(void)
91 {
92     return (did_emsg && force_abort) || got_int || did_throw;
93 }
94 
95 /*
96  * The value of "force_abort" is temporarily reset by the first emsg() call
97  * during an expression evaluation, and "cause_abort" is used instead.  It might
98  * be necessary to restore "force_abort" even before the throw point for the
99  * error message has been reached.  update_force_abort() should be called then.
100  */
101     void
102 update_force_abort(void)
103 {
104     if (cause_abort)
105 	force_abort = TRUE;
106 }
107 
108 /*
109  * Return TRUE if a command with a subcommand resulting in "retcode" should
110  * abort the script processing.  Can be used to suppress an autocommand after
111  * execution of a failing subcommand as long as the error message has not been
112  * displayed and actually caused the abortion.
113  */
114     int
115 should_abort(int retcode)
116 {
117     return ((retcode == FAIL && trylevel != 0 && !emsg_silent) || aborting());
118 }
119 
120 /*
121  * Return TRUE if a function with the "abort" flag should not be considered
122  * ended on an error.  This means that parsing commands is continued in order
123  * to find finally clauses to be executed, and that some errors in skipped
124  * commands are still reported.
125  */
126     int
127 aborted_in_try(void)
128 {
129     // This function is only called after an error.  In this case, "force_abort"
130     // determines whether searching for finally clauses is necessary.
131     return force_abort;
132 }
133 
134 /*
135  * cause_errthrow(): Cause a throw of an error exception if appropriate.
136  * Return TRUE if the error message should not be displayed by emsg().
137  * Sets "ignore", if the emsg() call should be ignored completely.
138  *
139  * When several messages appear in the same command, the first is usually the
140  * most specific one and used as the exception value.  The "severe" flag can be
141  * set to TRUE, if a later but severer message should be used instead.
142  */
143     int
144 cause_errthrow(
145     char_u	*mesg,
146     int		severe,
147     int		*ignore)
148 {
149     msglist_T	*elem;
150     msglist_T	**plist;
151 
152     /*
153      * Do nothing when displaying the interrupt message or reporting an
154      * uncaught exception (which has already been discarded then) at the top
155      * level.  Also when no exception can be thrown.  The message will be
156      * displayed by emsg().
157      */
158     if (suppress_errthrow)
159 	return FALSE;
160 
161     /*
162      * If emsg() has not been called previously, temporarily reset
163      * "force_abort" until the throw point for error messages has been
164      * reached.  This ensures that aborting() returns the same value for all
165      * errors that appear in the same command.  This means particularly that
166      * for parsing errors during expression evaluation emsg() will be called
167      * multiply, even when the expression is evaluated from a finally clause
168      * that was activated due to an aborting error, interrupt, or exception.
169      */
170     if (!did_emsg)
171     {
172 	cause_abort = force_abort;
173 	force_abort = FALSE;
174     }
175 
176     /*
177      * If no try conditional is active and no exception is being thrown and
178      * there has not been an error in a try conditional or a throw so far, do
179      * nothing (for compatibility of non-EH scripts).  The message will then
180      * be displayed by emsg().  When ":silent!" was used and we are not
181      * currently throwing an exception, do nothing.  The message text will
182      * then be stored to v:errmsg by emsg() without displaying it.
183      */
184     if (((trylevel == 0 && !cause_abort) || emsg_silent) && !did_throw)
185 	return FALSE;
186 
187     /*
188      * Ignore an interrupt message when inside a try conditional or when an
189      * exception is being thrown or when an error in a try conditional or
190      * throw has been detected previously.  This is important in order that an
191      * interrupt exception is catchable by the innermost try conditional and
192      * not replaced by an interrupt message error exception.
193      */
194     if (mesg == (char_u *)_(e_interr))
195     {
196 	*ignore = TRUE;
197 	return TRUE;
198     }
199 
200     /*
201      * Ensure that all commands in nested function calls and sourced files
202      * are aborted immediately.
203      */
204     cause_abort = TRUE;
205 
206     /*
207      * When an exception is being thrown, some commands (like conditionals) are
208      * not skipped.  Errors in those commands may affect what of the subsequent
209      * commands are regarded part of catch and finally clauses.  Catching the
210      * exception would then cause execution of commands not intended by the
211      * user, who wouldn't even get aware of the problem.  Therefor, discard the
212      * exception currently being thrown to prevent it from being caught.  Just
213      * execute finally clauses and terminate.
214      */
215     if (did_throw)
216     {
217 	// When discarding an interrupt exception, reset got_int to prevent the
218 	// same interrupt being converted to an exception again and discarding
219 	// the error exception we are about to throw here.
220 	if (current_exception->type == ET_INTERRUPT)
221 	    got_int = FALSE;
222 	discard_current_exception();
223     }
224 
225 #ifdef THROW_TEST
226     if (!THROW_ON_ERROR)
227     {
228 	/*
229 	 * Print error message immediately without searching for a matching
230 	 * catch clause; just finally clauses are executed before the script
231 	 * is terminated.
232 	 */
233 	return FALSE;
234     }
235     else
236 #endif
237     {
238 	/*
239 	 * Prepare the throw of an error exception, so that everything will
240 	 * be aborted (except for executing finally clauses), until the error
241 	 * exception is caught; if still uncaught at the top level, the error
242 	 * message will be displayed and the script processing terminated
243 	 * then.  -  This function has no access to the conditional stack.
244 	 * Thus, the actual throw is made after the failing command has
245 	 * returned.  -  Throw only the first of several errors in a row, except
246 	 * a severe error is following.
247 	 */
248 	if (msg_list != NULL)
249 	{
250 	    plist = msg_list;
251 	    while (*plist != NULL)
252 		plist = &(*plist)->next;
253 
254 	    elem = ALLOC_CLEAR_ONE(msglist_T);
255 	    if (elem == NULL)
256 	    {
257 		suppress_errthrow = TRUE;
258 		emsg(_(e_outofmem));
259 	    }
260 	    else
261 	    {
262 		elem->msg = (char *)vim_strsave(mesg);
263 		if (elem->msg == NULL)
264 		{
265 		    vim_free(elem);
266 		    suppress_errthrow = TRUE;
267 		    emsg(_(e_outofmem));
268 		}
269 		else
270 		{
271 		    elem->next = NULL;
272 		    elem->throw_msg = NULL;
273 		    *plist = elem;
274 		    if (plist == msg_list || severe)
275 		    {
276 			char	    *tmsg;
277 
278 			// Skip the extra "Vim " prefix for message "E458".
279 			tmsg = elem->msg;
280 			if (STRNCMP(tmsg, "Vim E", 5) == 0
281 				&& VIM_ISDIGIT(tmsg[5])
282 				&& VIM_ISDIGIT(tmsg[6])
283 				&& VIM_ISDIGIT(tmsg[7])
284 				&& tmsg[8] == ':'
285 				&& tmsg[9] == ' ')
286 			    (*msg_list)->throw_msg = &tmsg[4];
287 			else
288 			    (*msg_list)->throw_msg = tmsg;
289 		    }
290 
291 		    // Get the source name and lnum now, it may change before
292 		    // reaching do_errthrow().
293 		    elem->sfile = estack_sfile(ESTACK_NONE);
294 		    elem->slnum = SOURCING_LNUM;
295 		}
296 	    }
297 	}
298 	return TRUE;
299     }
300 }
301 
302 /*
303  * Free a "msg_list" and the messages it contains.
304  */
305     static void
306 free_msglist(msglist_T *l)
307 {
308     msglist_T  *messages, *next;
309 
310     messages = l;
311     while (messages != NULL)
312     {
313 	next = messages->next;
314 	vim_free(messages->msg);
315 	vim_free(messages->sfile);
316 	vim_free(messages);
317 	messages = next;
318     }
319 }
320 
321 /*
322  * Free global "*msg_list" and the messages it contains, then set "*msg_list"
323  * to NULL.
324  */
325     void
326 free_global_msglist(void)
327 {
328     free_msglist(*msg_list);
329     *msg_list = NULL;
330 }
331 
332 /*
333  * Throw the message specified in the call to cause_errthrow() above as an
334  * error exception.  If cstack is NULL, postpone the throw until do_cmdline()
335  * has returned (see do_one_cmd()).
336  */
337     void
338 do_errthrow(cstack_T *cstack, char_u *cmdname)
339 {
340     /*
341      * Ensure that all commands in nested function calls and sourced files
342      * are aborted immediately.
343      */
344     if (cause_abort)
345     {
346 	cause_abort = FALSE;
347 	force_abort = TRUE;
348     }
349 
350     // If no exception is to be thrown or the conversion should be done after
351     // returning to a previous invocation of do_one_cmd(), do nothing.
352     if (msg_list == NULL || *msg_list == NULL)
353 	return;
354 
355     if (throw_exception(*msg_list, ET_ERROR, cmdname) == FAIL)
356 	free_msglist(*msg_list);
357     else
358     {
359 	if (cstack != NULL)
360 	    do_throw(cstack);
361 	else
362 	    need_rethrow = TRUE;
363     }
364     *msg_list = NULL;
365 }
366 
367 /*
368  * do_intthrow(): Replace the current exception by an interrupt or interrupt
369  * exception if appropriate.  Return TRUE if the current exception is discarded,
370  * FALSE otherwise.
371  */
372     int
373 do_intthrow(cstack_T *cstack)
374 {
375     /*
376      * If no interrupt occurred or no try conditional is active and no exception
377      * is being thrown, do nothing (for compatibility of non-EH scripts).
378      */
379     if (!got_int || (trylevel == 0 && !did_throw))
380 	return FALSE;
381 
382 #ifdef THROW_TEST	// avoid warning for condition always true
383     if (!THROW_ON_INTERRUPT)
384     {
385 	/*
386 	 * The interrupt aborts everything except for executing finally clauses.
387 	 * Discard any user or error or interrupt exception currently being
388 	 * thrown.
389 	 */
390 	if (did_throw)
391 	    discard_current_exception();
392     }
393     else
394 #endif
395     {
396 	/*
397 	 * Throw an interrupt exception, so that everything will be aborted
398 	 * (except for executing finally clauses), until the interrupt exception
399 	 * is caught; if still uncaught at the top level, the script processing
400 	 * will be terminated then.  -  If an interrupt exception is already
401 	 * being thrown, do nothing.
402 	 *
403 	 */
404 	if (did_throw)
405 	{
406 	    if (current_exception->type == ET_INTERRUPT)
407 		return FALSE;
408 
409 	    // An interrupt exception replaces any user or error exception.
410 	    discard_current_exception();
411 	}
412 	if (throw_exception("Vim:Interrupt", ET_INTERRUPT, NULL) != FAIL)
413 	    do_throw(cstack);
414     }
415 
416     return TRUE;
417 }
418 
419 /*
420  * Get an exception message that is to be stored in current_exception->value.
421  */
422     char *
423 get_exception_string(
424     void	*value,
425     except_type_T type,
426     char_u	*cmdname,
427     int		*should_free)
428 {
429     char	*ret;
430     char	*mesg;
431     int		cmdlen;
432     char	*p, *val;
433 
434     if (type == ET_ERROR)
435     {
436 	*should_free = TRUE;
437 	mesg = ((msglist_T *)value)->throw_msg;
438 	if (cmdname != NULL && *cmdname != NUL)
439 	{
440 	    cmdlen = (int)STRLEN(cmdname);
441 	    ret = (char *)vim_strnsave((char_u *)"Vim(",
442 						4 + cmdlen + 2 + STRLEN(mesg));
443 	    if (ret == NULL)
444 		return ret;
445 	    STRCPY(&ret[4], cmdname);
446 	    STRCPY(&ret[4 + cmdlen], "):");
447 	    val = ret + 4 + cmdlen + 2;
448 	}
449 	else
450 	{
451 	    ret = (char *)vim_strnsave((char_u *)"Vim:", 4 + STRLEN(mesg));
452 	    if (ret == NULL)
453 		return ret;
454 	    val = ret + 4;
455 	}
456 
457 	// msg_add_fname may have been used to prefix the message with a file
458 	// name in quotes.  In the exception value, put the file name in
459 	// parentheses and move it to the end.
460 	for (p = mesg; ; p++)
461 	{
462 	    if (*p == NUL
463 		    || (*p == 'E'
464 			&& VIM_ISDIGIT(p[1])
465 			&& (p[2] == ':'
466 			    || (VIM_ISDIGIT(p[2])
467 				&& (p[3] == ':'
468 				    || (VIM_ISDIGIT(p[3])
469 					&& p[4] == ':'))))))
470 	    {
471 		if (*p == NUL || p == mesg)
472 		    STRCAT(val, mesg);  // 'E123' missing or at beginning
473 		else
474 		{
475 		    // '"filename" E123: message text'
476 		    if (mesg[0] != '"' || p-2 < &mesg[1] ||
477 			    p[-2] != '"' || p[-1] != ' ')
478 			// "E123:" is part of the file name.
479 			continue;
480 
481 		    STRCAT(val, p);
482 		    p[-2] = NUL;
483 		    sprintf((char *)(val + STRLEN(p)), " (%s)", &mesg[1]);
484 		    p[-2] = '"';
485 		}
486 		break;
487 	    }
488 	}
489     }
490     else
491     {
492 	*should_free = FALSE;
493 	ret = value;
494     }
495 
496     return ret;
497 }
498 
499 
500 /*
501  * Throw a new exception.  Return FAIL when out of memory or it was tried to
502  * throw an illegal user exception.  "value" is the exception string for a
503  * user or interrupt exception, or points to a message list in case of an
504  * error exception.
505  */
506     int
507 throw_exception(void *value, except_type_T type, char_u *cmdname)
508 {
509     except_T	*excp;
510     int		should_free;
511 
512     /*
513      * Disallow faking Interrupt or error exceptions as user exceptions.  They
514      * would be treated differently from real interrupt or error exceptions
515      * when no active try block is found, see do_cmdline().
516      */
517     if (type == ET_USER)
518     {
519 	if (STRNCMP((char_u *)value, "Vim", 3) == 0
520 		&& (((char_u *)value)[3] == NUL || ((char_u *)value)[3] == ':'
521 		    || ((char_u *)value)[3] == '('))
522 	{
523 	    emsg(_("E608: Cannot :throw exceptions with 'Vim' prefix"));
524 	    goto fail;
525 	}
526     }
527 
528     excp = ALLOC_ONE(except_T);
529     if (excp == NULL)
530 	goto nomem;
531 
532     if (type == ET_ERROR)
533 	// Store the original message and prefix the exception value with
534 	// "Vim:" or, if a command name is given, "Vim(cmdname):".
535 	excp->messages = (msglist_T *)value;
536 
537     excp->value = get_exception_string(value, type, cmdname, &should_free);
538     if (excp->value == NULL && should_free)
539 	goto nomem;
540 
541     excp->type = type;
542     if (type == ET_ERROR && ((msglist_T *)value)->sfile != NULL)
543     {
544 	msglist_T *entry = (msglist_T *)value;
545 
546 	excp->throw_name = entry->sfile;
547 	entry->sfile = NULL;
548 	excp->throw_lnum = entry->slnum;
549     }
550     else
551     {
552 	excp->throw_name = estack_sfile(ESTACK_NONE);
553 	if (excp->throw_name == NULL)
554 	    excp->throw_name = vim_strsave((char_u *)"");
555 	if (excp->throw_name == NULL)
556 	{
557 	    if (should_free)
558 		vim_free(excp->value);
559 	    goto nomem;
560 	}
561 	excp->throw_lnum = SOURCING_LNUM;
562     }
563 
564     if (p_verbose >= 13 || debug_break_level > 0)
565     {
566 	int	save_msg_silent = msg_silent;
567 
568 	if (debug_break_level > 0)
569 	    msg_silent = FALSE;		// display messages
570 	else
571 	    verbose_enter();
572 	++no_wait_return;
573 	if (debug_break_level > 0 || *p_vfile == NUL)
574 	    msg_scroll = TRUE;	    // always scroll up, don't overwrite
575 
576 	smsg(_("Exception thrown: %s"), excp->value);
577 	msg_puts("\n");   // don't overwrite this either
578 
579 	if (debug_break_level > 0 || *p_vfile == NUL)
580 	    cmdline_row = msg_row;
581 	--no_wait_return;
582 	if (debug_break_level > 0)
583 	    msg_silent = save_msg_silent;
584 	else
585 	    verbose_leave();
586     }
587 
588     current_exception = excp;
589     return OK;
590 
591 nomem:
592     vim_free(excp);
593     suppress_errthrow = TRUE;
594     emsg(_(e_outofmem));
595 fail:
596     current_exception = NULL;
597     return FAIL;
598 }
599 
600 /*
601  * Discard an exception.  "was_finished" is set when the exception has been
602  * caught and the catch clause has been ended normally.
603  */
604     static void
605 discard_exception(except_T *excp, int was_finished)
606 {
607     char_u		*saved_IObuff;
608 
609     if (current_exception == excp)
610 	current_exception = NULL;
611     if (excp == NULL)
612     {
613 	internal_error("discard_exception()");
614 	return;
615     }
616 
617     if (p_verbose >= 13 || debug_break_level > 0)
618     {
619 	int	save_msg_silent = msg_silent;
620 
621 	saved_IObuff = vim_strsave(IObuff);
622 	if (debug_break_level > 0)
623 	    msg_silent = FALSE;		// display messages
624 	else
625 	    verbose_enter();
626 	++no_wait_return;
627 	if (debug_break_level > 0 || *p_vfile == NUL)
628 	    msg_scroll = TRUE;	    // always scroll up, don't overwrite
629 	smsg(was_finished
630 		    ? _("Exception finished: %s")
631 		    : _("Exception discarded: %s"),
632 		excp->value);
633 	msg_puts("\n");   // don't overwrite this either
634 	if (debug_break_level > 0 || *p_vfile == NUL)
635 	    cmdline_row = msg_row;
636 	--no_wait_return;
637 	if (debug_break_level > 0)
638 	    msg_silent = save_msg_silent;
639 	else
640 	    verbose_leave();
641 	STRCPY(IObuff, saved_IObuff);
642 	vim_free(saved_IObuff);
643     }
644     if (excp->type != ET_INTERRUPT)
645 	vim_free(excp->value);
646     if (excp->type == ET_ERROR)
647 	free_msglist(excp->messages);
648     vim_free(excp->throw_name);
649     vim_free(excp);
650 }
651 
652 /*
653  * Discard the exception currently being thrown.
654  */
655     void
656 discard_current_exception(void)
657 {
658     if (current_exception != NULL)
659 	discard_exception(current_exception, FALSE);
660     did_throw = FALSE;
661     need_rethrow = FALSE;
662 }
663 
664 /*
665  * Put an exception on the caught stack.
666  */
667     void
668 catch_exception(except_T *excp)
669 {
670     excp->caught = caught_stack;
671     caught_stack = excp;
672     set_vim_var_string(VV_EXCEPTION, (char_u *)excp->value, -1);
673     if (*excp->throw_name != NUL)
674     {
675 	if (excp->throw_lnum != 0)
676 	    vim_snprintf((char *)IObuff, IOSIZE, _("%s, line %ld"),
677 				    excp->throw_name, (long)excp->throw_lnum);
678 	else
679 	    vim_snprintf((char *)IObuff, IOSIZE, "%s", excp->throw_name);
680 	set_vim_var_string(VV_THROWPOINT, IObuff, -1);
681     }
682     else
683 	// throw_name not set on an exception from a command that was typed.
684 	set_vim_var_string(VV_THROWPOINT, NULL, -1);
685 
686     if (p_verbose >= 13 || debug_break_level > 0)
687     {
688 	int	save_msg_silent = msg_silent;
689 
690 	if (debug_break_level > 0)
691 	    msg_silent = FALSE;		// display messages
692 	else
693 	    verbose_enter();
694 	++no_wait_return;
695 	if (debug_break_level > 0 || *p_vfile == NUL)
696 	    msg_scroll = TRUE;	    // always scroll up, don't overwrite
697 
698 	smsg(_("Exception caught: %s"), excp->value);
699 	msg_puts("\n");   // don't overwrite this either
700 
701 	if (debug_break_level > 0 || *p_vfile == NUL)
702 	    cmdline_row = msg_row;
703 	--no_wait_return;
704 	if (debug_break_level > 0)
705 	    msg_silent = save_msg_silent;
706 	else
707 	    verbose_leave();
708     }
709 }
710 
711 /*
712  * Remove an exception from the caught stack.
713  */
714     static void
715 finish_exception(except_T *excp)
716 {
717     if (excp != caught_stack)
718 	internal_error("finish_exception()");
719     caught_stack = caught_stack->caught;
720     if (caught_stack != NULL)
721     {
722 	set_vim_var_string(VV_EXCEPTION, (char_u *)caught_stack->value, -1);
723 	if (*caught_stack->throw_name != NUL)
724 	{
725 	    if (caught_stack->throw_lnum != 0)
726 		vim_snprintf((char *)IObuff, IOSIZE,
727 			_("%s, line %ld"), caught_stack->throw_name,
728 			(long)caught_stack->throw_lnum);
729 	    else
730 		vim_snprintf((char *)IObuff, IOSIZE, "%s",
731 						    caught_stack->throw_name);
732 	    set_vim_var_string(VV_THROWPOINT, IObuff, -1);
733 	}
734 	else
735 	    // throw_name not set on an exception from a command that was
736 	    // typed.
737 	    set_vim_var_string(VV_THROWPOINT, NULL, -1);
738     }
739     else
740     {
741 	set_vim_var_string(VV_EXCEPTION, NULL, -1);
742 	set_vim_var_string(VV_THROWPOINT, NULL, -1);
743     }
744 
745     // Discard the exception, but use the finish message for 'verbose'.
746     discard_exception(excp, TRUE);
747 }
748 
749 /*
750  * Flags specifying the message displayed by report_pending.
751  */
752 #define RP_MAKE		0
753 #define RP_RESUME	1
754 #define RP_DISCARD	2
755 
756 /*
757  * Report information about something pending in a finally clause if required by
758  * the 'verbose' option or when debugging.  "action" tells whether something is
759  * made pending or something pending is resumed or discarded.  "pending" tells
760  * what is pending.  "value" specifies the return value for a pending ":return"
761  * or the exception value for a pending exception.
762  */
763     static void
764 report_pending(int action, int pending, void *value)
765 {
766     char	*mesg;
767     char	*s;
768     int		save_msg_silent;
769 
770 
771     switch (action)
772     {
773 	case RP_MAKE:
774 	    mesg = _("%s made pending");
775 	    break;
776 	case RP_RESUME:
777 	    mesg = _("%s resumed");
778 	    break;
779 	// case RP_DISCARD:
780 	default:
781 	    mesg = _("%s discarded");
782 	    break;
783     }
784 
785     switch (pending)
786     {
787 	case CSTP_NONE:
788 	    return;
789 
790 	case CSTP_CONTINUE:
791 	    s = ":continue";
792 	    break;
793 	case CSTP_BREAK:
794 	    s = ":break";
795 	    break;
796 	case CSTP_FINISH:
797 	    s = ":finish";
798 	    break;
799 	case CSTP_RETURN:
800 	    // ":return" command producing value, allocated
801 	    s = (char *)get_return_cmd(value);
802 	    break;
803 
804 	default:
805 	    if (pending & CSTP_THROW)
806 	    {
807 		vim_snprintf((char *)IObuff, IOSIZE, mesg, _("Exception"));
808 		mesg = (char *)vim_strnsave(IObuff, STRLEN(IObuff) + 4);
809 		STRCAT(mesg, ": %s");
810 		s = (char *)((except_T *)value)->value;
811 	    }
812 	    else if ((pending & CSTP_ERROR) && (pending & CSTP_INTERRUPT))
813 		s = _("Error and interrupt");
814 	    else if (pending & CSTP_ERROR)
815 		s = _("Error");
816 	    else // if (pending & CSTP_INTERRUPT)
817 		s = _("Interrupt");
818     }
819 
820     save_msg_silent = msg_silent;
821     if (debug_break_level > 0)
822 	msg_silent = FALSE;	// display messages
823     ++no_wait_return;
824     msg_scroll = TRUE;		// always scroll up, don't overwrite
825     smsg(mesg, s);
826     msg_puts("\n");   // don't overwrite this either
827     cmdline_row = msg_row;
828     --no_wait_return;
829     if (debug_break_level > 0)
830 	msg_silent = save_msg_silent;
831 
832     if (pending == CSTP_RETURN)
833 	vim_free(s);
834     else if (pending & CSTP_THROW)
835 	vim_free(mesg);
836 }
837 
838 /*
839  * If something is made pending in a finally clause, report it if required by
840  * the 'verbose' option or when debugging.
841  */
842     void
843 report_make_pending(int pending, void *value)
844 {
845     if (p_verbose >= 14 || debug_break_level > 0)
846     {
847 	if (debug_break_level <= 0)
848 	    verbose_enter();
849 	report_pending(RP_MAKE, pending, value);
850 	if (debug_break_level <= 0)
851 	    verbose_leave();
852     }
853 }
854 
855 /*
856  * If something pending in a finally clause is resumed at the ":endtry", report
857  * it if required by the 'verbose' option or when debugging.
858  */
859     static void
860 report_resume_pending(int pending, void *value)
861 {
862     if (p_verbose >= 14 || debug_break_level > 0)
863     {
864 	if (debug_break_level <= 0)
865 	    verbose_enter();
866 	report_pending(RP_RESUME, pending, value);
867 	if (debug_break_level <= 0)
868 	    verbose_leave();
869     }
870 }
871 
872 /*
873  * If something pending in a finally clause is discarded, report it if required
874  * by the 'verbose' option or when debugging.
875  */
876     static void
877 report_discard_pending(int pending, void *value)
878 {
879     if (p_verbose >= 14 || debug_break_level > 0)
880     {
881 	if (debug_break_level <= 0)
882 	    verbose_enter();
883 	report_pending(RP_DISCARD, pending, value);
884 	if (debug_break_level <= 0)
885 	    verbose_leave();
886     }
887 }
888 
889 
890 /*
891  * ":eval".
892  */
893     void
894 ex_eval(exarg_T *eap)
895 {
896     typval_T	tv;
897     evalarg_T	evalarg;
898 
899     fill_evalarg_from_eap(&evalarg, eap, eap->skip);
900 
901     if (eval0(eap->arg, &tv, eap, &evalarg) == OK)
902 	clear_tv(&tv);
903 
904     clear_evalarg(&evalarg, eap);
905 }
906 
907 /*
908  * Start a new scope/block.  Caller should have checked that cs_idx is not
909  * exceeding CSTACK_LEN.
910  */
911     static void
912 enter_block(cstack_T *cstack)
913 {
914     ++cstack->cs_idx;
915     if (in_vim9script())
916     {
917 	scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
918 
919 	cstack->cs_script_var_len[cstack->cs_idx] = si->sn_var_vals.ga_len;
920 	cstack->cs_block_id[cstack->cs_idx] = ++si->sn_last_block_id;
921 	si->sn_current_block_id = si->sn_last_block_id;
922     }
923 }
924 
925     static void
926 leave_block(cstack_T *cstack)
927 {
928     if (in_vim9script() && SCRIPT_ID_VALID(current_sctx.sc_sid))
929     {
930 	scriptitem_T	*si = SCRIPT_ITEM(current_sctx.sc_sid);
931 	int		i;
932 	int		func_defined =
933 			       cstack->cs_flags[cstack->cs_idx] & CSF_FUNC_DEF;
934 
935 	for (i = cstack->cs_script_var_len[cstack->cs_idx];
936 					       i < si->sn_var_vals.ga_len; ++i)
937 	{
938 	    svar_T	*sv = ((svar_T *)si->sn_var_vals.ga_data) + i;
939 
940 	    // sv_name is set to NULL if it was already removed.  This happens
941 	    // when it was defined in an inner block and no functions were
942 	    // defined there.
943 	    if (sv->sv_name != NULL)
944 		// Remove a variable declared inside the block, if it still
945 		// exists, from sn_vars and move the value into sn_all_vars
946 		// if "func_defined" is non-zero.
947 		hide_script_var(si, i, func_defined);
948 	}
949 
950 	// TODO: is this needed?
951 	cstack->cs_script_var_len[cstack->cs_idx] = si->sn_var_vals.ga_len;
952 
953 	if (cstack->cs_idx == 0)
954 	    si->sn_current_block_id = 0;
955 	else
956 	    si->sn_current_block_id = cstack->cs_block_id[cstack->cs_idx - 1];
957     }
958     --cstack->cs_idx;
959 }
960 
961 /*
962  * ":if".
963  */
964     void
965 ex_if(exarg_T *eap)
966 {
967     int		error;
968     int		skip;
969     int		result;
970     cstack_T	*cstack = eap->cstack;
971 
972     if (cstack->cs_idx == CSTACK_LEN - 1)
973 	eap->errmsg = _("E579: :if nesting too deep");
974     else
975     {
976 	enter_block(cstack);
977 	cstack->cs_flags[cstack->cs_idx] = 0;
978 
979 	/*
980 	 * Don't do something after an error, interrupt, or throw, or when
981 	 * there is a surrounding conditional and it was not active.
982 	 */
983 	skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
984 		&& !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
985 
986 	result = eval_to_bool(eap->arg, &error, eap, skip);
987 
988 	if (!skip && !error)
989 	{
990 	    if (result)
991 		cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE | CSF_TRUE;
992 	}
993 	else
994 	    // set TRUE, so this conditional will never get active
995 	    cstack->cs_flags[cstack->cs_idx] = CSF_TRUE;
996     }
997 }
998 
999 /*
1000  * ":endif".
1001  */
1002     void
1003 ex_endif(exarg_T *eap)
1004 {
1005     cstack_T	*cstack = eap->cstack;
1006 
1007     did_endif = TRUE;
1008     if (cstack->cs_idx < 0
1009 	    || (cstack->cs_flags[cstack->cs_idx]
1010 				& (CSF_WHILE | CSF_FOR | CSF_TRY | CSF_BLOCK)))
1011 	eap->errmsg = _(e_endif_without_if);
1012     else
1013     {
1014 	/*
1015 	 * When debugging or a breakpoint was encountered, display the debug
1016 	 * prompt (if not already done).  This shows the user that an ":endif"
1017 	 * is executed when the ":if" or a previous ":elseif" was not TRUE.
1018 	 * Handle a ">quit" debug command as if an interrupt had occurred before
1019 	 * the ":endif".  That is, throw an interrupt exception if appropriate.
1020 	 * Doing this here prevents an exception for a parsing error being
1021 	 * discarded by throwing the interrupt exception later on.
1022 	 */
1023 	if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE)
1024 						    && dbg_check_skipped(eap))
1025 	    (void)do_intthrow(cstack);
1026 
1027 	leave_block(cstack);
1028     }
1029 }
1030 
1031 /*
1032  * ":else" and ":elseif".
1033  */
1034     void
1035 ex_else(exarg_T *eap)
1036 {
1037     int		error;
1038     int		skip;
1039     int		result;
1040     cstack_T	*cstack = eap->cstack;
1041 
1042     /*
1043      * Don't do something after an error, interrupt, or throw, or when there is
1044      * a surrounding conditional and it was not active.
1045      */
1046     skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
1047 	    && !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
1048 
1049     if (cstack->cs_idx < 0
1050 	    || (cstack->cs_flags[cstack->cs_idx]
1051 				& (CSF_WHILE | CSF_FOR | CSF_TRY | CSF_BLOCK)))
1052     {
1053 	if (eap->cmdidx == CMD_else)
1054 	{
1055 	    eap->errmsg = _(e_else_without_if);
1056 	    return;
1057 	}
1058 	eap->errmsg = _(e_elseif_without_if);
1059 	skip = TRUE;
1060     }
1061     else if (cstack->cs_flags[cstack->cs_idx] & CSF_ELSE)
1062     {
1063 	if (eap->cmdidx == CMD_else)
1064 	{
1065 	    eap->errmsg = _("E583: multiple :else");
1066 	    return;
1067 	}
1068 	eap->errmsg = _("E584: :elseif after :else");
1069 	skip = TRUE;
1070     }
1071 
1072     // if skipping or the ":if" was TRUE, reset ACTIVE, otherwise set it
1073     if (skip || cstack->cs_flags[cstack->cs_idx] & CSF_TRUE)
1074     {
1075 	if (eap->errmsg == NULL)
1076 	    cstack->cs_flags[cstack->cs_idx] = CSF_TRUE;
1077 	skip = TRUE;	// don't evaluate an ":elseif"
1078     }
1079     else
1080 	cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE;
1081 
1082     /*
1083      * When debugging or a breakpoint was encountered, display the debug prompt
1084      * (if not already done).  This shows the user that an ":else" or ":elseif"
1085      * is executed when the ":if" or previous ":elseif" was not TRUE.  Handle
1086      * a ">quit" debug command as if an interrupt had occurred before the
1087      * ":else" or ":elseif".  That is, set "skip" and throw an interrupt
1088      * exception if appropriate.  Doing this here prevents that an exception
1089      * for a parsing errors is discarded when throwing the interrupt exception
1090      * later on.
1091      */
1092     if (!skip && dbg_check_skipped(eap) && got_int)
1093     {
1094 	(void)do_intthrow(cstack);
1095 	skip = TRUE;
1096     }
1097 
1098     if (eap->cmdidx == CMD_elseif)
1099     {
1100 	result = eval_to_bool(eap->arg, &error, eap, skip);
1101 
1102 	// When throwing error exceptions, we want to throw always the first
1103 	// of several errors in a row.  This is what actually happens when
1104 	// a conditional error was detected above and there is another failure
1105 	// when parsing the expression.  Since the skip flag is set in this
1106 	// case, the parsing error will be ignored by emsg().
1107 	if (!skip && !error)
1108 	{
1109 	    if (result)
1110 		cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE | CSF_TRUE;
1111 	    else
1112 		cstack->cs_flags[cstack->cs_idx] = 0;
1113 	}
1114 	else if (eap->errmsg == NULL)
1115 	    // set TRUE, so this conditional will never get active
1116 	    cstack->cs_flags[cstack->cs_idx] = CSF_TRUE;
1117     }
1118     else
1119 	cstack->cs_flags[cstack->cs_idx] |= CSF_ELSE;
1120 }
1121 
1122 /*
1123  * Handle ":while" and ":for".
1124  */
1125     void
1126 ex_while(exarg_T *eap)
1127 {
1128     int		error;
1129     int		skip;
1130     int		result;
1131     cstack_T	*cstack = eap->cstack;
1132 
1133     if (cstack->cs_idx == CSTACK_LEN - 1)
1134 	eap->errmsg = _("E585: :while/:for nesting too deep");
1135     else
1136     {
1137 	/*
1138 	 * The loop flag is set when we have jumped back from the matching
1139 	 * ":endwhile" or ":endfor".  When not set, need to initialise this
1140 	 * cstack entry.
1141 	 */
1142 	if ((cstack->cs_lflags & CSL_HAD_LOOP) == 0)
1143 	{
1144 	    enter_block(cstack);
1145 	    ++cstack->cs_looplevel;
1146 	    cstack->cs_line[cstack->cs_idx] = -1;
1147 	}
1148 	cstack->cs_flags[cstack->cs_idx] =
1149 			       eap->cmdidx == CMD_while ? CSF_WHILE : CSF_FOR;
1150 
1151 	/*
1152 	 * Don't do something after an error, interrupt, or throw, or when
1153 	 * there is a surrounding conditional and it was not active.
1154 	 */
1155 	skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
1156 		&& !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
1157 	if (eap->cmdidx == CMD_while)
1158 	{
1159 	    /*
1160 	     * ":while bool-expr"
1161 	     */
1162 	    result = eval_to_bool(eap->arg, &error, eap, skip);
1163 	}
1164 	else
1165 	{
1166 	    void	*fi;
1167 	    evalarg_T	evalarg;
1168 
1169 	    CLEAR_FIELD(evalarg);
1170 	    evalarg.eval_flags = skip ? 0 : EVAL_EVALUATE;
1171 	    if (getline_equal(eap->getline, eap->cookie, getsourceline))
1172 	    {
1173 		evalarg.eval_getline = eap->getline;
1174 		evalarg.eval_cookie = eap->cookie;
1175 	    }
1176 
1177 	    /*
1178 	     * ":for var in list-expr"
1179 	     */
1180 	    if ((cstack->cs_lflags & CSL_HAD_LOOP) != 0)
1181 	    {
1182 		// Jumping here from a ":continue" or ":endfor": use the
1183 		// previously evaluated list.
1184 		fi = cstack->cs_forinfo[cstack->cs_idx];
1185 		error = FALSE;
1186 
1187 		// the "in expr" is not used, skip over it
1188 		skip_for_lines(fi, &evalarg);
1189 	    }
1190 	    else
1191 	    {
1192 		// Evaluate the argument and get the info in a structure.
1193 		fi = eval_for_line(eap->arg, &error, eap, &evalarg);
1194 		cstack->cs_forinfo[cstack->cs_idx] = fi;
1195 	    }
1196 
1197 	    // use the element at the start of the list and advance
1198 	    if (!error && fi != NULL && !skip)
1199 		result = next_for_item(fi, eap->arg);
1200 	    else
1201 		result = FALSE;
1202 
1203 	    if (!result)
1204 	    {
1205 		free_for_info(fi);
1206 		cstack->cs_forinfo[cstack->cs_idx] = NULL;
1207 	    }
1208 	    clear_evalarg(&evalarg, eap);
1209 	}
1210 
1211 	/*
1212 	 * If this cstack entry was just initialised and is active, set the
1213 	 * loop flag, so do_cmdline() will set the line number in cs_line[].
1214 	 * If executing the command a second time, clear the loop flag.
1215 	 */
1216 	if (!skip && !error && result)
1217 	{
1218 	    cstack->cs_flags[cstack->cs_idx] |= (CSF_ACTIVE | CSF_TRUE);
1219 	    cstack->cs_lflags ^= CSL_HAD_LOOP;
1220 	}
1221 	else
1222 	{
1223 	    cstack->cs_lflags &= ~CSL_HAD_LOOP;
1224 	    // If the ":while" evaluates to FALSE or ":for" is past the end of
1225 	    // the list, show the debug prompt at the ":endwhile"/":endfor" as
1226 	    // if there was a ":break" in a ":while"/":for" evaluating to
1227 	    // TRUE.
1228 	    if (!skip && !error)
1229 		cstack->cs_flags[cstack->cs_idx] |= CSF_TRUE;
1230 	}
1231     }
1232 }
1233 
1234 /*
1235  * ":continue"
1236  */
1237     void
1238 ex_continue(exarg_T *eap)
1239 {
1240     int		idx;
1241     cstack_T	*cstack = eap->cstack;
1242 
1243     if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0)
1244 	eap->errmsg = _(e_continue);
1245     else
1246     {
1247 	// Try to find the matching ":while".  This might stop at a try
1248 	// conditional not in its finally clause (which is then to be executed
1249 	// next).  Therefor, inactivate all conditionals except the ":while"
1250 	// itself (if reached).
1251 	idx = cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, FALSE);
1252 	if (idx >= 0 && (cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR)))
1253 	{
1254 	    rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel);
1255 
1256 	    /*
1257 	     * Set CSL_HAD_CONT, so do_cmdline() will jump back to the
1258 	     * matching ":while".
1259 	     */
1260 	    cstack->cs_lflags |= CSL_HAD_CONT;	// let do_cmdline() handle it
1261 	}
1262 	else
1263 	{
1264 	    // If a try conditional not in its finally clause is reached first,
1265 	    // make the ":continue" pending for execution at the ":endtry".
1266 	    cstack->cs_pending[idx] = CSTP_CONTINUE;
1267 	    report_make_pending(CSTP_CONTINUE, NULL);
1268 	}
1269     }
1270 }
1271 
1272 /*
1273  * ":break"
1274  */
1275     void
1276 ex_break(exarg_T *eap)
1277 {
1278     int		idx;
1279     cstack_T	*cstack = eap->cstack;
1280 
1281     if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0)
1282 	eap->errmsg = _(e_break);
1283     else
1284     {
1285 	// Inactivate conditionals until the matching ":while" or a try
1286 	// conditional not in its finally clause (which is then to be
1287 	// executed next) is found.  In the latter case, make the ":break"
1288 	// pending for execution at the ":endtry".
1289 	idx = cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, TRUE);
1290 	if (idx >= 0 && !(cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR)))
1291 	{
1292 	    cstack->cs_pending[idx] = CSTP_BREAK;
1293 	    report_make_pending(CSTP_BREAK, NULL);
1294 	}
1295     }
1296 }
1297 
1298 /*
1299  * ":endwhile" and ":endfor"
1300  */
1301     void
1302 ex_endwhile(exarg_T *eap)
1303 {
1304     cstack_T	*cstack = eap->cstack;
1305     int		idx;
1306     char	*err;
1307     int		csf;
1308     int		fl;
1309 
1310     if (eap->cmdidx == CMD_endwhile)
1311     {
1312 	err = e_while;
1313 	csf = CSF_WHILE;
1314     }
1315     else
1316     {
1317 	err = e_for;
1318 	csf = CSF_FOR;
1319     }
1320 
1321     if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0)
1322 	eap->errmsg = _(err);
1323     else
1324     {
1325 	fl =  cstack->cs_flags[cstack->cs_idx];
1326 	if (!(fl & csf))
1327 	{
1328 	    // If we are in a ":while" or ":for" but used the wrong endloop
1329 	    // command, do not rewind to the next enclosing ":for"/":while".
1330 	    if (fl & CSF_WHILE)
1331 		eap->errmsg = _("E732: Using :endfor with :while");
1332 	    else if (fl & CSF_FOR)
1333 		eap->errmsg = _("E733: Using :endwhile with :for");
1334 	}
1335 	if (!(fl & (CSF_WHILE | CSF_FOR)))
1336 	{
1337 	    if (!(fl & CSF_TRY))
1338 		eap->errmsg = _(e_endif);
1339 	    else if (fl & CSF_FINALLY)
1340 		eap->errmsg = _(e_endtry);
1341 	    // Try to find the matching ":while" and report what's missing.
1342 	    for (idx = cstack->cs_idx; idx > 0; --idx)
1343 	    {
1344 		fl =  cstack->cs_flags[idx];
1345 		if ((fl & CSF_TRY) && !(fl & CSF_FINALLY))
1346 		{
1347 		    // Give up at a try conditional not in its finally clause.
1348 		    // Ignore the ":endwhile"/":endfor".
1349 		    eap->errmsg = _(err);
1350 		    return;
1351 		}
1352 		if (fl & csf)
1353 		    break;
1354 	    }
1355 	    // Cleanup and rewind all contained (and unclosed) conditionals.
1356 	    (void)cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, FALSE);
1357 	    rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel);
1358 	}
1359 
1360 	/*
1361 	 * When debugging or a breakpoint was encountered, display the debug
1362 	 * prompt (if not already done).  This shows the user that an
1363 	 * ":endwhile"/":endfor" is executed when the ":while" was not TRUE or
1364 	 * after a ":break".  Handle a ">quit" debug command as if an
1365 	 * interrupt had occurred before the ":endwhile"/":endfor".  That is,
1366 	 * throw an interrupt exception if appropriate.  Doing this here
1367 	 * prevents that an exception for a parsing error is discarded when
1368 	 * throwing the interrupt exception later on.
1369 	 */
1370 	else if (cstack->cs_flags[cstack->cs_idx] & CSF_TRUE
1371 		&& !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE)
1372 		&& dbg_check_skipped(eap))
1373 	    (void)do_intthrow(cstack);
1374 
1375 	/*
1376 	 * Set loop flag, so do_cmdline() will jump back to the matching
1377 	 * ":while" or ":for".
1378 	 */
1379 	cstack->cs_lflags |= CSL_HAD_ENDLOOP;
1380     }
1381 }
1382 
1383 /*
1384  * "{" start of a block in Vim9 script
1385  */
1386     void
1387 ex_block(exarg_T *eap)
1388 {
1389     cstack_T	*cstack = eap->cstack;
1390 
1391     if (cstack->cs_idx == CSTACK_LEN - 1)
1392 	eap->errmsg = _("E579: block nesting too deep");
1393     else
1394     {
1395 	enter_block(cstack);
1396 	cstack->cs_flags[cstack->cs_idx] = CSF_BLOCK | CSF_ACTIVE | CSF_TRUE;
1397     }
1398 }
1399 
1400 /*
1401  * "}" end of a block in Vim9 script
1402  */
1403     void
1404 ex_endblock(exarg_T *eap)
1405 {
1406     cstack_T	*cstack = eap->cstack;
1407 
1408     if (cstack->cs_idx < 0
1409 	    || (cstack->cs_flags[cstack->cs_idx] & CSF_BLOCK) == 0)
1410 	eap->errmsg = _(e_endblock_without_block);
1411     else
1412 	leave_block(cstack);
1413 }
1414 
1415 /*
1416  * ":throw expr"
1417  */
1418     void
1419 ex_throw(exarg_T *eap)
1420 {
1421     char_u	*arg = eap->arg;
1422     char_u	*value;
1423 
1424     if (*arg != NUL && *arg != '|' && *arg != '\n')
1425 	value = eval_to_string_skip(arg, eap, eap->skip);
1426     else
1427     {
1428 	emsg(_(e_argreq));
1429 	value = NULL;
1430     }
1431 
1432     // On error or when an exception is thrown during argument evaluation, do
1433     // not throw.
1434     if (!eap->skip && value != NULL)
1435     {
1436 	if (throw_exception(value, ET_USER, NULL) == FAIL)
1437 	    vim_free(value);
1438 	else
1439 	    do_throw(eap->cstack);
1440     }
1441 }
1442 
1443 /*
1444  * Throw the current exception through the specified cstack.  Common routine
1445  * for ":throw" (user exception) and error and interrupt exceptions.  Also
1446  * used for rethrowing an uncaught exception.
1447  */
1448     void
1449 do_throw(cstack_T *cstack)
1450 {
1451     int		idx;
1452     int		inactivate_try = FALSE;
1453 
1454     /*
1455      * Cleanup and inactivate up to the next surrounding try conditional that
1456      * is not in its finally clause.  Normally, do not inactivate the try
1457      * conditional itself, so that its ACTIVE flag can be tested below.  But
1458      * if a previous error or interrupt has not been converted to an exception,
1459      * inactivate the try conditional, too, as if the conversion had been done,
1460      * and reset the did_emsg or got_int flag, so this won't happen again at
1461      * the next surrounding try conditional.
1462      */
1463 #ifndef THROW_ON_ERROR_TRUE
1464     if (did_emsg && !THROW_ON_ERROR)
1465     {
1466 	inactivate_try = TRUE;
1467 	did_emsg = FALSE;
1468     }
1469 #endif
1470 #ifndef THROW_ON_INTERRUPT_TRUE
1471     if (got_int && !THROW_ON_INTERRUPT)
1472     {
1473 	inactivate_try = TRUE;
1474 	got_int = FALSE;
1475     }
1476 #endif
1477     idx = cleanup_conditionals(cstack, 0, inactivate_try);
1478     if (idx >= 0)
1479     {
1480 	/*
1481 	 * If this try conditional is active and we are before its first
1482 	 * ":catch", set THROWN so that the ":catch" commands will check
1483 	 * whether the exception matches.  When the exception came from any of
1484 	 * the catch clauses, it will be made pending at the ":finally" (if
1485 	 * present) and rethrown at the ":endtry".  This will also happen if
1486 	 * the try conditional is inactive.  This is the case when we are
1487 	 * throwing an exception due to an error or interrupt on the way from
1488 	 * a preceding ":continue", ":break", ":return", ":finish", error or
1489 	 * interrupt (not converted to an exception) to the finally clause or
1490 	 * from a preceding throw of a user or error or interrupt exception to
1491 	 * the matching catch clause or the finally clause.
1492 	 */
1493 	if (!(cstack->cs_flags[idx] & CSF_CAUGHT))
1494 	{
1495 	    if (cstack->cs_flags[idx] & CSF_ACTIVE)
1496 		cstack->cs_flags[idx] |= CSF_THROWN;
1497 	    else
1498 		// THROWN may have already been set for a catchable exception
1499 		// that has been discarded.  Ensure it is reset for the new
1500 		// exception.
1501 		cstack->cs_flags[idx] &= ~CSF_THROWN;
1502 	}
1503 	cstack->cs_flags[idx] &= ~CSF_ACTIVE;
1504 	cstack->cs_exception[idx] = current_exception;
1505     }
1506 #if 0
1507     // TODO: Add optimization below.  Not yet done because of interface
1508     // problems to eval.c and ex_cmds2.c. (Servatius)
1509     else
1510     {
1511 	/*
1512 	 * There are no catch clauses to check or finally clauses to execute.
1513 	 * End the current script or function.  The exception will be rethrown
1514 	 * in the caller.
1515 	 */
1516 	if (getline_equal(eap->getline, eap->cookie, get_func_line))
1517 	    current_funccal->returned = TRUE;
1518 	elseif (eap->get_func_line == getsourceline)
1519 	    ((struct source_cookie *)eap->cookie)->finished = TRUE;
1520     }
1521 #endif
1522 
1523     did_throw = TRUE;
1524 }
1525 
1526 /*
1527  * ":try"
1528  */
1529     void
1530 ex_try(exarg_T *eap)
1531 {
1532     int		skip;
1533     cstack_T	*cstack = eap->cstack;
1534 
1535     if (cstack->cs_idx == CSTACK_LEN - 1)
1536 	eap->errmsg = _("E601: :try nesting too deep");
1537     else
1538     {
1539 	enter_block(cstack);
1540 	++cstack->cs_trylevel;
1541 	cstack->cs_flags[cstack->cs_idx] = CSF_TRY;
1542 	cstack->cs_pending[cstack->cs_idx] = CSTP_NONE;
1543 
1544 	/*
1545 	 * Don't do something after an error, interrupt, or throw, or when there
1546 	 * is a surrounding conditional and it was not active.
1547 	 */
1548 	skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
1549 		&& !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
1550 
1551 	if (!skip)
1552 	{
1553 	    // Set ACTIVE and TRUE.  TRUE means that the corresponding ":catch"
1554 	    // commands should check for a match if an exception is thrown and
1555 	    // that the finally clause needs to be executed.
1556 	    cstack->cs_flags[cstack->cs_idx] |= CSF_ACTIVE | CSF_TRUE;
1557 
1558 	    /*
1559 	     * ":silent!", even when used in a try conditional, disables
1560 	     * displaying of error messages and conversion of errors to
1561 	     * exceptions.  When the silent commands again open a try
1562 	     * conditional, save "emsg_silent" and reset it so that errors are
1563 	     * again converted to exceptions.  The value is restored when that
1564 	     * try conditional is left.  If it is left normally, the commands
1565 	     * following the ":endtry" are again silent.  If it is left by
1566 	     * a ":continue", ":break", ":return", or ":finish", the commands
1567 	     * executed next are again silent.  If it is left due to an
1568 	     * aborting error, an interrupt, or an exception, restoring
1569 	     * "emsg_silent" does not matter since we are already in the
1570 	     * aborting state and/or the exception has already been thrown.
1571 	     * The effect is then just freeing the memory that was allocated
1572 	     * to save the value.
1573 	     */
1574 	    if (emsg_silent)
1575 	    {
1576 		eslist_T	*elem;
1577 
1578 		elem = ALLOC_ONE(struct eslist_elem);
1579 		if (elem == NULL)
1580 		    emsg(_(e_outofmem));
1581 		else
1582 		{
1583 		    elem->saved_emsg_silent = emsg_silent;
1584 		    elem->next = cstack->cs_emsg_silent_list;
1585 		    cstack->cs_emsg_silent_list = elem;
1586 		    cstack->cs_flags[cstack->cs_idx] |= CSF_SILENT;
1587 		    emsg_silent = 0;
1588 		}
1589 	    }
1590 	}
1591 
1592     }
1593 }
1594 
1595 /*
1596  * ":catch /{pattern}/" and ":catch"
1597  */
1598     void
1599 ex_catch(exarg_T *eap)
1600 {
1601     int		idx = 0;
1602     int		give_up = FALSE;
1603     int		skip = FALSE;
1604     int		caught = FALSE;
1605     char_u	*end;
1606     int		save_char = 0;
1607     char_u	*save_cpo;
1608     regmatch_T	regmatch;
1609     int		prev_got_int;
1610     cstack_T	*cstack = eap->cstack;
1611     char_u	*pat;
1612 
1613     if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)
1614     {
1615 	eap->errmsg = _(e_catch);
1616 	give_up = TRUE;
1617     }
1618     else
1619     {
1620 	if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
1621 	{
1622 	    // Report what's missing if the matching ":try" is not in its
1623 	    // finally clause.
1624 	    eap->errmsg = get_end_emsg(cstack);
1625 	    skip = TRUE;
1626 	}
1627 	for (idx = cstack->cs_idx; idx > 0; --idx)
1628 	    if (cstack->cs_flags[idx] & CSF_TRY)
1629 		break;
1630 	if (cstack->cs_flags[idx] & CSF_FINALLY)
1631 	{
1632 	    // Give up for a ":catch" after ":finally" and ignore it.
1633 	    // Just parse.
1634 	    eap->errmsg = _("E604: :catch after :finally");
1635 	    give_up = TRUE;
1636 	}
1637 	else
1638 	    rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,
1639 						       &cstack->cs_looplevel);
1640     }
1641 
1642     if (ends_excmd2(eap->cmd, eap->arg))   // no argument, catch all errors
1643     {
1644 	pat = (char_u *)".*";
1645 	end = NULL;
1646 	eap->nextcmd = find_nextcmd(eap->arg);
1647     }
1648     else
1649     {
1650 	pat = eap->arg + 1;
1651 	end = skip_regexp_err(pat, *eap->arg, TRUE);
1652 	if (end == NULL)
1653 	    give_up = TRUE;
1654     }
1655 
1656     if (!give_up)
1657     {
1658 	/*
1659 	 * Don't do something when no exception has been thrown or when the
1660 	 * corresponding try block never got active (because of an inactive
1661 	 * surrounding conditional or after an error or interrupt or throw).
1662 	 */
1663 	if (!did_throw || !(cstack->cs_flags[idx] & CSF_TRUE))
1664 	    skip = TRUE;
1665 
1666 	/*
1667 	 * Check for a match only if an exception is thrown but not caught by
1668 	 * a previous ":catch".  An exception that has replaced a discarded
1669 	 * exception is not checked (THROWN is not set then).
1670 	 */
1671 	if (!skip && (cstack->cs_flags[idx] & CSF_THROWN)
1672 		&& !(cstack->cs_flags[idx] & CSF_CAUGHT))
1673 	{
1674 	    if (end != NULL && *end != NUL
1675 				      && !ends_excmd2(end, skipwhite(end + 1)))
1676 	    {
1677 		semsg(_(e_trailing_arg), end);
1678 		return;
1679 	    }
1680 
1681 	    // When debugging or a breakpoint was encountered, display the
1682 	    // debug prompt (if not already done) before checking for a match.
1683 	    // This is a helpful hint for the user when the regular expression
1684 	    // matching fails.  Handle a ">quit" debug command as if an
1685 	    // interrupt had occurred before the ":catch".  That is, discard
1686 	    // the original exception, replace it by an interrupt exception,
1687 	    // and don't catch it in this try block.
1688 	    if (!dbg_check_skipped(eap) || !do_intthrow(cstack))
1689 	    {
1690 		// Terminate the pattern and avoid the 'l' flag in 'cpoptions'
1691 		// while compiling it.
1692 		if (end != NULL)
1693 		{
1694 		    save_char = *end;
1695 		    *end = NUL;
1696 		}
1697 		save_cpo  = p_cpo;
1698 		p_cpo = (char_u *)"";
1699 		// Disable error messages, it will make current_exception
1700 		// invalid.
1701 		++emsg_off;
1702 		regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
1703 		--emsg_off;
1704 		regmatch.rm_ic = FALSE;
1705 		if (end != NULL)
1706 		    *end = save_char;
1707 		p_cpo = save_cpo;
1708 		if (regmatch.regprog == NULL)
1709 		    semsg(_(e_invarg2), pat);
1710 		else
1711 		{
1712 		    /*
1713 		     * Save the value of got_int and reset it.  We don't want
1714 		     * a previous interruption cancel matching, only hitting
1715 		     * CTRL-C while matching should abort it.
1716 		     */
1717 		    prev_got_int = got_int;
1718 		    got_int = FALSE;
1719 		    caught = vim_regexec_nl(&regmatch,
1720 			       (char_u *)current_exception->value, (colnr_T)0);
1721 		    got_int |= prev_got_int;
1722 		    vim_regfree(regmatch.regprog);
1723 		}
1724 	    }
1725 	}
1726 
1727 	if (caught)
1728 	{
1729 	    // Make this ":catch" clause active and reset did_emsg, got_int,
1730 	    // and did_throw.  Put the exception on the caught stack.
1731 	    cstack->cs_flags[idx] |= CSF_ACTIVE | CSF_CAUGHT;
1732 	    did_emsg = got_int = did_throw = FALSE;
1733 	    catch_exception((except_T *)cstack->cs_exception[idx]);
1734 	    // It's mandatory that the current exception is stored in the cstack
1735 	    // so that it can be discarded at the next ":catch", ":finally", or
1736 	    // ":endtry" or when the catch clause is left by a ":continue",
1737 	    // ":break", ":return", ":finish", error, interrupt, or another
1738 	    // exception.
1739 	    if (cstack->cs_exception[cstack->cs_idx] != current_exception)
1740 		internal_error("ex_catch()");
1741 	}
1742 	else
1743 	{
1744 	    /*
1745 	     * If there is a preceding catch clause and it caught the exception,
1746 	     * finish the exception now.  This happens also after errors except
1747 	     * when this ":catch" was after the ":finally" or not within
1748 	     * a ":try".  Make the try conditional inactive so that the
1749 	     * following catch clauses are skipped.  On an error or interrupt
1750 	     * after the preceding try block or catch clause was left by
1751 	     * a ":continue", ":break", ":return", or ":finish", discard the
1752 	     * pending action.
1753 	     */
1754 	    cleanup_conditionals(cstack, CSF_TRY, TRUE);
1755 	}
1756     }
1757 
1758     if (end != NULL)
1759 	eap->nextcmd = find_nextcmd(end);
1760 }
1761 
1762 /*
1763  * ":finally"
1764  */
1765     void
1766 ex_finally(exarg_T *eap)
1767 {
1768     int		idx;
1769     int		skip = FALSE;
1770     int		pending = CSTP_NONE;
1771     cstack_T	*cstack = eap->cstack;
1772 
1773     if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)
1774 	eap->errmsg = _(e_finally);
1775     else
1776     {
1777 	if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
1778 	{
1779 	    eap->errmsg = get_end_emsg(cstack);
1780 	    for (idx = cstack->cs_idx - 1; idx > 0; --idx)
1781 		if (cstack->cs_flags[idx] & CSF_TRY)
1782 		    break;
1783 	    // Make this error pending, so that the commands in the following
1784 	    // finally clause can be executed.  This overrules also a pending
1785 	    // ":continue", ":break", ":return", or ":finish".
1786 	    pending = CSTP_ERROR;
1787 	}
1788 	else
1789 	    idx = cstack->cs_idx;
1790 
1791 	if (cstack->cs_flags[idx] & CSF_FINALLY)
1792 	{
1793 	    // Give up for a multiple ":finally" and ignore it.
1794 	    eap->errmsg = _(e_finally_dup);
1795 	    return;
1796 	}
1797 	rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,
1798 						       &cstack->cs_looplevel);
1799 
1800 	/*
1801 	 * Don't do something when the corresponding try block never got active
1802 	 * (because of an inactive surrounding conditional or after an error or
1803 	 * interrupt or throw) or for a ":finally" without ":try" or a multiple
1804 	 * ":finally".  After every other error (did_emsg or the conditional
1805 	 * errors detected above) or after an interrupt (got_int) or an
1806 	 * exception (did_throw), the finally clause must be executed.
1807 	 */
1808 	skip = !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE);
1809 
1810 	if (!skip)
1811 	{
1812 	    // When debugging or a breakpoint was encountered, display the
1813 	    // debug prompt (if not already done).  The user then knows that the
1814 	    // finally clause is executed.
1815 	    if (dbg_check_skipped(eap))
1816 	    {
1817 		// Handle a ">quit" debug command as if an interrupt had
1818 		// occurred before the ":finally".  That is, discard the
1819 		// original exception and replace it by an interrupt
1820 		// exception.
1821 		(void)do_intthrow(cstack);
1822 	    }
1823 
1824 	    /*
1825 	     * If there is a preceding catch clause and it caught the exception,
1826 	     * finish the exception now.  This happens also after errors except
1827 	     * when this is a multiple ":finally" or one not within a ":try".
1828 	     * After an error or interrupt, this also discards a pending
1829 	     * ":continue", ":break", ":finish", or ":return" from the preceding
1830 	     * try block or catch clause.
1831 	     */
1832 	    cleanup_conditionals(cstack, CSF_TRY, FALSE);
1833 
1834 	    /*
1835 	     * Make did_emsg, got_int, did_throw pending.  If set, they overrule
1836 	     * a pending ":continue", ":break", ":return", or ":finish".  Then
1837 	     * we have particularly to discard a pending return value (as done
1838 	     * by the call to cleanup_conditionals() above when did_emsg or
1839 	     * got_int is set).  The pending values are restored by the
1840 	     * ":endtry", except if there is a new error, interrupt, exception,
1841 	     * ":continue", ":break", ":return", or ":finish" in the following
1842 	     * finally clause.  A missing ":endwhile", ":endfor" or ":endif"
1843 	     * detected here is treated as if did_emsg and did_throw had
1844 	     * already been set, respectively in case that the error is not
1845 	     * converted to an exception, did_throw had already been unset.
1846 	     * We must not set did_emsg here since that would suppress the
1847 	     * error message.
1848 	     */
1849 	    if (pending == CSTP_ERROR || did_emsg || got_int || did_throw)
1850 	    {
1851 		if (cstack->cs_pending[cstack->cs_idx] == CSTP_RETURN)
1852 		{
1853 		    report_discard_pending(CSTP_RETURN,
1854 					   cstack->cs_rettv[cstack->cs_idx]);
1855 		    discard_pending_return(cstack->cs_rettv[cstack->cs_idx]);
1856 		}
1857 		if (pending == CSTP_ERROR && !did_emsg)
1858 		    pending |= (THROW_ON_ERROR) ? CSTP_THROW : 0;
1859 		else
1860 		    pending |= did_throw ? CSTP_THROW : 0;
1861 		pending |= did_emsg  ? CSTP_ERROR     : 0;
1862 		pending |= got_int   ? CSTP_INTERRUPT : 0;
1863 		cstack->cs_pending[cstack->cs_idx] = pending;
1864 
1865 		// It's mandatory that the current exception is stored in the
1866 		// cstack so that it can be rethrown at the ":endtry" or be
1867 		// discarded if the finally clause is left by a ":continue",
1868 		// ":break", ":return", ":finish", error, interrupt, or another
1869 		// exception.  When emsg() is called for a missing ":endif" or
1870 		// a missing ":endwhile"/":endfor" detected here, the
1871 		// exception will be discarded.
1872 		if (did_throw && cstack->cs_exception[cstack->cs_idx]
1873 							 != current_exception)
1874 		    internal_error("ex_finally()");
1875 	    }
1876 
1877 	    /*
1878 	     * Set CSL_HAD_FINA, so do_cmdline() will reset did_emsg,
1879 	     * got_int, and did_throw and make the finally clause active.
1880 	     * This will happen after emsg() has been called for a missing
1881 	     * ":endif" or a missing ":endwhile"/":endfor" detected here, so
1882 	     * that the following finally clause will be executed even then.
1883 	     */
1884 	    cstack->cs_lflags |= CSL_HAD_FINA;
1885 	}
1886     }
1887 }
1888 
1889 /*
1890  * ":endtry"
1891  */
1892     void
1893 ex_endtry(exarg_T *eap)
1894 {
1895     int		idx;
1896     int		skip;
1897     int		rethrow = FALSE;
1898     int		pending = CSTP_NONE;
1899     void	*rettv = NULL;
1900     cstack_T	*cstack = eap->cstack;
1901 
1902     if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)
1903 	eap->errmsg = _(e_no_endtry);
1904     else
1905     {
1906 	/*
1907 	 * Don't do something after an error, interrupt or throw in the try
1908 	 * block, catch clause, or finally clause preceding this ":endtry" or
1909 	 * when an error or interrupt occurred after a ":continue", ":break",
1910 	 * ":return", or ":finish" in a try block or catch clause preceding this
1911 	 * ":endtry" or when the try block never got active (because of an
1912 	 * inactive surrounding conditional or after an error or interrupt or
1913 	 * throw) or when there is a surrounding conditional and it has been
1914 	 * made inactive by a ":continue", ":break", ":return", or ":finish" in
1915 	 * the finally clause.  The latter case need not be tested since then
1916 	 * anything pending has already been discarded. */
1917 	skip = did_emsg || got_int || did_throw ||
1918 	    !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE);
1919 
1920 	if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
1921 	{
1922 	    eap->errmsg = get_end_emsg(cstack);
1923 	    // Find the matching ":try" and report what's missing.
1924 	    idx = cstack->cs_idx;
1925 	    do
1926 		--idx;
1927 	    while (idx > 0 && !(cstack->cs_flags[idx] & CSF_TRY));
1928 	    rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,
1929 						       &cstack->cs_looplevel);
1930 	    skip = TRUE;
1931 
1932 	    /*
1933 	     * If an exception is being thrown, discard it to prevent it from
1934 	     * being rethrown at the end of this function.  It would be
1935 	     * discarded by the error message, anyway.  Resets did_throw.
1936 	     * This does not affect the script termination due to the error
1937 	     * since "trylevel" is decremented after emsg() has been called.
1938 	     */
1939 	    if (did_throw)
1940 		discard_current_exception();
1941 	}
1942 	else
1943 	{
1944 	    idx = cstack->cs_idx;
1945 
1946 	    /*
1947 	     * If we stopped with the exception currently being thrown at this
1948 	     * try conditional since we didn't know that it doesn't have
1949 	     * a finally clause, we need to rethrow it after closing the try
1950 	     * conditional.
1951 	     */
1952 	    if (did_throw && (cstack->cs_flags[idx] & CSF_TRUE)
1953 		    && !(cstack->cs_flags[idx] & CSF_FINALLY))
1954 		rethrow = TRUE;
1955 	}
1956 
1957 	// If there was no finally clause, show the user when debugging or
1958 	// a breakpoint was encountered that the end of the try conditional has
1959 	// been reached: display the debug prompt (if not already done).  Do
1960 	// this on normal control flow or when an exception was thrown, but not
1961 	// on an interrupt or error not converted to an exception or when
1962 	// a ":break", ":continue", ":return", or ":finish" is pending.  These
1963 	// actions are carried out immediately.
1964 	if ((rethrow || (!skip
1965 			&& !(cstack->cs_flags[idx] & CSF_FINALLY)
1966 			&& !cstack->cs_pending[idx]))
1967 		&& dbg_check_skipped(eap))
1968 	{
1969 	    // Handle a ">quit" debug command as if an interrupt had occurred
1970 	    // before the ":endtry".  That is, throw an interrupt exception and
1971 	    // set "skip" and "rethrow".
1972 	    if (got_int)
1973 	    {
1974 		skip = TRUE;
1975 		(void)do_intthrow(cstack);
1976 		// The do_intthrow() call may have reset did_throw or
1977 		// cstack->cs_pending[idx].
1978 		rethrow = FALSE;
1979 		if (did_throw && !(cstack->cs_flags[idx] & CSF_FINALLY))
1980 		    rethrow = TRUE;
1981 	    }
1982 	}
1983 
1984 	/*
1985 	 * If a ":return" is pending, we need to resume it after closing the
1986 	 * try conditional; remember the return value.  If there was a finally
1987 	 * clause making an exception pending, we need to rethrow it.  Make it
1988 	 * the exception currently being thrown.
1989 	 */
1990 	if (!skip)
1991 	{
1992 	    pending = cstack->cs_pending[idx];
1993 	    cstack->cs_pending[idx] = CSTP_NONE;
1994 	    if (pending == CSTP_RETURN)
1995 		rettv = cstack->cs_rettv[idx];
1996 	    else if (pending & CSTP_THROW)
1997 		current_exception = cstack->cs_exception[idx];
1998 	}
1999 
2000 	/*
2001 	 * Discard anything pending on an error, interrupt, or throw in the
2002 	 * finally clause.  If there was no ":finally", discard a pending
2003 	 * ":continue", ":break", ":return", or ":finish" if an error or
2004 	 * interrupt occurred afterwards, but before the ":endtry" was reached.
2005 	 * If an exception was caught by the last of the catch clauses and there
2006 	 * was no finally clause, finish the exception now.  This happens also
2007 	 * after errors except when this ":endtry" is not within a ":try".
2008 	 * Restore "emsg_silent" if it has been reset by this try conditional.
2009 	 */
2010 	(void)cleanup_conditionals(cstack, CSF_TRY | CSF_SILENT, TRUE);
2011 
2012 	leave_block(cstack);
2013 	--cstack->cs_trylevel;
2014 
2015 	if (!skip)
2016 	{
2017 	    report_resume_pending(pending,
2018 		    (pending == CSTP_RETURN) ? rettv :
2019 		    (pending & CSTP_THROW) ? (void *)current_exception : NULL);
2020 	    switch (pending)
2021 	    {
2022 		case CSTP_NONE:
2023 		    break;
2024 
2025 		// Reactivate a pending ":continue", ":break", ":return",
2026 		// ":finish" from the try block or a catch clause of this try
2027 		// conditional.  This is skipped, if there was an error in an
2028 		// (unskipped) conditional command or an interrupt afterwards
2029 		// or if the finally clause is present and executed a new error,
2030 		// interrupt, throw, ":continue", ":break", ":return", or
2031 		// ":finish".
2032 		case CSTP_CONTINUE:
2033 		    ex_continue(eap);
2034 		    break;
2035 		case CSTP_BREAK:
2036 		    ex_break(eap);
2037 		    break;
2038 		case CSTP_RETURN:
2039 		    do_return(eap, FALSE, FALSE, rettv);
2040 		    break;
2041 		case CSTP_FINISH:
2042 		    do_finish(eap, FALSE);
2043 		    break;
2044 
2045 		// When the finally clause was entered due to an error,
2046 		// interrupt or throw (as opposed to a ":continue", ":break",
2047 		// ":return", or ":finish"), restore the pending values of
2048 		// did_emsg, got_int, and did_throw.  This is skipped, if there
2049 		// was a new error, interrupt, throw, ":continue", ":break",
2050 		// ":return", or ":finish".  in the finally clause.
2051 		default:
2052 		    if (pending & CSTP_ERROR)
2053 			did_emsg = TRUE;
2054 		    if (pending & CSTP_INTERRUPT)
2055 			got_int = TRUE;
2056 		    if (pending & CSTP_THROW)
2057 			rethrow = TRUE;
2058 		    break;
2059 	    }
2060 	}
2061 
2062 	if (rethrow)
2063 	    // Rethrow the current exception (within this cstack).
2064 	    do_throw(cstack);
2065     }
2066 }
2067 
2068 /*
2069  * enter_cleanup() and leave_cleanup()
2070  *
2071  * Functions to be called before/after invoking a sequence of autocommands for
2072  * cleanup for a failed command.  (Failure means here that a call to emsg()
2073  * has been made, an interrupt occurred, or there is an uncaught exception
2074  * from a previous autocommand execution of the same command.)
2075  *
2076  * Call enter_cleanup() with a pointer to a cleanup_T and pass the same
2077  * pointer to leave_cleanup().  The cleanup_T structure stores the pending
2078  * error/interrupt/exception state.
2079  */
2080 
2081 /*
2082  * This function works a bit like ex_finally() except that there was not
2083  * actually an extra try block around the part that failed and an error or
2084  * interrupt has not (yet) been converted to an exception.  This function
2085  * saves the error/interrupt/ exception state and prepares for the call to
2086  * do_cmdline() that is going to be made for the cleanup autocommand
2087  * execution.
2088  */
2089     void
2090 enter_cleanup(cleanup_T *csp)
2091 {
2092     int		pending = CSTP_NONE;
2093 
2094     /*
2095      * Postpone did_emsg, got_int, did_throw.  The pending values will be
2096      * restored by leave_cleanup() except if there was an aborting error,
2097      * interrupt, or uncaught exception after this function ends.
2098      */
2099     if (did_emsg || got_int || did_throw || need_rethrow)
2100     {
2101 	csp->pending = (did_emsg     ? CSTP_ERROR     : 0)
2102 		     | (got_int      ? CSTP_INTERRUPT : 0)
2103 		     | (did_throw    ? CSTP_THROW     : 0)
2104 		     | (need_rethrow ? CSTP_THROW     : 0);
2105 
2106 	// If we are currently throwing an exception (did_throw), save it as
2107 	// well.  On an error not yet converted to an exception, update
2108 	// "force_abort" and reset "cause_abort" (as do_errthrow() would do).
2109 	// This is needed for the do_cmdline() call that is going to be made
2110 	// for autocommand execution.  We need not save *msg_list because
2111 	// there is an extra instance for every call of do_cmdline(), anyway.
2112 	if (did_throw || need_rethrow)
2113 	{
2114 	    csp->exception = current_exception;
2115 	    current_exception = NULL;
2116 	}
2117 	else
2118 	{
2119 	    csp->exception = NULL;
2120 	    if (did_emsg)
2121 	    {
2122 		force_abort |= cause_abort;
2123 		cause_abort = FALSE;
2124 	    }
2125 	}
2126 	did_emsg = got_int = did_throw = need_rethrow = FALSE;
2127 
2128 	// Report if required by the 'verbose' option or when debugging.
2129 	report_make_pending(pending, csp->exception);
2130     }
2131     else
2132     {
2133 	csp->pending = CSTP_NONE;
2134 	csp->exception = NULL;
2135     }
2136 }
2137 
2138 /*
2139  * See comment above enter_cleanup() for how this function is used.
2140  *
2141  * This function is a bit like ex_endtry() except that there was not actually
2142  * an extra try block around the part that failed and an error or interrupt
2143  * had not (yet) been converted to an exception when the cleanup autocommand
2144  * sequence was invoked.
2145  *
2146  * This function has to be called with the address of the cleanup_T structure
2147  * filled by enter_cleanup() as an argument; it restores the error/interrupt/
2148  * exception state saved by that function - except there was an aborting
2149  * error, an interrupt or an uncaught exception during execution of the
2150  * cleanup autocommands.  In the latter case, the saved error/interrupt/
2151  * exception state is discarded.
2152  */
2153     void
2154 leave_cleanup(cleanup_T *csp)
2155 {
2156     int		pending = csp->pending;
2157 
2158     if (pending == CSTP_NONE)	// nothing to do
2159 	return;
2160 
2161     // If there was an aborting error, an interrupt, or an uncaught exception
2162     // after the corresponding call to enter_cleanup(), discard what has been
2163     // made pending by it.  Report this to the user if required by the
2164     // 'verbose' option or when debugging.
2165     if (aborting() || need_rethrow)
2166     {
2167 	if (pending & CSTP_THROW)
2168 	    // Cancel the pending exception (includes report).
2169 	    discard_exception((except_T *)csp->exception, FALSE);
2170 	else
2171 	    report_discard_pending(pending, NULL);
2172 
2173 	// If an error was about to be converted to an exception when
2174 	// enter_cleanup() was called, free the message list.
2175 	if (msg_list != NULL)
2176 	    free_global_msglist();
2177     }
2178 
2179     /*
2180      * If there was no new error, interrupt, or throw between the calls
2181      * to enter_cleanup() and leave_cleanup(), restore the pending
2182      * error/interrupt/exception state.
2183      */
2184     else
2185     {
2186 	/*
2187 	 * If there was an exception being thrown when enter_cleanup() was
2188 	 * called, we need to rethrow it.  Make it the exception currently
2189 	 * being thrown.
2190 	 */
2191 	if (pending & CSTP_THROW)
2192 	    current_exception = csp->exception;
2193 
2194 	/*
2195 	 * If an error was about to be converted to an exception when
2196 	 * enter_cleanup() was called, let "cause_abort" take the part of
2197 	 * "force_abort" (as done by cause_errthrow()).
2198 	 */
2199 	else if (pending & CSTP_ERROR)
2200 	{
2201 	    cause_abort = force_abort;
2202 	    force_abort = FALSE;
2203 	}
2204 
2205 	/*
2206 	 * Restore the pending values of did_emsg, got_int, and did_throw.
2207 	 */
2208 	if (pending & CSTP_ERROR)
2209 	    did_emsg = TRUE;
2210 	if (pending & CSTP_INTERRUPT)
2211 	    got_int = TRUE;
2212 	if (pending & CSTP_THROW)
2213 	    need_rethrow = TRUE;    // did_throw will be set by do_one_cmd()
2214 
2215 	// Report if required by the 'verbose' option or when debugging.
2216 	report_resume_pending(pending,
2217 		   (pending & CSTP_THROW) ? (void *)current_exception : NULL);
2218     }
2219 }
2220 
2221 
2222 /*
2223  * Make conditionals inactive and discard what's pending in finally clauses
2224  * until the conditional type searched for or a try conditional not in its
2225  * finally clause is reached.  If this is in an active catch clause, finish
2226  * the caught exception.
2227  * Return the cstack index where the search stopped.
2228  * Values used for "searched_cond" are (CSF_WHILE | CSF_FOR) or CSF_TRY or 0,
2229  * the latter meaning the innermost try conditional not in its finally clause.
2230  * "inclusive" tells whether the conditional searched for should be made
2231  * inactive itself (a try conditional not in its finally clause possibly find
2232  * before is always made inactive).  If "inclusive" is TRUE and
2233  * "searched_cond" is CSF_TRY|CSF_SILENT, the saved former value of
2234  * "emsg_silent", if reset when the try conditional finally reached was
2235  * entered, is restored (used by ex_endtry()).  This is normally done only
2236  * when such a try conditional is left.
2237  */
2238     int
2239 cleanup_conditionals(
2240     cstack_T   *cstack,
2241     int		searched_cond,
2242     int		inclusive)
2243 {
2244     int		idx;
2245     int		stop = FALSE;
2246 
2247     for (idx = cstack->cs_idx; idx >= 0; --idx)
2248     {
2249 	if (cstack->cs_flags[idx] & CSF_TRY)
2250 	{
2251 	    /*
2252 	     * Discard anything pending in a finally clause and continue the
2253 	     * search.  There may also be a pending ":continue", ":break",
2254 	     * ":return", or ":finish" before the finally clause.  We must not
2255 	     * discard it, unless an error or interrupt occurred afterwards.
2256 	     */
2257 	    if (did_emsg || got_int || (cstack->cs_flags[idx] & CSF_FINALLY))
2258 	    {
2259 		switch (cstack->cs_pending[idx])
2260 		{
2261 		    case CSTP_NONE:
2262 			break;
2263 
2264 		    case CSTP_CONTINUE:
2265 		    case CSTP_BREAK:
2266 		    case CSTP_FINISH:
2267 			report_discard_pending(cstack->cs_pending[idx], NULL);
2268 			cstack->cs_pending[idx] = CSTP_NONE;
2269 			break;
2270 
2271 		    case CSTP_RETURN:
2272 			report_discard_pending(CSTP_RETURN,
2273 						      cstack->cs_rettv[idx]);
2274 			discard_pending_return(cstack->cs_rettv[idx]);
2275 			cstack->cs_pending[idx] = CSTP_NONE;
2276 			break;
2277 
2278 		    default:
2279 			if (cstack->cs_flags[idx] & CSF_FINALLY)
2280 			{
2281 			    if (cstack->cs_pending[idx] & CSTP_THROW)
2282 			    {
2283 				// Cancel the pending exception.  This is in the
2284 				// finally clause, so that the stack of the
2285 				// caught exceptions is not involved.
2286 				discard_exception(
2287 					(except_T *)cstack->cs_exception[idx],
2288 					FALSE);
2289 			    }
2290 			    else
2291 				report_discard_pending(cstack->cs_pending[idx],
2292 					NULL);
2293 			    cstack->cs_pending[idx] = CSTP_NONE;
2294 			}
2295 			break;
2296 		}
2297 	    }
2298 
2299 	    /*
2300 	     * Stop at a try conditional not in its finally clause.  If this try
2301 	     * conditional is in an active catch clause, finish the caught
2302 	     * exception.
2303 	     */
2304 	    if (!(cstack->cs_flags[idx] & CSF_FINALLY))
2305 	    {
2306 		if ((cstack->cs_flags[idx] & CSF_ACTIVE)
2307 			&& (cstack->cs_flags[idx] & CSF_CAUGHT))
2308 		    finish_exception((except_T *)cstack->cs_exception[idx]);
2309 		// Stop at this try conditional - except the try block never
2310 		// got active (because of an inactive surrounding conditional
2311 		// or when the ":try" appeared after an error or interrupt or
2312 		// throw).
2313 		if (cstack->cs_flags[idx] & CSF_TRUE)
2314 		{
2315 		    if (searched_cond == 0 && !inclusive)
2316 			break;
2317 		    stop = TRUE;
2318 		}
2319 	    }
2320 	}
2321 
2322 	// Stop on the searched conditional type (even when the surrounding
2323 	// conditional is not active or something has been made pending).
2324 	// If "inclusive" is TRUE and "searched_cond" is CSF_TRY|CSF_SILENT,
2325 	// check first whether "emsg_silent" needs to be restored.
2326 	if (cstack->cs_flags[idx] & searched_cond)
2327 	{
2328 	    if (!inclusive)
2329 		break;
2330 	    stop = TRUE;
2331 	}
2332 	cstack->cs_flags[idx] &= ~CSF_ACTIVE;
2333 	if (stop && searched_cond != (CSF_TRY | CSF_SILENT))
2334 	    break;
2335 
2336 	/*
2337 	 * When leaving a try conditional that reset "emsg_silent" on its
2338 	 * entry after saving the original value, restore that value here and
2339 	 * free the memory used to store it.
2340 	 */
2341 	if ((cstack->cs_flags[idx] & CSF_TRY)
2342 		&& (cstack->cs_flags[idx] & CSF_SILENT))
2343 	{
2344 	    eslist_T	*elem;
2345 
2346 	    elem = cstack->cs_emsg_silent_list;
2347 	    cstack->cs_emsg_silent_list = elem->next;
2348 	    emsg_silent = elem->saved_emsg_silent;
2349 	    vim_free(elem);
2350 	    cstack->cs_flags[idx] &= ~CSF_SILENT;
2351 	}
2352 	if (stop)
2353 	    break;
2354     }
2355     return idx;
2356 }
2357 
2358 /*
2359  * Return an appropriate error message for a missing endwhile/endfor/endif.
2360  */
2361    static char *
2362 get_end_emsg(cstack_T *cstack)
2363 {
2364     if (cstack->cs_flags[cstack->cs_idx] & CSF_WHILE)
2365 	return _(e_endwhile);
2366     if (cstack->cs_flags[cstack->cs_idx] & CSF_FOR)
2367 	return _(e_endfor);
2368     return _(e_endif);
2369 }
2370 
2371 
2372 /*
2373  * Rewind conditionals until index "idx" is reached.  "cond_type" and
2374  * "cond_level" specify a conditional type and the address of a level variable
2375  * which is to be decremented with each skipped conditional of the specified
2376  * type.
2377  * Also free "for info" structures where needed.
2378  */
2379     void
2380 rewind_conditionals(
2381     cstack_T   *cstack,
2382     int		idx,
2383     int		cond_type,
2384     int		*cond_level)
2385 {
2386     while (cstack->cs_idx > idx)
2387     {
2388 	if (cstack->cs_flags[cstack->cs_idx] & cond_type)
2389 	    --*cond_level;
2390 	if (cstack->cs_flags[cstack->cs_idx] & CSF_FOR)
2391 	    free_for_info(cstack->cs_forinfo[cstack->cs_idx]);
2392 	leave_block(cstack);
2393     }
2394 }
2395 
2396 /*
2397  * ":endfunction" when not after a ":function"
2398  */
2399     void
2400 ex_endfunction(exarg_T *eap)
2401 {
2402     if (eap->cmdidx == CMD_enddef)
2403 	emsg(_("E193: :enddef not inside a function"));
2404     else
2405 	emsg(_("E193: :endfunction not inside a function"));
2406 }
2407 
2408 /*
2409  * Return TRUE if the string "p" looks like a ":while" or ":for" command.
2410  */
2411     int
2412 has_loop_cmd(char_u *p)
2413 {
2414     int		len;
2415 
2416     // skip modifiers, white space and ':'
2417     for (;;)
2418     {
2419 	while (*p == ' ' || *p == '\t' || *p == ':')
2420 	    ++p;
2421 	len = modifier_len(p);
2422 	if (len == 0)
2423 	    break;
2424 	p += len;
2425     }
2426     if ((p[0] == 'w' && p[1] == 'h')
2427 	    || (p[0] == 'f' && p[1] == 'o' && p[2] == 'r'))
2428 	return TRUE;
2429     return FALSE;
2430 }
2431 
2432 #endif // FEAT_EVAL
2433