patch 9.1.0984: exception handling can be improved

Problem:  exception handling can be improved
Solution: add v:stacktrace and getstacktrace()

closes: #16360

Co-authored-by: Naruhiko Nishino <naru123456789@gmail.com>
Signed-off-by: ichizok <gclient.gaap@gmail.com>
Signed-off-by: Christian Brabandt <cb@256bit.org>
diff --git a/src/dict.c b/src/dict.c
index d3636f3..8f0db7e 100644
--- a/src/dict.c
+++ b/src/dict.c
@@ -532,6 +532,29 @@
 }
 
 /*
+ * Add a function entry to dictionary "d".
+ * Returns FAIL when out of memory and when key already exists.
+ */
+    int
+dict_add_func(dict_T *d, char *key, ufunc_T *fp)
+{
+    dictitem_T	*item;
+
+    item = dictitem_alloc((char_u *)key);
+    if (item == NULL)
+	return FAIL;
+    item->di_tv.v_type = VAR_FUNC;
+    item->di_tv.vval.v_string = vim_strsave(fp->uf_name);
+    if (dict_add(d, item) == FAIL)
+    {
+	dictitem_free(item);
+	return FAIL;
+    }
+    func_ref(item->di_tv.vval.v_string);
+    return OK;
+}
+
+/*
  * Initializes "iter" for iterating over dictionary items with
  * dict_iterate_next().
  * If "var" is not a Dict or an empty Dict then there will be nothing to
diff --git a/src/evalfunc.c b/src/evalfunc.c
index ec108b0c..d81480b 100644
--- a/src/evalfunc.c
+++ b/src/evalfunc.c
@@ -2170,6 +2170,8 @@
 			ret_string,	    f_getregtype},
     {"getscriptinfo",	0, 1, 0,	    arg1_dict_any,
 			ret_list_dict_any,  f_getscriptinfo},
+    {"getstacktrace",	0, 0, 0,	    NULL,
+			ret_list_dict_any,  f_getstacktrace},
     {"gettabinfo",	0, 1, FEARG_1,	    arg1_number,
 			ret_list_dict_any,  f_gettabinfo},
     {"gettabvar",	2, 3, FEARG_1,	    arg3_number_string_any,
diff --git a/src/evalvars.c b/src/evalvars.c
index 038d7ed..f5fef04 100644
--- a/src/evalvars.c
+++ b/src/evalvars.c
@@ -160,7 +160,8 @@
     {VV_NAME("python3_version",	 VAR_NUMBER), NULL, VV_RO},
     {VV_NAME("t_typealias",	 VAR_NUMBER), NULL, VV_RO},
     {VV_NAME("t_enum",		 VAR_NUMBER), NULL, VV_RO},
-    {VV_NAME("t_enumvalue",	 VAR_NUMBER), NULL, VV_RO}
+    {VV_NAME("t_enumvalue",	 VAR_NUMBER), NULL, VV_RO},
+    {VV_NAME("stacktrace",	 VAR_LIST), &t_list_string, VV_RO},
 };
 
 // shorthand
diff --git a/src/ex_eval.c b/src/ex_eval.c
index 79e9d94..e996ce2 100644
--- a/src/ex_eval.c
+++ b/src/ex_eval.c
@@ -562,6 +562,10 @@
 	excp->throw_lnum = SOURCING_LNUM;
     }
 
+    excp->stacktrace = stacktrace_create();
+    if (excp->stacktrace != NULL)
+	excp->stacktrace->lv_refcount = 1;
+
     if (p_verbose >= 13 || debug_break_level > 0)
     {
 	int	save_msg_silent = msg_silent;
@@ -647,6 +651,7 @@
     if (excp->type == ET_ERROR)
 	free_msglist(excp->messages);
     vim_free(excp->throw_name);
+    list_unref(excp->stacktrace);
     vim_free(excp);
 }
 
@@ -671,6 +676,7 @@
     excp->caught = caught_stack;
     caught_stack = excp;
     set_vim_var_string(VV_EXCEPTION, (char_u *)excp->value, -1);
+    set_vim_var_list(VV_STACKTRACE, excp->stacktrace);
     if (*excp->throw_name != NUL)
     {
 	if (excp->throw_lnum != 0)
@@ -721,6 +727,7 @@
     if (caught_stack != NULL)
     {
 	set_vim_var_string(VV_EXCEPTION, (char_u *)caught_stack->value, -1);
+	set_vim_var_list(VV_STACKTRACE, caught_stack->stacktrace);
 	if (*caught_stack->throw_name != NUL)
 	{
 	    if (caught_stack->throw_lnum != 0)
@@ -741,6 +748,7 @@
     {
 	set_vim_var_string(VV_EXCEPTION, NULL, -1);
 	set_vim_var_string(VV_THROWPOINT, NULL, -1);
+	set_vim_var_list(VV_STACKTRACE, NULL);
     }
 
     // Discard the exception, but use the finish message for 'verbose'.
diff --git a/src/proto/dict.pro b/src/proto/dict.pro
index b1ceecc..421b169 100644
--- a/src/proto/dict.pro
+++ b/src/proto/dict.pro
@@ -22,6 +22,7 @@
 int dict_add_list(dict_T *d, char *key, list_T *list);
 int dict_add_tv(dict_T *d, char *key, typval_T *tv);
 int dict_add_callback(dict_T *d, char *key, callback_T *cb);
+int dict_add_func(dict_T *d, char *key, ufunc_T *fp);
 void dict_iterate_start(typval_T *var, dict_iterator_T *iter);
 char_u *dict_iterate_next(dict_iterator_T *iter, typval_T **tv_result);
 int dict_add_dict(dict_T *d, char *key, dict_T *dict);
diff --git a/src/proto/scriptfile.pro b/src/proto/scriptfile.pro
index c8ff04a..e81d16b 100644
--- a/src/proto/scriptfile.pro
+++ b/src/proto/scriptfile.pro
@@ -5,6 +5,8 @@
 int estack_top_is_ufunc(ufunc_T *ufunc, long lnum);
 estack_T *estack_pop(void);
 char_u *estack_sfile(estack_arg_T which);
+list_T *stacktrace_create(void);
+void f_getstacktrace(typval_T *argvars, typval_T *rettv);
 void ex_runtime(exarg_T *eap);
 void set_context_in_runtime_cmd(expand_T *xp, char_u *arg);
 int find_script_by_name(char_u *name);
diff --git a/src/scriptfile.c b/src/scriptfile.c
index 711f576..856d00f 100644
--- a/src/scriptfile.c
+++ b/src/scriptfile.c
@@ -237,6 +237,89 @@
 #endif
 }
 
+#ifdef FEAT_EVAL
+    static void
+stacktrace_push_item(
+	list_T		*l,
+	ufunc_T		*fp,
+	char_u		*event,
+	linenr_T	lnum,
+	char_u		*filepath)
+{
+    dict_T	*d;
+    typval_T	tv;
+
+    d = dict_alloc_lock(VAR_FIXED);
+    if (d == NULL)
+	return;
+
+    tv.v_type = VAR_DICT;
+    tv.v_lock = VAR_LOCKED;
+    tv.vval.v_dict = d;
+
+    if (fp != NULL)
+	dict_add_func(d, "funcref", fp);
+    if (event != NULL)
+	dict_add_string(d, "event", event);
+    dict_add_number(d, "lnum", lnum);
+    dict_add_string(d, "filepath", filepath);
+
+    list_append_tv(l, &tv);
+}
+
+/*
+ * Create the stacktrace from exestack.
+ */
+    list_T *
+stacktrace_create(void)
+{
+    list_T	*l;
+    int		i;
+
+    l = list_alloc();
+    if (l == NULL)
+	return NULL;
+
+    for (i = 0; i < exestack.ga_len; ++i)
+    {
+	estack_T *entry = &((estack_T *)exestack.ga_data)[i];
+	linenr_T lnum = entry->es_lnum;
+
+	if (entry->es_type == ETYPE_SCRIPT)
+	    stacktrace_push_item(l, NULL, NULL, lnum, entry->es_name);
+	else if (entry->es_type == ETYPE_UFUNC)
+	{
+	    ufunc_T *fp = entry->es_info.ufunc;
+	    sctx_T sctx = fp->uf_script_ctx;
+	    char_u *filepath = sctx.sc_sid > 0 ?
+				   get_scriptname(sctx.sc_sid) : (char_u *)"";
+
+	    lnum += sctx.sc_lnum;
+	    stacktrace_push_item(l, fp, NULL, lnum, filepath);
+	}
+	else if (entry->es_type == ETYPE_AUCMD)
+	{
+	    sctx_T sctx = *acp_script_ctx(entry->es_info.aucmd);
+	    char_u *filepath = sctx.sc_sid > 0 ?
+				   get_scriptname(sctx.sc_sid) : (char_u *)"";
+
+	    lnum += sctx.sc_lnum;
+	    stacktrace_push_item(l, NULL, entry->es_name, lnum, filepath);
+	}
+    }
+    return l;
+}
+
+/*
+ * getstacktrace() function
+ */
+    void
+f_getstacktrace(typval_T *argvars UNUSED, typval_T *rettv)
+{
+    rettv_list_set(rettv, stacktrace_create());
+}
+#endif
+
 /*
  * Get DIP_ flags from the [where] argument of a :runtime command.
  * "*argp" is advanced to after the [where] argument if it is found.
diff --git a/src/structs.h b/src/structs.h
index c036bf1..87aca30 100644
--- a/src/structs.h
+++ b/src/structs.h
@@ -63,6 +63,17 @@
 
 #define GA_EMPTY    {0, 0, 0, 0, NULL}
 
+// On rare systems "char" is unsigned, sometimes we really want a signed 8-bit
+// value.
+typedef signed char	int8_T;
+typedef double		float_T;
+
+typedef struct typval_S		typval_T;
+typedef struct listvar_S	list_T;
+typedef struct dictvar_S	dict_T;
+typedef struct partial_S	partial_T;
+typedef struct blobvar_S	blob_T;
+
 typedef struct window_S		win_T;
 typedef struct wininfo_S	wininfo_T;
 typedef struct frame_S		frame_T;
@@ -1087,6 +1098,7 @@
     struct msglist	*messages;	// message(s) causing error exception
     char_u		*throw_name;	// name of the throw point
     linenr_T		throw_lnum;	// line number of the throw point
+    list_T		*stacktrace;	// stacktrace
     except_T		*caught;	// next exception on the caught stack
 };
 
@@ -1447,18 +1459,6 @@
 # endif
 #endif
 
-// On rare systems "char" is unsigned, sometimes we really want a signed 8-bit
-// value.
-typedef signed char int8_T;
-
-typedef double	float_T;
-
-typedef struct typval_S typval_T;
-typedef struct listvar_S list_T;
-typedef struct dictvar_S dict_T;
-typedef struct partial_S partial_T;
-typedef struct blobvar_S blob_T;
-
 // Struct that holds both a normal function name and a partial_T, as used for a
 // callback argument.
 // When used temporarily "cb_name" is not allocated.  The refcounts to either
diff --git a/src/testdir/Make_all.mak b/src/testdir/Make_all.mak
index 7285354..13f4830 100644
--- a/src/testdir/Make_all.mak
+++ b/src/testdir/Make_all.mak
@@ -292,6 +292,7 @@
 	test_spell_utf8 \
 	test_spellfile \
 	test_spellrare \
+	test_stacktrace \
 	test_startup \
 	test_startup_utf8 \
 	test_stat \
@@ -545,6 +546,7 @@
 	test_spell_utf8.res \
 	test_spellfile.res \
 	test_spellrare.res \
+	test_stacktrace.res \
 	test_startup.res \
 	test_stat.res \
 	test_statusline.res \
diff --git a/src/testdir/test_stacktrace.vim b/src/testdir/test_stacktrace.vim
new file mode 100644
index 0000000..8cdb6ef
--- /dev/null
+++ b/src/testdir/test_stacktrace.vim
@@ -0,0 +1,107 @@
+" Test for getstacktrace() and v:stacktrace
+
+let s:thisfile = expand('%:p')
+let s:testdir = s:thisfile->fnamemodify(':h')
+
+func Filepath(name)
+  return s:testdir .. '/' .. a:name
+endfunc
+
+func AssertStacktrace(expect, actual)
+  call assert_equal(#{lnum: 617, filepath: Filepath('runtest.vim')}, a:actual[0])
+  call assert_equal(a:expect, a:actual[-len(a:expect):])
+endfunc
+
+func Test_getstacktrace()
+  let g:stacktrace = []
+  let lines1 =<< trim [SCRIPT]
+  " Xscript1
+  source Xscript2
+  func Xfunc1()
+    " Xfunc1
+    call Xfunc2()
+  endfunc
+  [SCRIPT]
+  let lines2 =<< trim [SCRIPT]
+  " Xscript2
+  func Xfunc2()
+    " Xfunc2
+    let g:stacktrace = getstacktrace()
+  endfunc
+  [SCRIPT]
+  call writefile(lines1, 'Xscript1', 'D')
+  call writefile(lines2, 'Xscript2', 'D')
+  source Xscript1
+  call Xfunc1()
+  call AssertStacktrace([
+        \ #{funcref: funcref('Test_getstacktrace'), lnum: 35, filepath: s:thisfile},
+        \ #{funcref: funcref('Xfunc1'), lnum: 5, filepath: Filepath('Xscript1')},
+        \ #{funcref: funcref('Xfunc2'), lnum: 4, filepath: Filepath('Xscript2')},
+        \ ], g:stacktrace)
+  unlet g:stacktrace
+endfunc
+
+func Test_getstacktrace_event()
+  let g:stacktrace = []
+  let lines1 =<< trim [SCRIPT]
+  " Xscript1
+  func Xfunc()
+    " Xfunc
+    let g:stacktrace = getstacktrace()
+  endfunc
+  augroup test_stacktrace
+    autocmd SourcePre * call Xfunc()
+  augroup END
+  [SCRIPT]
+  let lines2 =<< trim [SCRIPT]
+  " Xscript2
+  [SCRIPT]
+  call writefile(lines1, 'Xscript1', 'D')
+  call writefile(lines2, 'Xscript2', 'D')
+  source Xscript1
+  source Xscript2
+  call AssertStacktrace([
+       \ #{funcref: funcref('Test_getstacktrace_event'), lnum: 62, filepath: s:thisfile},
+       \ #{event: 'SourcePre Autocommands for "*"', lnum: 7, filepath: Filepath('Xscript1')},
+       \ #{funcref: funcref('Xfunc'), lnum: 4, filepath: Filepath('Xscript1')},
+       \ ], g:stacktrace)
+  augroup test_stacktrace
+    autocmd!
+  augroup END
+  unlet g:stacktrace
+endfunc
+
+func Test_vstacktrace()
+  let lines1 =<< trim [SCRIPT]
+  " Xscript1
+  source Xscript2
+  func Xfunc1()
+    " Xfunc1
+    call Xfunc2()
+  endfunc
+  [SCRIPT]
+  let lines2 =<< trim [SCRIPT]
+  " Xscript2
+  func Xfunc2()
+    " Xfunc2
+    throw 'Exception from Xfunc2'
+  endfunc
+  [SCRIPT]
+  call writefile(lines1, 'Xscript1', 'D')
+  call writefile(lines2, 'Xscript2', 'D')
+  source Xscript1
+  call assert_equal([], v:stacktrace)
+  try
+    call Xfunc1()
+  catch
+    let stacktrace = v:stacktrace
+  endtry
+  call assert_equal([], v:stacktrace)
+  call AssertStacktrace([
+       \ #{funcref: funcref('Test_vstacktrace'), lnum: 95, filepath: s:thisfile},
+       \ #{funcref: funcref('Xfunc1'), lnum: 5, filepath: Filepath('Xscript1')},
+       \ #{funcref: funcref('Xfunc2'), lnum: 4, filepath: Filepath('Xscript2')},
+       \ ], stacktrace)
+endfunc
+
+" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/version.c b/src/version.c
index 48a0606..cb1129d 100644
--- a/src/version.c
+++ b/src/version.c
@@ -705,6 +705,8 @@
 static int included_patches[] =
 {   /* Add new patch number below this line */
 /**/
+    984,
+/**/
     983,
 /**/
     982,
diff --git a/src/vim.h b/src/vim.h
index f8090bf..25c9d12 100644
--- a/src/vim.h
+++ b/src/vim.h
@@ -2190,7 +2190,8 @@
 #define VV_TYPE_TYPEALIAS 107
 #define VV_TYPE_ENUM	  108
 #define VV_TYPE_ENUMVALUE 109
-#define VV_LEN		110	// number of v: vars
+#define VV_STACKTRACE	110
+#define VV_LEN		111	// number of v: vars
 
 // used for v_number in VAR_BOOL and VAR_SPECIAL
 #define VVAL_FALSE	0L	// VAR_BOOL