robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

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