XEmacs 21.2.29 "Hestia".
[chise/xemacs-chise.git.1] / src / eval.c
1 /* Evaluator for XEmacs Lisp interpreter.
2    Copyright (C) 1985-1987, 1992-1994 Free Software Foundation, Inc.
3    Copyright (C) 1995 Sun Microsystems, Inc.
4
5 This file is part of XEmacs.
6
7 XEmacs is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 2, or (at your option) any
10 later version.
11
12 XEmacs is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with XEmacs; see the file COPYING.  If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 /* Synched up with: FSF 19.30 (except for Fsignal), Mule 2.0. */
23
24 #include <config.h>
25 #include "lisp.h"
26
27 #include "commands.h"
28 #include "backtrace.h"
29 #include "bytecode.h"
30 #include "buffer.h"
31 #include "console.h"
32 #include "opaque.h"
33
34 #ifdef ERROR_CHECK_GC
35 int always_gc;                  /* Debugging hack */
36 #else
37 #define always_gc 0
38 #endif
39
40 struct backtrace *backtrace_list;
41
42 /* Note: you must always fill in all of the fields in a backtrace structure
43    before pushing them on the backtrace_list.  The profiling code depends
44    on this. */
45
46 #define PUSH_BACKTRACE(bt) do {         \
47   (bt).next = backtrace_list;           \
48   backtrace_list = &(bt);               \
49 } while (0)
50
51 #define POP_BACKTRACE(bt) do {          \
52   backtrace_list = (bt).next;           \
53 } while (0)
54
55 /* Macros for calling subrs with an argument list whose length is only
56    known at runtime.  See EXFUN and DEFUN for similar hackery.  */
57
58 #define AV_0(av)
59 #define AV_1(av) av[0]
60 #define AV_2(av) AV_1(av), av[1]
61 #define AV_3(av) AV_2(av), av[2]
62 #define AV_4(av) AV_3(av), av[3]
63 #define AV_5(av) AV_4(av), av[4]
64 #define AV_6(av) AV_5(av), av[5]
65 #define AV_7(av) AV_6(av), av[6]
66 #define AV_8(av) AV_7(av), av[7]
67
68 #define PRIMITIVE_FUNCALL_1(fn, av, ac) \
69 (((Lisp_Object (*)(EXFUN_##ac)) (fn)) (AV_##ac (av)))
70
71 /* If subrs take more than 8 arguments, more cases need to be added
72    to this switch.  (But wait - don't do it - if you really need
73    a SUBR with more than 8 arguments, use max_args == MANY.
74    See the DEFUN macro in lisp.h)  */
75 #define PRIMITIVE_FUNCALL(rv, fn, av, ac) do {                  \
76   void (*PF_fn)(void) = (void (*)(void)) fn;                    \
77   Lisp_Object *PF_av = (av);                                    \
78   switch (ac)                                                   \
79     {                                                           \
80     default:rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 0); break;   \
81     case 1: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 1); break;   \
82     case 2: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 2); break;   \
83     case 3: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 3); break;   \
84     case 4: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 4); break;   \
85     case 5: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 5); break;   \
86     case 6: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 6); break;   \
87     case 7: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 7); break;   \
88     case 8: rv = PRIMITIVE_FUNCALL_1(PF_fn, PF_av, 8); break;   \
89     }                                                           \
90 } while (0)
91
92 #define FUNCALL_SUBR(rv, subr, av, ac) \
93         PRIMITIVE_FUNCALL (rv, subr_function (subr), av, ac);
94
95
96 /* This is the list of current catches (and also condition-cases).
97    This is a stack: the most recent catch is at the head of the
98    list.  Catches are created by declaring a 'struct catchtag'
99    locally, filling the .TAG field in with the tag, and doing
100    a setjmp() on .JMP.  Fthrow() will store the value passed
101    to it in .VAL and longjmp() back to .JMP, back to the function
102    that established the catch.  This will always be either
103    internal_catch() (catches established internally or through
104    `catch') or condition_case_1 (condition-cases established
105    internally or through `condition-case').
106
107    The catchtag also records the current position in the
108    call stack (stored in BACKTRACE_LIST), the current position
109    in the specpdl stack (used for variable bindings and
110    unwind-protects), the value of LISP_EVAL_DEPTH, and the
111    current position in the GCPRO stack.  All of these are
112    restored by Fthrow().
113    */
114
115 struct catchtag *catchlist;
116
117 Lisp_Object Qautoload, Qmacro, Qexit;
118 Lisp_Object Qinteractive, Qcommandp, Qdefun, Qprogn, Qvalues;
119 Lisp_Object Vquit_flag, Vinhibit_quit;
120 Lisp_Object Qand_rest, Qand_optional;
121 Lisp_Object Qdebug_on_error, Qstack_trace_on_error;
122 Lisp_Object Qdebug_on_signal, Qstack_trace_on_signal;
123 Lisp_Object Qdebugger;
124 Lisp_Object Qinhibit_quit;
125 Lisp_Object Qrun_hooks;
126 Lisp_Object Qsetq;
127 Lisp_Object Qdisplay_warning;
128 Lisp_Object Vpending_warnings, Vpending_warnings_tail;
129 Lisp_Object Qif;
130
131 /* Records whether we want errors to occur.  This will be a boolean,
132    nil (errors OK) or t (no errors).  If t, an error will cause a
133    throw to Qunbound_suspended_errors_tag.
134
135    See call_with_suspended_errors(). */
136 Lisp_Object Vcurrent_error_state;
137
138 /* Current warning class when warnings occur, or nil for no warnings.
139    Only meaningful when Vcurrent_error_state is non-nil.
140    See call_with_suspended_errors(). */
141 Lisp_Object Vcurrent_warning_class;
142
143 /* Special catch tag used in call_with_suspended_errors(). */
144 Lisp_Object Qunbound_suspended_errors_tag;
145
146 /* Non-nil means we're going down, so we better not run any hooks
147    or do other non-essential stuff. */
148 int preparing_for_armageddon;
149
150 /* Non-nil means record all fset's and provide's, to be undone
151    if the file being autoloaded is not fully loaded.
152    They are recorded by being consed onto the front of Vautoload_queue:
153    (FUN . ODEF) for a defun, (OFEATURES . nil) for a provide.  */
154 Lisp_Object Vautoload_queue;
155
156 /* Current number of specbindings allocated in specpdl.  */
157 int specpdl_size;
158
159 /* Pointer to beginning of specpdl.  */
160 struct specbinding *specpdl;
161
162 /* Pointer to first unused element in specpdl.  */
163 struct specbinding *specpdl_ptr;
164
165 /* specpdl_ptr - specpdl */
166 int specpdl_depth_counter;
167
168 /* Maximum size allowed for specpdl allocation */
169 int max_specpdl_size;
170
171 /* Depth in Lisp evaluations and function calls.  */
172 static int lisp_eval_depth;
173
174 /* Maximum allowed depth in Lisp evaluations and function calls.  */
175 int max_lisp_eval_depth;
176
177 /* Nonzero means enter debugger before next function call */
178 static int debug_on_next_call;
179
180 /* List of conditions (non-nil atom means all) which cause a backtrace
181    if an error is handled by the command loop's error handler.  */
182 Lisp_Object Vstack_trace_on_error;
183
184 /* List of conditions (non-nil atom means all) which enter the debugger
185    if an error is handled by the command loop's error handler.  */
186 Lisp_Object Vdebug_on_error;
187
188 /* List of conditions and regexps specifying error messages which
189    do not enter the debugger even if Vdebug_on_error says they should.  */
190 Lisp_Object Vdebug_ignored_errors;
191
192 /* List of conditions (non-nil atom means all) which cause a backtrace
193    if any error is signalled.  */
194 Lisp_Object Vstack_trace_on_signal;
195
196 /* List of conditions (non-nil atom means all) which enter the debugger
197    if any error is signalled.  */
198 Lisp_Object Vdebug_on_signal;
199
200 /* Nonzero means enter debugger if a quit signal
201    is handled by the command loop's error handler.
202
203    From lisp, this is a boolean variable and may have the values 0 and 1.
204    But, eval.c temporarily uses the second bit of this variable to indicate
205    that a critical_quit is in progress.  The second bit is reset immediately
206    after it is processed in signal_call_debugger().  */
207 int debug_on_quit;
208
209 #if 0 /* FSFmacs */
210 /* entering_debugger is basically equivalent */
211 /* The value of num_nonmacro_input_chars as of the last time we
212    started to enter the debugger.  If we decide to enter the debugger
213    again when this is still equal to num_nonmacro_input_chars, then we
214    know that the debugger itself has an error, and we should just
215    signal the error instead of entering an infinite loop of debugger
216    invocations.  */
217 int when_entered_debugger;
218 #endif
219
220 /* Nonzero means we are trying to enter the debugger.
221    This is to prevent recursive attempts.
222    Cleared by the debugger calling Fbacktrace */
223 static int entering_debugger;
224
225 /* Function to call to invoke the debugger */
226 Lisp_Object Vdebugger;
227
228 /* Chain of condition handlers currently in effect.
229    The elements of this chain are contained in the stack frames
230    of Fcondition_case and internal_condition_case.
231    When an error is signaled (by calling Fsignal, below),
232    this chain is searched for an element that applies.
233
234    Each element of this list is one of the following:
235
236    A list of a handler function and possibly args to pass to
237    the function.  This is a handler established with
238    `call-with-condition-handler' (q.v.).
239
240    A list whose car is Qunbound and whose cdr is Qt.
241    This is a special condition-case handler established
242    by C code with condition_case_1().  All errors are
243    trapped; the debugger is not invoked even if
244    `debug-on-error' was set.
245
246    A list whose car is Qunbound and whose cdr is Qerror.
247    This is a special condition-case handler established
248    by C code with condition_case_1().  It is like Qt
249    except that the debugger is invoked normally if it is
250    called for.
251
252    A list whose car is Qunbound and whose cdr is a list
253    of lists (CONDITION-NAME BODY ...) exactly as in
254    `condition-case'.  This is a normal `condition-case'
255    handler.
256
257    Note that in all cases *except* the first, there is a
258    corresponding catch, whose TAG is the value of
259    Vcondition_handlers just after the handler data just
260    described is pushed onto it.  The reason is that
261    `condition-case' handlers need to throw back to the
262    place where the handler was installed before invoking
263    it, while `call-with-condition-handler' handlers are
264    invoked in the environment that `signal' was invoked
265    in.
266 */
267 static Lisp_Object Vcondition_handlers;
268
269
270 #if 0 /* no longer used */
271 /* Used for error catching purposes by throw_or_bomb_out */
272 static int throw_level;
273 #endif /* unused */
274
275 \f
276 /************************************************************************/
277 /*                      The subr object type                            */
278 /************************************************************************/
279
280 static void
281 print_subr (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
282 {
283   Lisp_Subr *subr = XSUBR (obj);
284   const char *header =
285     (subr->max_args == UNEVALLED) ? "#<special-form " : "#<subr ";
286   const char *name = subr_name (subr);
287   const char *trailer = subr->prompt ? " (interactive)>" : ">";
288
289   if (print_readably)
290     error ("printing unreadable object %s%s%s", header, name, trailer);
291
292   write_c_string (header,  printcharfun);
293   write_c_string (name,    printcharfun);
294   write_c_string (trailer, printcharfun);
295 }
296
297 static const struct lrecord_description subr_description[] = {
298   { XD_DOC_STRING, offsetof (Lisp_Subr, doc) },
299   { XD_END }
300 };
301
302 DEFINE_BASIC_LRECORD_IMPLEMENTATION ("subr", subr,
303                                      this_one_is_unmarkable, print_subr, 0, 0, 0,
304                                      subr_description,
305                                      Lisp_Subr);
306 \f
307 /************************************************************************/
308 /*                       Entering the debugger                          */
309 /************************************************************************/
310
311 /* unwind-protect used by call_debugger() to restore the value of
312    entering_debugger. (We cannot use specbind() because the
313    variable is not Lisp-accessible.) */
314
315 static Lisp_Object
316 restore_entering_debugger (Lisp_Object arg)
317 {
318   entering_debugger = ! NILP (arg);
319   return arg;
320 }
321
322 /* Actually call the debugger.  ARG is a list of args that will be
323    passed to the debugger function, as follows;
324
325 If due to frame exit, args are `exit' and the value being returned;
326  this function's value will be returned instead of that.
327 If due to error, args are `error' and a list of the args to `signal'.
328 If due to `apply' or `funcall' entry, one arg, `lambda'.
329 If due to `eval' entry, one arg, t.
330
331 */
332
333 static Lisp_Object
334 call_debugger_259 (Lisp_Object arg)
335 {
336   return apply1 (Vdebugger, arg);
337 }
338
339 /* Call the debugger, doing some encapsulation.  We make sure we have
340    some room on the eval and specpdl stacks, and bind entering_debugger
341    to 1 during this call.  This is used to trap errors that may occur
342    when entering the debugger (e.g. the value of `debugger' is invalid),
343    so that the debugger will not be recursively entered if debug-on-error
344    is set. (Otherwise, XEmacs would infinitely recurse, attempting to
345    enter the debugger.) entering_debugger gets reset to 0 as soon
346    as a backtrace is displayed, so that further errors can indeed be
347    handled normally.
348
349    We also establish a catch for 'debugger.  If the debugger function
350    throws to this instead of returning a value, it means that the user
351    pressed 'c' (pretend like the debugger was never entered).  The
352    function then returns Qunbound. (If the user pressed 'r', for
353    return a value, then the debugger function returns normally with
354    this value.)
355
356    The difference between 'c' and 'r' is as follows:
357
358    debug-on-call:
359      No difference.  The call proceeds as normal.
360    debug-on-exit:
361      With 'r', the specified value is returned as the function's
362      return value.  With 'c', the value that would normally be
363      returned is returned.
364    signal:
365      With 'r', the specified value is returned as the return
366      value of `signal'. (This is the only time that `signal'
367      can return, instead of making a non-local exit.) With `c',
368      `signal' will continue looking for handlers as if the
369      debugger was never entered, and will probably end up
370      throwing to a handler or to top-level.
371 */
372
373 static Lisp_Object
374 call_debugger (Lisp_Object arg)
375 {
376   int threw;
377   Lisp_Object val;
378   int speccount;
379
380   if (lisp_eval_depth + 20 > max_lisp_eval_depth)
381     max_lisp_eval_depth = lisp_eval_depth + 20;
382   if (specpdl_size + 40 > max_specpdl_size)
383     max_specpdl_size = specpdl_size + 40;
384   debug_on_next_call = 0;
385
386   speccount = specpdl_depth();
387   record_unwind_protect (restore_entering_debugger,
388                          (entering_debugger ? Qt : Qnil));
389   entering_debugger = 1;
390   val = internal_catch (Qdebugger, call_debugger_259, arg, &threw);
391
392   return unbind_to (speccount, ((threw)
393                                 ? Qunbound /* Not returning a value */
394                                 : val));
395 }
396
397 /* Called when debug-on-exit behavior is called for.  Enter the debugger
398    with the appropriate args for this.  VAL is the exit value that is
399    about to be returned. */
400
401 static Lisp_Object
402 do_debug_on_exit (Lisp_Object val)
403 {
404   /* This is falsified by call_debugger */
405   Lisp_Object v = call_debugger (list2 (Qexit, val));
406
407   return !UNBOUNDP (v) ? v : val;
408 }
409
410 /* Called when debug-on-call behavior is called for.  Enter the debugger
411    with the appropriate args for this.  VAL is either t for a call
412    through `eval' or 'lambda for a call through `funcall'.
413
414    #### The differentiation here between EVAL and FUNCALL is bogus.
415    FUNCALL can be defined as
416
417    (defmacro func (fun &rest args)
418      (cons (eval fun) args))
419
420    and should be treated as such.
421  */
422
423 static void
424 do_debug_on_call (Lisp_Object code)
425 {
426   debug_on_next_call = 0;
427   backtrace_list->debug_on_exit = 1;
428   call_debugger (list1 (code));
429 }
430
431 /* LIST is the value of one of the variables `debug-on-error',
432    `debug-on-signal', `stack-trace-on-error', or `stack-trace-on-signal',
433    and CONDITIONS is the list of error conditions associated with
434    the error being signalled.  This returns non-nil if LIST
435    matches CONDITIONS. (A nil value for LIST does not match
436    CONDITIONS.  A non-list value for LIST does match CONDITIONS.
437    A list matches CONDITIONS when one of the symbols in LIST is the
438    same as one of the symbols in CONDITIONS.) */
439
440 static int
441 wants_debugger (Lisp_Object list, Lisp_Object conditions)
442 {
443   if (NILP (list))
444     return 0;
445   if (! CONSP (list))
446     return 1;
447
448   while (CONSP (conditions))
449     {
450       Lisp_Object this, tail;
451       this = XCAR (conditions);
452       for (tail = list; CONSP (tail); tail = XCDR (tail))
453         if (EQ (XCAR (tail), this))
454           return 1;
455       conditions = XCDR (conditions);
456     }
457   return 0;
458 }
459
460
461 /* Return 1 if an error with condition-symbols CONDITIONS,
462    and described by SIGNAL-DATA, should skip the debugger
463    according to debugger-ignore-errors.  */
464
465 static int
466 skip_debugger (Lisp_Object conditions, Lisp_Object data)
467 {
468   /* This function can GC */
469   Lisp_Object tail;
470   int first_string = 1;
471   Lisp_Object error_message = Qnil;
472
473   for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
474     {
475       if (STRINGP (XCAR (tail)))
476         {
477           if (first_string)
478             {
479               error_message = Ferror_message_string (data);
480               first_string = 0;
481             }
482           if (fast_lisp_string_match (XCAR (tail), error_message) >= 0)
483             return 1;
484         }
485       else
486         {
487           Lisp_Object contail;
488
489           for (contail = conditions; CONSP (contail); contail = XCDR (contail))
490             if (EQ (XCAR (tail), XCAR (contail)))
491               return 1;
492         }
493     }
494
495   return 0;
496 }
497
498 /* Actually generate a backtrace on STREAM. */
499
500 static Lisp_Object
501 backtrace_259 (Lisp_Object stream)
502 {
503   return Fbacktrace (stream, Qt);
504 }
505
506 /* An error was signaled.  Maybe call the debugger, if the `debug-on-error'
507    etc. variables call for this.  CONDITIONS is the list of conditions
508    associated with the error being signalled.  SIG is the actual error
509    being signalled, and DATA is the associated data (these are exactly
510    the same as the arguments to `signal').  ACTIVE_HANDLERS is the
511    list of error handlers that are to be put in place while the debugger
512    is called.  This is generally the remaining handlers that are
513    outside of the innermost handler trapping this error.  This way,
514    if the same error occurs inside of the debugger, you usually don't get
515    the debugger entered recursively.
516
517    This function returns Qunbound if it didn't call the debugger or if
518    the user asked (through 'c') that XEmacs should pretend like the
519    debugger was never entered.  Otherwise, it returns the value
520    that the user specified with `r'. (Note that much of the time,
521    the user will abort with C-], and we will never have a chance to
522    return anything at all.)
523
524    SIGNAL_VARS_ONLY means we should only look at debug-on-signal
525    and stack-trace-on-signal to control whether we do anything.
526    This is so that debug-on-error doesn't make handled errors
527    cause the debugger to get invoked.
528
529    STACK_TRACE_DISPLAYED and DEBUGGER_ENTERED are used so that
530    those functions aren't done more than once in a single `signal'
531    session. */
532
533 static Lisp_Object
534 signal_call_debugger (Lisp_Object conditions,
535                       Lisp_Object sig, Lisp_Object data,
536                       Lisp_Object active_handlers,
537                       int signal_vars_only,
538                       int *stack_trace_displayed,
539                       int *debugger_entered)
540 {
541   /* This function can GC */
542   Lisp_Object val = Qunbound;
543   Lisp_Object all_handlers = Vcondition_handlers;
544   Lisp_Object temp_data = Qnil;
545   int speccount = specpdl_depth();
546   struct gcpro gcpro1, gcpro2;
547   GCPRO2 (all_handlers, temp_data);
548
549   Vcondition_handlers = active_handlers;
550
551   temp_data = Fcons (sig, data); /* needed for skip_debugger */
552
553   if (!entering_debugger && !*stack_trace_displayed && !signal_vars_only
554       && wants_debugger (Vstack_trace_on_error, conditions)
555       && !skip_debugger (conditions, temp_data))
556     {
557       specbind (Qdebug_on_error,        Qnil);
558       specbind (Qstack_trace_on_error,  Qnil);
559       specbind (Qdebug_on_signal,       Qnil);
560       specbind (Qstack_trace_on_signal, Qnil);
561
562       internal_with_output_to_temp_buffer (build_string ("*Backtrace*"),
563                                            backtrace_259,
564                                            Qnil,
565                                            Qnil);
566       unbind_to (speccount, Qnil);
567       *stack_trace_displayed = 1;
568     }
569
570   if (!entering_debugger && !*debugger_entered && !signal_vars_only
571       && (EQ (sig, Qquit)
572           ? debug_on_quit
573           : wants_debugger (Vdebug_on_error, conditions))
574       && !skip_debugger (conditions, temp_data))
575     {
576       debug_on_quit &= ~2;      /* reset critical bit */
577       specbind (Qdebug_on_error,        Qnil);
578       specbind (Qstack_trace_on_error,  Qnil);
579       specbind (Qdebug_on_signal,       Qnil);
580       specbind (Qstack_trace_on_signal, Qnil);
581
582       val = call_debugger (list2 (Qerror, (Fcons (sig, data))));
583       *debugger_entered = 1;
584     }
585
586   if (!entering_debugger && !*stack_trace_displayed
587       && wants_debugger (Vstack_trace_on_signal, conditions))
588     {
589       specbind (Qdebug_on_error,        Qnil);
590       specbind (Qstack_trace_on_error,  Qnil);
591       specbind (Qdebug_on_signal,       Qnil);
592       specbind (Qstack_trace_on_signal, Qnil);
593
594       internal_with_output_to_temp_buffer (build_string ("*Backtrace*"),
595                                            backtrace_259,
596                                            Qnil,
597                                            Qnil);
598       unbind_to (speccount, Qnil);
599       *stack_trace_displayed = 1;
600     }
601
602   if (!entering_debugger && !*debugger_entered
603       && (EQ (sig, Qquit)
604           ? debug_on_quit
605           : wants_debugger (Vdebug_on_signal, conditions)))
606     {
607       debug_on_quit &= ~2;      /* reset critical bit */
608       specbind (Qdebug_on_error,        Qnil);
609       specbind (Qstack_trace_on_error,  Qnil);
610       specbind (Qdebug_on_signal,       Qnil);
611       specbind (Qstack_trace_on_signal, Qnil);
612
613       val = call_debugger (list2 (Qerror, (Fcons (sig, data))));
614       *debugger_entered = 1;
615     }
616
617   UNGCPRO;
618   Vcondition_handlers = all_handlers;
619   return unbind_to (speccount, val);
620 }
621
622 \f
623 /************************************************************************/
624 /*                     The basic special forms                          */
625 /************************************************************************/
626
627 /* Except for Fprogn(), the basic special forms below are only called
628    from interpreted code.  The byte compiler turns them into bytecodes. */
629
630 DEFUN ("or", For, 0, UNEVALLED, 0, /*
631 Eval args until one of them yields non-nil, then return that value.
632 The remaining args are not evalled at all.
633 If all args return nil, return nil.
634 */
635        (args))
636 {
637   /* This function can GC */
638   REGISTER Lisp_Object arg, val;
639
640   LIST_LOOP_2 (arg, args)
641     {
642       if (!NILP (val = Feval (arg)))
643         return val;
644     }
645
646   return Qnil;
647 }
648
649 DEFUN ("and", Fand, 0, UNEVALLED, 0, /*
650 Eval args until one of them yields nil, then return nil.
651 The remaining args are not evalled at all.
652 If no arg yields nil, return the last arg's value.
653 */
654        (args))
655 {
656   /* This function can GC */
657   REGISTER Lisp_Object arg, val = Qt;
658
659   LIST_LOOP_2 (arg, args)
660     {
661       if (NILP (val = Feval (arg)))
662         return val;
663     }
664
665   return val;
666 }
667
668 DEFUN ("if", Fif, 2, UNEVALLED, 0, /*
669 \(if COND THEN ELSE...): if COND yields non-nil, do THEN, else do ELSE...
670 Returns the value of THEN or the value of the last of the ELSE's.
671 THEN must be one expression, but ELSE... can be zero or more expressions.
672 If COND yields nil, and there are no ELSE's, the value is nil.
673 */
674        (args))
675 {
676   /* This function can GC */
677   Lisp_Object condition  = XCAR (args);
678   Lisp_Object then_form  = XCAR (XCDR (args));
679   Lisp_Object else_forms = XCDR (XCDR (args));
680
681   if (!NILP (Feval (condition)))
682     return Feval (then_form);
683   else
684     return Fprogn (else_forms);
685 }
686
687 /* Macros `when' and `unless' are trivially defined in Lisp,
688    but it helps for bootstrapping to have them ALWAYS defined. */
689
690 DEFUN ("when", Fwhen, 1, MANY, 0, /*
691 \(when COND BODY...): if COND yields non-nil, do BODY, else return nil.
692 BODY can be zero or more expressions.  If BODY is nil, return nil.
693 */
694        (int nargs, Lisp_Object *args))
695 {
696   Lisp_Object cond = args[0];
697   Lisp_Object body;
698
699   switch (nargs)
700     {
701     case 1:  body = Qnil; break;
702     case 2:  body = args[1]; break;
703     default: body = Fcons (Qprogn, Flist (nargs-1, args+1)); break;
704     }
705
706   return list3 (Qif, cond, body);
707 }
708
709 DEFUN ("unless", Funless, 1, MANY, 0, /*
710 \(unless COND BODY...): if COND yields nil, do BODY, else return nil.
711 BODY can be zero or more expressions.  If BODY is nil, return nil.
712 */
713        (int nargs, Lisp_Object *args))
714 {
715   Lisp_Object cond = args[0];
716   Lisp_Object body = Flist (nargs-1, args+1);
717   return Fcons (Qif, Fcons (cond, Fcons (Qnil, body)));
718 }
719
720 DEFUN ("cond", Fcond, 0, UNEVALLED, 0, /*
721 (cond CLAUSES...): try each clause until one succeeds.
722 Each clause looks like (CONDITION BODY...).  CONDITION is evaluated
723 and, if the value is non-nil, this clause succeeds:
724 then the expressions in BODY are evaluated and the last one's
725 value is the value of the cond-form.
726 If no clause succeeds, cond returns nil.
727 If a clause has one element, as in (CONDITION),
728 CONDITION's value if non-nil is returned from the cond-form.
729 */
730        (args))
731 {
732   /* This function can GC */
733   REGISTER Lisp_Object val, clause;
734
735   LIST_LOOP_2 (clause, args)
736     {
737       CHECK_CONS (clause);
738       if (!NILP (val = Feval (XCAR (clause))))
739         {
740           if (!NILP (clause = XCDR (clause)))
741             {
742               CHECK_TRUE_LIST (clause);
743               val = Fprogn (clause);
744             }
745           return val;
746         }
747     }
748
749   return Qnil;
750 }
751
752 DEFUN ("progn", Fprogn, 0, UNEVALLED, 0, /*
753 \(progn BODY...): eval BODY forms sequentially and return value of last one.
754 */
755        (args))
756 {
757   /* This function can GC */
758   /* Caller must provide a true list in ARGS */
759   REGISTER Lisp_Object form, val = Qnil;
760   struct gcpro gcpro1;
761
762   GCPRO1 (args);
763
764   {
765     LIST_LOOP_2 (form, args)
766       val = Feval (form);
767   }
768
769   UNGCPRO;
770   return val;
771 }
772
773 /* Fprog1() is the canonical example of a function that must GCPRO a
774    Lisp_Object across calls to Feval(). */
775
776 DEFUN ("prog1", Fprog1, 1, UNEVALLED, 0, /*
777 Similar to `progn', but the value of the first form is returned.
778 \(prog1 FIRST BODY...): All the arguments are evaluated sequentially.
779 The value of FIRST is saved during evaluation of the remaining args,
780 whose values are discarded.
781 */
782        (args))
783 {
784   /* This function can GC */
785   REGISTER Lisp_Object val, form;
786   struct gcpro gcpro1;
787
788   val = Feval (XCAR (args));
789
790   GCPRO1 (val);
791
792   {
793     LIST_LOOP_2 (form, XCDR (args))
794       Feval (form);
795   }
796
797   UNGCPRO;
798   return val;
799 }
800
801 DEFUN ("prog2", Fprog2, 2, UNEVALLED, 0, /*
802 Similar to `progn', but the value of the second form is returned.
803 \(prog2 FIRST SECOND BODY...): All the arguments are evaluated sequentially.
804 The value of SECOND is saved during evaluation of the remaining args,
805 whose values are discarded.
806 */
807        (args))
808 {
809   /* This function can GC */
810   REGISTER Lisp_Object val, form, tail;
811   struct gcpro gcpro1;
812
813   Feval (XCAR (args));
814   args = XCDR (args);
815   val = Feval (XCAR (args));
816   args = XCDR (args);
817
818   GCPRO1 (val);
819
820   LIST_LOOP_3 (form, args, tail)
821     Feval (form);
822
823   UNGCPRO;
824   return val;
825 }
826
827 DEFUN ("let*", FletX, 1, UNEVALLED, 0, /*
828 \(let* VARLIST BODY...): bind variables according to VARLIST then eval BODY.
829 The value of the last form in BODY is returned.
830 Each element of VARLIST is a symbol (which is bound to nil)
831 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
832 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
833 */
834        (args))
835 {
836   /* This function can GC */
837   Lisp_Object var, tail;
838   Lisp_Object varlist = XCAR (args);
839   Lisp_Object body    = XCDR (args);
840   int speccount = specpdl_depth();
841
842   EXTERNAL_LIST_LOOP_3 (var, varlist, tail)
843     {
844       Lisp_Object symbol, value, tem;
845       if (SYMBOLP (var))
846         symbol = var, value = Qnil;
847       else
848         {
849           CHECK_CONS (var);
850           symbol = XCAR (var);
851           tem    = XCDR (var);
852           if (NILP (tem))
853             value = Qnil;
854           else
855             {
856               CHECK_CONS (tem);
857               value = Feval (XCAR (tem));
858               if (!NILP (XCDR (tem)))
859                 signal_simple_error
860                   ("`let' bindings can have only one value-form", var);
861             }
862         }
863       specbind (symbol, value);
864     }
865   return unbind_to (speccount, Fprogn (body));
866 }
867
868 DEFUN ("let", Flet, 1, UNEVALLED, 0, /*
869 \(let VARLIST BODY...): bind variables according to VARLIST then eval BODY.
870 The value of the last form in BODY is returned.
871 Each element of VARLIST is a symbol (which is bound to nil)
872 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
873 All the VALUEFORMs are evalled before any symbols are bound.
874 */
875        (args))
876 {
877   /* This function can GC */
878   Lisp_Object var, tail;
879   Lisp_Object varlist = XCAR (args);
880   Lisp_Object body    = XCDR (args);
881   int speccount = specpdl_depth();
882   Lisp_Object *temps;
883   int idx;
884   struct gcpro gcpro1;
885
886   /* Make space to hold the values to give the bound variables. */
887   {
888     int varcount;
889     GET_EXTERNAL_LIST_LENGTH (varlist, varcount);
890     temps = alloca_array (Lisp_Object, varcount);
891   }
892
893   /* Compute the values and store them in `temps' */
894   GCPRO1 (*temps);
895   gcpro1.nvars = 0;
896
897   idx = 0;
898   LIST_LOOP_3 (var, varlist, tail)
899     {
900       Lisp_Object *value = &temps[idx++];
901       if (SYMBOLP (var))
902         *value = Qnil;
903       else
904         {
905           Lisp_Object tem;
906           CHECK_CONS (var);
907           tem = XCDR (var);
908           if (NILP (tem))
909             *value = Qnil;
910           else
911             {
912               CHECK_CONS (tem);
913               *value = Feval (XCAR (tem));
914               gcpro1.nvars = idx;
915
916               if (!NILP (XCDR (tem)))
917                 signal_simple_error
918                   ("`let' bindings can have only one value-form", var);
919             }
920         }
921     }
922
923   idx = 0;
924   LIST_LOOP_3 (var, varlist, tail)
925     {
926       specbind (SYMBOLP (var) ? var : XCAR (var), temps[idx++]);
927     }
928
929   UNGCPRO;
930
931   return unbind_to (speccount, Fprogn (body));
932 }
933
934 DEFUN ("while", Fwhile, 1, UNEVALLED, 0, /*
935 \(while TEST BODY...): if TEST yields non-nil, eval BODY... and repeat.
936 The order of execution is thus TEST, BODY, TEST, BODY and so on
937 until TEST returns nil.
938 */
939        (args))
940 {
941   /* This function can GC */
942   Lisp_Object test = XCAR (args);
943   Lisp_Object body = XCDR (args);
944
945   while (!NILP (Feval (test)))
946     {
947       QUIT;
948       Fprogn (body);
949     }
950
951   return Qnil;
952 }
953
954 DEFUN ("setq", Fsetq, 0, UNEVALLED, 0, /*
955 \(setq SYM VAL SYM VAL ...): set each SYM to the value of its VAL.
956 The symbols SYM are variables; they are literal (not evaluated).
957 The values VAL are expressions; they are evaluated.
958 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
959 The second VAL is not computed until after the first SYM is set, and so on;
960 each VAL can use the new value of variables set earlier in the `setq'.
961 The return value of the `setq' form is the value of the last VAL.
962 */
963        (args))
964 {
965   /* This function can GC */
966   Lisp_Object symbol, tail, val = Qnil;
967   int nargs;
968   struct gcpro gcpro1;
969
970   GET_LIST_LENGTH (args, nargs);
971
972   if (nargs & 1)                /* Odd number of arguments? */
973     Fsignal (Qwrong_number_of_arguments, list2 (Qsetq, make_int (nargs)));
974
975   GCPRO1 (val);
976
977   PROPERTY_LIST_LOOP (tail, symbol, val, args)
978     {
979       val = Feval (val);
980       Fset (symbol, val);
981     }
982
983   UNGCPRO;
984   return val;
985 }
986
987 DEFUN ("quote", Fquote, 1, UNEVALLED, 0, /*
988 Return the argument, without evaluating it.  `(quote x)' yields `x'.
989 */
990        (args))
991 {
992   return XCAR (args);
993 }
994
995 DEFUN ("function", Ffunction, 1, UNEVALLED, 0, /*
996 Like `quote', but preferred for objects which are functions.
997 In byte compilation, `function' causes its argument to be compiled.
998 `quote' cannot do that.
999 */
1000        (args))
1001 {
1002   return XCAR (args);
1003 }
1004
1005 \f
1006 /************************************************************************/
1007 /*                      Defining functions/variables                    */
1008 /************************************************************************/
1009 static Lisp_Object
1010 define_function (Lisp_Object name, Lisp_Object defn)
1011 {
1012   Ffset (name, defn);
1013   LOADHIST_ATTACH (name);
1014   return name;
1015 }
1016
1017 DEFUN ("defun", Fdefun, 2, UNEVALLED, 0, /*
1018 \(defun NAME ARGLIST [DOCSTRING] BODY...): define NAME as a function.
1019 The definition is (lambda ARGLIST [DOCSTRING] BODY...).
1020 See also the function `interactive'.
1021 */
1022        (args))
1023 {
1024   /* This function can GC */
1025   return define_function (XCAR (args),
1026                           Fcons (Qlambda, XCDR (args)));
1027 }
1028
1029 DEFUN ("defmacro", Fdefmacro, 2, UNEVALLED, 0, /*
1030 \(defmacro NAME ARGLIST [DOCSTRING] BODY...): define NAME as a macro.
1031 The definition is (macro lambda ARGLIST [DOCSTRING] BODY...).
1032 When the macro is called, as in (NAME ARGS...),
1033 the function (lambda ARGLIST BODY...) is applied to
1034 the list ARGS... as it appears in the expression,
1035 and the result should be a form to be evaluated instead of the original.
1036 */
1037        (args))
1038 {
1039   /* This function can GC */
1040   return define_function (XCAR (args),
1041                           Fcons (Qmacro, Fcons (Qlambda, XCDR (args))));
1042 }
1043
1044 DEFUN ("defvar", Fdefvar, 1, UNEVALLED, 0, /*
1045 \(defvar SYMBOL INITVALUE DOCSTRING): define SYMBOL as a variable.
1046 You are not required to define a variable in order to use it,
1047  but the definition can supply documentation and an initial value
1048  in a way that tags can recognize.
1049
1050 INITVALUE is evaluated, and used to set SYMBOL, only if SYMBOL's value is
1051  void. (However, when you evaluate a defvar interactively, it acts like a
1052  defconst: SYMBOL's value is always set regardless of whether it's currently
1053  void.)
1054 If SYMBOL is buffer-local, its default value is what is set;
1055  buffer-local values are not affected.
1056 INITVALUE and DOCSTRING are optional.
1057 If DOCSTRING starts with *, this variable is identified as a user option.
1058  This means that M-x set-variable and M-x edit-options recognize it.
1059 If INITVALUE is missing, SYMBOL's value is not set.
1060
1061 In lisp-interaction-mode defvar is treated as defconst.
1062 */
1063        (args))
1064 {
1065   /* This function can GC */
1066   Lisp_Object sym = XCAR (args);
1067
1068   if (!NILP (args = XCDR (args)))
1069     {
1070       Lisp_Object val = XCAR (args);
1071
1072       if (NILP (Fdefault_boundp (sym)))
1073         {
1074           struct gcpro gcpro1;
1075           GCPRO1 (val);
1076           val = Feval (val);
1077           Fset_default (sym, val);
1078           UNGCPRO;
1079         }
1080
1081       if (!NILP (args = XCDR (args)))
1082         {
1083           Lisp_Object doc = XCAR (args);
1084           Fput (sym, Qvariable_documentation, doc);
1085           if (!NILP (args = XCDR (args)))
1086             error ("too many arguments");
1087         }
1088     }
1089
1090 #ifdef I18N3
1091   if (!NILP (Vfile_domain))
1092     Fput (sym, Qvariable_domain, Vfile_domain);
1093 #endif
1094
1095   LOADHIST_ATTACH (sym);
1096   return sym;
1097 }
1098
1099 DEFUN ("defconst", Fdefconst, 2, UNEVALLED, 0, /*
1100 \(defconst SYMBOL INITVALUE DOCSTRING): define SYMBOL as a constant
1101 variable.
1102 The intent is that programs do not change this value, but users may.
1103 Always sets the value of SYMBOL to the result of evalling INITVALUE.
1104 If SYMBOL is buffer-local, its default value is what is set;
1105  buffer-local values are not affected.
1106 DOCSTRING is optional.
1107 If DOCSTRING starts with *, this variable is identified as a user option.
1108  This means that M-x set-variable and M-x edit-options recognize it.
1109
1110 Note: do not use `defconst' for user options in libraries that are not
1111  normally loaded, since it is useful for users to be able to specify
1112  their own values for such variables before loading the library.
1113 Since `defconst' unconditionally assigns the variable,
1114  it would override the user's choice.
1115 */
1116        (args))
1117 {
1118   /* This function can GC */
1119   Lisp_Object sym = XCAR (args);
1120   Lisp_Object val = Feval (XCAR (args = XCDR (args)));
1121   struct gcpro gcpro1;
1122
1123   GCPRO1 (val);
1124
1125   Fset_default (sym, val);
1126
1127   UNGCPRO;
1128
1129   if (!NILP (args = XCDR (args)))
1130     {
1131       Lisp_Object doc = XCAR (args);
1132       Fput (sym, Qvariable_documentation, doc);
1133       if (!NILP (args = XCDR (args)))
1134         error ("too many arguments");
1135     }
1136
1137 #ifdef I18N3
1138   if (!NILP (Vfile_domain))
1139     Fput (sym, Qvariable_domain, Vfile_domain);
1140 #endif
1141
1142   LOADHIST_ATTACH (sym);
1143   return sym;
1144 }
1145
1146 DEFUN ("user-variable-p", Fuser_variable_p, 1, 1, 0, /*
1147 Return t if VARIABLE is intended to be set and modified by users.
1148 \(The alternative is a variable used internally in a Lisp program.)
1149 Determined by whether the first character of the documentation
1150 for the variable is `*'.
1151 */
1152        (variable))
1153 {
1154   Lisp_Object documentation = Fget (variable, Qvariable_documentation, Qnil);
1155
1156   return
1157     ((INTP (documentation) && XINT (documentation) < 0) ||
1158
1159      (STRINGP (documentation) &&
1160       (string_byte (XSTRING (documentation), 0) == '*')) ||
1161
1162      /* If (STRING . INTEGER), a negative integer means a user variable. */
1163      (CONSP (documentation)
1164       && STRINGP (XCAR (documentation))
1165       && INTP (XCDR (documentation))
1166       && XINT (XCDR (documentation)) < 0)) ?
1167     Qt : Qnil;
1168 }
1169
1170 DEFUN ("macroexpand-internal", Fmacroexpand_internal, 1, 2, 0, /*
1171 Return result of expanding macros at top level of FORM.
1172 If FORM is not a macro call, it is returned unchanged.
1173 Otherwise, the macro is expanded and the expansion is considered
1174 in place of FORM.  When a non-macro-call results, it is returned.
1175
1176 The second optional arg ENVIRONMENT species an environment of macro
1177 definitions to shadow the loaded ones for use in file byte-compilation.
1178 */
1179        (form, env))
1180 {
1181   /* This function can GC */
1182   /* With cleanups from Hallvard Furuseth.  */
1183   REGISTER Lisp_Object expander, sym, def, tem;
1184
1185   while (1)
1186     {
1187       /* Come back here each time we expand a macro call,
1188          in case it expands into another macro call.  */
1189       if (!CONSP (form))
1190         break;
1191       /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1192       def = sym = XCAR (form);
1193       tem = Qnil;
1194       /* Trace symbols aliases to other symbols
1195          until we get a symbol that is not an alias.  */
1196       while (SYMBOLP (def))
1197         {
1198           QUIT;
1199           sym = def;
1200           tem = Fassq (sym, env);
1201           if (NILP (tem))
1202             {
1203               def = XSYMBOL (sym)->function;
1204               if (!UNBOUNDP (def))
1205                 continue;
1206             }
1207           break;
1208         }
1209       /* Right now TEM is the result from SYM in ENV,
1210          and if TEM is nil then DEF is SYM's function definition.  */
1211       if (NILP (tem))
1212         {
1213           /* SYM is not mentioned in ENV.
1214              Look at its function definition.  */
1215           if (UNBOUNDP (def)
1216               || !CONSP (def))
1217             /* Not defined or definition not suitable */
1218             break;
1219           if (EQ (XCAR (def), Qautoload))
1220             {
1221               /* Autoloading function: will it be a macro when loaded?  */
1222               tem = Felt (def, make_int (4));
1223               if (EQ (tem, Qt) || EQ (tem, Qmacro))
1224                 {
1225                   /* Yes, load it and try again.  */
1226                   do_autoload (def, sym);
1227                   continue;
1228                 }
1229               else
1230                 break;
1231             }
1232           else if (!EQ (XCAR (def), Qmacro))
1233             break;
1234           else expander = XCDR (def);
1235         }
1236       else
1237         {
1238           expander = XCDR (tem);
1239           if (NILP (expander))
1240             break;
1241         }
1242       form = apply1 (expander, XCDR (form));
1243     }
1244   return form;
1245 }
1246
1247 \f
1248 /************************************************************************/
1249 /*                          Non-local exits                             */
1250 /************************************************************************/
1251
1252 DEFUN ("catch", Fcatch, 1, UNEVALLED, 0, /*
1253 \(catch TAG BODY...): eval BODY allowing nonlocal exits using `throw'.
1254 TAG is evalled to get the tag to use.  Then the BODY is executed.
1255 Within BODY, (throw TAG) with same tag exits BODY and exits this `catch'.
1256 If no throw happens, `catch' returns the value of the last BODY form.
1257 If a throw happens, it specifies the value to return from `catch'.
1258 */
1259        (args))
1260 {
1261   /* This function can GC */
1262   Lisp_Object tag  = Feval (XCAR (args));
1263   Lisp_Object body = XCDR (args);
1264   return internal_catch (tag, Fprogn, body, 0);
1265 }
1266
1267 /* Set up a catch, then call C function FUNC on argument ARG.
1268    FUNC should return a Lisp_Object.
1269    This is how catches are done from within C code. */
1270
1271 Lisp_Object
1272 internal_catch (Lisp_Object tag,
1273                 Lisp_Object (*func) (Lisp_Object arg),
1274                 Lisp_Object arg,
1275                 int * volatile threw)
1276 {
1277   /* This structure is made part of the chain `catchlist'.  */
1278   struct catchtag c;
1279
1280   /* Fill in the components of c, and put it on the list.  */
1281   c.next = catchlist;
1282   c.tag = tag;
1283   c.val = Qnil;
1284   c.backlist = backtrace_list;
1285 #if 0 /* FSFmacs */
1286   /* #### */
1287   c.handlerlist = handlerlist;
1288 #endif
1289   c.lisp_eval_depth = lisp_eval_depth;
1290   c.pdlcount = specpdl_depth();
1291 #if 0 /* FSFmacs */
1292   c.poll_suppress_count = async_timer_suppress_count;
1293 #endif
1294   c.gcpro = gcprolist;
1295   catchlist = &c;
1296
1297   /* Call FUNC.  */
1298   if (SETJMP (c.jmp))
1299     {
1300       /* Throw works by a longjmp that comes right here.  */
1301       if (threw) *threw = 1;
1302       return c.val;
1303     }
1304   c.val = (*func) (arg);
1305   if (threw) *threw = 0;
1306   catchlist = c.next;
1307   return c.val;
1308 }
1309
1310
1311 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1312    jump to that CATCH, returning VALUE as the value of that catch.
1313
1314    This is the guts Fthrow and Fsignal; they differ only in the way
1315    they choose the catch tag to throw to.  A catch tag for a
1316    condition-case form has a TAG of Qnil.
1317
1318    Before each catch is discarded, unbind all special bindings and
1319    execute all unwind-protect clauses made above that catch.  Unwind
1320    the handler stack as we go, so that the proper handlers are in
1321    effect for each unwind-protect clause we run.  At the end, restore
1322    some static info saved in CATCH, and longjmp to the location
1323    specified in the
1324
1325    This is used for correct unwinding in Fthrow and Fsignal.  */
1326
1327 static void
1328 unwind_to_catch (struct catchtag *c, Lisp_Object val)
1329 {
1330 #if 0 /* FSFmacs */
1331   /* #### */
1332   REGISTER int last_time;
1333 #endif
1334
1335   /* Unwind the specbind, catch, and handler stacks back to CATCH
1336      Before each catch is discarded, unbind all special bindings
1337      and execute all unwind-protect clauses made above that catch.
1338      At the end, restore some static info saved in CATCH,
1339      and longjmp to the location specified.
1340      */
1341
1342   /* Save the value somewhere it will be GC'ed.
1343      (Can't overwrite tag slot because an unwind-protect may
1344      want to throw to this same tag, which isn't yet invalid.) */
1345   c->val = val;
1346
1347 #if 0 /* FSFmacs */
1348   /* Restore the polling-suppression count.  */
1349   set_poll_suppress_count (catch->poll_suppress_count);
1350 #endif
1351
1352 #if 0 /* FSFmacs */
1353   /* #### FSFmacs has the following loop.  Is it more correct? */
1354   do
1355     {
1356       last_time = catchlist == c;
1357
1358       /* Unwind the specpdl stack, and then restore the proper set of
1359          handlers.  */
1360       unbind_to (catchlist->pdlcount, Qnil);
1361       handlerlist = catchlist->handlerlist;
1362       catchlist = catchlist->next;
1363     }
1364   while (! last_time);
1365 #else /* Actual XEmacs code */
1366   /* Unwind the specpdl stack */
1367   unbind_to (c->pdlcount, Qnil);
1368   catchlist = c->next;
1369 #endif
1370
1371   gcprolist = c->gcpro;
1372   backtrace_list = c->backlist;
1373   lisp_eval_depth = c->lisp_eval_depth;
1374
1375 #if 0 /* no longer used */
1376   throw_level = 0;
1377 #endif
1378   LONGJMP (c->jmp, 1);
1379 }
1380
1381 static DOESNT_RETURN
1382 throw_or_bomb_out (Lisp_Object tag, Lisp_Object val, int bomb_out_p,
1383                    Lisp_Object sig, Lisp_Object data)
1384 {
1385 #if 0
1386   /* die if we recurse more than is reasonable */
1387   if (++throw_level > 20)
1388     abort();
1389 #endif
1390
1391   /* If bomb_out_p is t, this is being called from Fsignal as a
1392      "last resort" when there is no handler for this error and
1393       the debugger couldn't be invoked, so we are throwing to
1394      'top-level.  If this tag doesn't exist (happens during the
1395      initialization stages) we would get in an infinite recursive
1396      Fsignal/Fthrow loop, so instead we bomb out to the
1397      really-early-error-handler.
1398
1399      Note that in fact the only time that the "last resort"
1400      occurs is when there's no catch for 'top-level -- the
1401      'top-level catch and the catch-all error handler are
1402      established at the same time, in initial_command_loop/
1403      top_level_1.
1404
1405      #### Fix this horrifitude!
1406      */
1407
1408   while (1)
1409     {
1410       REGISTER struct catchtag *c;
1411
1412 #if 0 /* FSFmacs */
1413       if (!NILP (tag)) /* #### */
1414 #endif
1415       for (c = catchlist; c; c = c->next)
1416         {
1417           if (EQ (c->tag, tag))
1418             unwind_to_catch (c, val);
1419         }
1420       if (!bomb_out_p)
1421         tag = Fsignal (Qno_catch, list2 (tag, val));
1422       else
1423         call1 (Qreally_early_error_handler, Fcons (sig, data));
1424     }
1425
1426   /* can't happen.  who cares? - (Sun's compiler does) */
1427   /* throw_level--; */
1428   /* getting tired of compilation warnings */
1429   /* return Qnil; */
1430 }
1431
1432 /* See above, where CATCHLIST is defined, for a description of how
1433    Fthrow() works.
1434
1435    Fthrow() is also called by Fsignal(), to do a non-local jump
1436    back to the appropriate condition-case handler after (maybe)
1437    the debugger is entered.  In that case, TAG is the value
1438    of Vcondition_handlers that was in place just after the
1439    condition-case handler was set up.  The car of this will be
1440    some data referring to the handler: Its car will be Qunbound
1441    (thus, this tag can never be generated by Lisp code), and
1442    its CDR will be the HANDLERS argument to condition_case_1()
1443    (either Qerror, Qt, or a list of handlers as in `condition-case').
1444    This works fine because Fthrow() does not care what TAG was
1445    passed to it: it just looks up the catch list for something
1446    that is EQ() to TAG.  When it finds it, it will longjmp()
1447    back to the place that established the catch (in this case,
1448    condition_case_1).  See below for more info.
1449 */
1450
1451 DEFUN ("throw", Fthrow, 2, 2, 0, /*
1452 \(throw TAG VALUE): throw to the catch for TAG and return VALUE from it.
1453 Both TAG and VALUE are evalled.
1454 */
1455        (tag, val))
1456 {
1457   throw_or_bomb_out (tag, val, 0, Qnil, Qnil); /* Doesn't return */
1458   return Qnil;
1459 }
1460
1461 DEFUN ("unwind-protect", Funwind_protect, 1, UNEVALLED, 0, /*
1462 Do BODYFORM, protecting with UNWINDFORMS.
1463 Usage looks like (unwind-protect BODYFORM UNWINDFORMS...).
1464 If BODYFORM completes normally, its value is returned
1465 after executing the UNWINDFORMS.
1466 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1467 */
1468        (args))
1469 {
1470   /* This function can GC */
1471   int speccount = specpdl_depth();
1472
1473   record_unwind_protect (Fprogn, XCDR (args));
1474   return unbind_to (speccount, Feval (XCAR (args)));
1475 }
1476
1477 \f
1478 /************************************************************************/
1479 /*                    Signalling and trapping errors                    */
1480 /************************************************************************/
1481
1482 static Lisp_Object
1483 condition_bind_unwind (Lisp_Object loser)
1484 {
1485   Lisp_Cons *victim;
1486   /* ((handler-fun . handler-args) ... other handlers) */
1487   Lisp_Object tem = XCAR (loser);
1488
1489   while (CONSP (tem))
1490     {
1491       victim = XCONS (tem);
1492       tem = victim->cdr;
1493       free_cons (victim);
1494     }
1495   victim = XCONS (loser);
1496
1497   if (EQ (loser, Vcondition_handlers)) /* may have been rebound to some tail */
1498     Vcondition_handlers = victim->cdr;
1499
1500   free_cons (victim);
1501   return Qnil;
1502 }
1503
1504 static Lisp_Object
1505 condition_case_unwind (Lisp_Object loser)
1506 {
1507   Lisp_Cons *victim;
1508
1509   /* ((<unbound> . clauses) ... other handlers */
1510   victim = XCONS (XCAR (loser));
1511   free_cons (victim);
1512
1513   victim = XCONS (loser);
1514   if (EQ (loser, Vcondition_handlers)) /* may have been rebound to some tail */
1515     Vcondition_handlers = victim->cdr;
1516
1517   free_cons (victim);
1518   return Qnil;
1519 }
1520
1521 /* Split out from condition_case_3 so that primitive C callers
1522    don't have to cons up a lisp handler form to be evaluated. */
1523
1524 /* Call a function BFUN of one argument BARG, trapping errors as
1525    specified by HANDLERS.  If no error occurs that is indicated by
1526    HANDLERS as something to be caught, the return value of this
1527    function is the return value from BFUN.  If such an error does
1528    occur, HFUN is called, and its return value becomes the
1529    return value of condition_case_1().  The second argument passed
1530    to HFUN will always be HARG.  The first argument depends on
1531    HANDLERS:
1532
1533    If HANDLERS is Qt, all errors (this includes QUIT, but not
1534    non-local exits with `throw') cause HFUN to be invoked, and VAL
1535    (the first argument to HFUN) is a cons (SIG . DATA) of the
1536    arguments passed to `signal'.  The debugger is not invoked even if
1537    `debug-on-error' was set.
1538
1539    A HANDLERS value of Qerror is the same as Qt except that the
1540    debugger is invoked if `debug-on-error' was set.
1541
1542    Otherwise, HANDLERS should be a list of lists (CONDITION-NAME BODY ...)
1543    exactly as in `condition-case', and errors will be trapped
1544    as indicated in HANDLERS.  VAL (the first argument to HFUN) will
1545    be a cons whose car is the cons (SIG . DATA) and whose CDR is the
1546    list (BODY ...) from the appropriate slot in HANDLERS.
1547
1548    This function pushes HANDLERS onto the front of Vcondition_handlers
1549    (actually with a Qunbound marker as well -- see Fthrow() above
1550    for why), establishes a catch whose tag is this new value of
1551    Vcondition_handlers, and calls BFUN.  When Fsignal() is called,
1552    it calls Fthrow(), setting TAG to this same new value of
1553    Vcondition_handlers and setting VAL to the same thing that will
1554    be passed to HFUN, as above.  Fthrow() longjmp()s back to the
1555    jump point we just established, and we in turn just call the
1556    HFUN and return its value.
1557
1558    For a real condition-case, HFUN will always be
1559    run_condition_case_handlers() and HARG is the argument VAR
1560    to condition-case.  That function just binds VAR to the cons
1561    (SIG . DATA) that is the CAR of VAL, and calls the handler
1562    (BODY ...) that is the CDR of VAL.  Note that before calling
1563    Fthrow(), Fsignal() restored Vcondition_handlers to the value
1564    it had *before* condition_case_1() was called.  This maintains
1565    consistency (so that the state of things at exit of
1566    condition_case_1() is the same as at entry), and implies
1567    that the handler can signal the same error again (possibly
1568    after processing of its own), without getting in an infinite
1569    loop. */
1570
1571 Lisp_Object
1572 condition_case_1 (Lisp_Object handlers,
1573                   Lisp_Object (*bfun) (Lisp_Object barg),
1574                   Lisp_Object barg,
1575                   Lisp_Object (*hfun) (Lisp_Object val, Lisp_Object harg),
1576                   Lisp_Object harg)
1577 {
1578   int speccount = specpdl_depth();
1579   struct catchtag c;
1580   struct gcpro gcpro1;
1581
1582 #if 0 /* FSFmacs */
1583   c.tag = Qnil;
1584 #else
1585   /* Do consing now so out-of-memory error happens up front */
1586   /* (unbound . stuff) is a special condition-case kludge marker
1587      which is known specially by Fsignal.
1588      This is an abomination, but to fix it would require either
1589      making condition_case cons (a union of the conditions of the clauses)
1590      or changing the byte-compiler output (no thanks). */
1591   c.tag = noseeum_cons (noseeum_cons (Qunbound, handlers),
1592                         Vcondition_handlers);
1593 #endif
1594   c.val = Qnil;
1595   c.backlist = backtrace_list;
1596 #if 0 /* FSFmacs */
1597   /* #### */
1598   c.handlerlist = handlerlist;
1599 #endif
1600   c.lisp_eval_depth = lisp_eval_depth;
1601   c.pdlcount = specpdl_depth();
1602 #if 0 /* FSFmacs */
1603   c.poll_suppress_count = async_timer_suppress_count;
1604 #endif
1605   c.gcpro = gcprolist;
1606   /* #### FSFmacs does the following statement *after* the setjmp(). */
1607   c.next = catchlist;
1608
1609   if (SETJMP (c.jmp))
1610     {
1611       /* throw does ungcpro, etc */
1612       return (*hfun) (c.val, harg);
1613     }
1614
1615   record_unwind_protect (condition_case_unwind, c.tag);
1616
1617   catchlist = &c;
1618 #if 0 /* FSFmacs */
1619   h.handler = handlers;
1620   h.var = Qnil;
1621   h.next = handlerlist;
1622   h.tag = &c;
1623   handlerlist = &h;
1624 #else
1625   Vcondition_handlers = c.tag;
1626 #endif
1627   GCPRO1 (harg);                /* Somebody has to gc-protect */
1628
1629   c.val = ((*bfun) (barg));
1630
1631   /* The following is *not* true: (ben)
1632
1633      ungcpro, restoring catchlist and condition_handlers are actually
1634      redundant since unbind_to now restores them.  But it looks funny not to
1635      have this code here, and it doesn't cost anything, so I'm leaving it.*/
1636   UNGCPRO;
1637   catchlist = c.next;
1638   Vcondition_handlers = XCDR (c.tag);
1639
1640   return unbind_to (speccount, c.val);
1641 }
1642
1643 static Lisp_Object
1644 run_condition_case_handlers (Lisp_Object val, Lisp_Object var)
1645 {
1646   /* This function can GC */
1647 #if 0 /* FSFmacs */
1648   if (!NILP (h.var))
1649     specbind (h.var, c.val);
1650   val = Fprogn (Fcdr (h.chosen_clause));
1651
1652   /* Note that this just undoes the binding of h.var; whoever
1653      longjmp()ed to us unwound the stack to c.pdlcount before
1654      throwing. */
1655   unbind_to (c.pdlcount, Qnil);
1656   return val;
1657 #else
1658   int speccount;
1659
1660   CHECK_TRUE_LIST (val);
1661   if (NILP (var))
1662     return Fprogn (Fcdr (val)); /* tail call */
1663
1664   speccount = specpdl_depth();
1665   specbind (var, Fcar (val));
1666   val = Fprogn (Fcdr (val));
1667   return unbind_to (speccount, val);
1668 #endif
1669 }
1670
1671 /* Here for bytecode to call non-consfully.  This is exactly like
1672    condition-case except that it takes three arguments rather
1673    than a single list of arguments. */
1674 Lisp_Object
1675 condition_case_3 (Lisp_Object bodyform, Lisp_Object var, Lisp_Object handlers)
1676 {
1677   /* This function can GC */
1678   Lisp_Object handler;
1679
1680   EXTERNAL_LIST_LOOP_2 (handler, handlers)
1681     {
1682       if (NILP (handler))
1683         ;
1684       else if (CONSP (handler))
1685         {
1686           Lisp_Object conditions = XCAR (handler);
1687           /* CONDITIONS must a condition name or a list of condition names */
1688           if (SYMBOLP (conditions))
1689             ;
1690           else
1691             {
1692               Lisp_Object condition;
1693               EXTERNAL_LIST_LOOP_2 (condition, conditions)
1694                 if (!SYMBOLP (condition))
1695                   goto invalid_condition_handler;
1696             }
1697         }
1698       else
1699         {
1700         invalid_condition_handler:
1701           signal_simple_error ("Invalid condition handler", handler);
1702         }
1703     }
1704
1705   CHECK_SYMBOL (var);
1706
1707   return condition_case_1 (handlers,
1708                            Feval, bodyform,
1709                            run_condition_case_handlers,
1710                            var);
1711 }
1712
1713 DEFUN ("condition-case", Fcondition_case, 2, UNEVALLED, 0, /*
1714 Regain control when an error is signalled.
1715 Usage looks like (condition-case VAR BODYFORM HANDLERS...).
1716 Executes BODYFORM and returns its value if no error happens.
1717 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1718 where the BODY is made of Lisp expressions.
1719
1720 A handler is applicable to an error if CONDITION-NAME is one of the
1721 error's condition names.  If an error happens, the first applicable
1722 handler is run.  As a special case, a CONDITION-NAME of t matches
1723 all errors, even those without the `error' condition name on them
1724 \(e.g. `quit').
1725
1726 The car of a handler may be a list of condition names
1727 instead of a single condition name.
1728
1729 When a handler handles an error,
1730 control returns to the condition-case and the handler BODY... is executed
1731 with VAR bound to (SIGNALED-CONDITIONS . SIGNAL-DATA).
1732 VAR may be nil; then you do not get access to the signal information.
1733
1734 The value of the last BODY form is returned from the condition-case.
1735 See also the function `signal' for more info.
1736
1737 Note that at the time the condition handler is invoked, the Lisp stack
1738 and the current catches, condition-cases, and bindings have all been
1739 popped back to the state they were in just before the call to
1740 `condition-case'.  This means that resignalling the error from
1741 within the handler will not result in an infinite loop.
1742
1743 If you want to establish an error handler that is called with the
1744 Lisp stack, bindings, etc. as they were when `signal' was called,
1745 rather than when the handler was set, use `call-with-condition-handler'.
1746 */
1747      (args))
1748 {
1749   /* This function can GC */
1750   Lisp_Object var = XCAR (args);
1751   Lisp_Object bodyform = XCAR (XCDR (args));
1752   Lisp_Object handlers = XCDR (XCDR (args));
1753   return condition_case_3 (bodyform, var, handlers);
1754 }
1755
1756 DEFUN ("call-with-condition-handler", Fcall_with_condition_handler, 2, MANY, 0, /*
1757 Regain control when an error is signalled, without popping the stack.
1758 Usage looks like (call-with-condition-handler HANDLER FUNCTION &rest ARGS).
1759 This function is similar to `condition-case', but the handler is invoked
1760 with the same environment (Lisp stack, bindings, catches, condition-cases)
1761 that was current when `signal' was called, rather than when the handler
1762 was established.
1763
1764 HANDLER should be a function of one argument, which is a cons of the args
1765 \(SIG . DATA) that were passed to `signal'.  It is invoked whenever
1766 `signal' is called (this differs from `condition-case', which allows
1767 you to specify which errors are trapped).  If the handler function
1768 returns, `signal' continues as if the handler were never invoked.
1769 \(It continues to look for handlers established earlier than this one,
1770 and invokes the standard error-handler if none is found.)
1771 */
1772        (int nargs, Lisp_Object *args)) /* Note!  Args side-effected! */
1773 {
1774   /* This function can GC */
1775   int speccount = specpdl_depth();
1776   Lisp_Object tem;
1777
1778   /* #### If there were a way to check that args[0] were a function
1779      which accepted one arg, that should be done here ... */
1780
1781   /* (handler-fun . handler-args) */
1782   tem = noseeum_cons (list1 (args[0]), Vcondition_handlers);
1783   record_unwind_protect (condition_bind_unwind, tem);
1784   Vcondition_handlers = tem;
1785
1786   /* Caller should have GC-protected args */
1787   return unbind_to (speccount, Ffuncall (nargs - 1, args + 1));
1788 }
1789
1790 static int
1791 condition_type_p (Lisp_Object type, Lisp_Object conditions)
1792 {
1793   if (EQ (type, Qt))
1794     /* (condition-case c # (t c)) catches -all- signals
1795      *   Use with caution! */
1796     return 1;
1797
1798   if (SYMBOLP (type))
1799     return !NILP (Fmemq (type, conditions));
1800
1801   for (; CONSP (type); type = XCDR (type))
1802     if (!NILP (Fmemq (XCAR (type), conditions)))
1803       return 1;
1804
1805   return 0;
1806 }
1807
1808 static Lisp_Object
1809 return_from_signal (Lisp_Object value)
1810 {
1811 #if 1
1812   /* Most callers are not prepared to handle gc if this
1813      returns.  So, since this feature is not very useful,
1814      take it out.  */
1815   /* Have called debugger; return value to signaller  */
1816   return value;
1817 #else  /* But the reality is that that stinks, because: */
1818   /* GACK!!! Really want some way for debug-on-quit errors
1819      to be continuable!! */
1820   error ("Returning a value from an error is no longer supported");
1821 #endif
1822 }
1823
1824 extern int in_display;
1825
1826 \f
1827 /************************************************************************/
1828 /*               the workhorse error-signaling function                 */
1829 /************************************************************************/
1830
1831 /* #### This function has not been synched with FSF.  It diverges
1832    significantly. */
1833
1834 static Lisp_Object
1835 signal_1 (Lisp_Object sig, Lisp_Object data)
1836 {
1837   /* This function can GC */
1838   struct gcpro gcpro1, gcpro2;
1839   Lisp_Object conditions;
1840   Lisp_Object handlers;
1841   /* signal_call_debugger() could get called more than once
1842      (once when a call-with-condition-handler is about to
1843      be dealt with, and another when a condition-case handler
1844      is about to be invoked).  So make sure the debugger and/or
1845      stack trace aren't done more than once. */
1846   int stack_trace_displayed = 0;
1847   int debugger_entered = 0;
1848   GCPRO2 (conditions, handlers);
1849
1850   if (!initialized)
1851     {
1852       /* who knows how much has been initialized?  Safest bet is
1853          just to bomb out immediately. */
1854       fprintf (stderr, "Error before initialization is complete!\n");
1855       abort ();
1856     }
1857
1858   if (gc_in_progress || in_display)
1859     /* This is one of many reasons why you can't run lisp code from redisplay.
1860        There is no sensible way to handle errors there. */
1861     abort ();
1862
1863   conditions = Fget (sig, Qerror_conditions, Qnil);
1864
1865   for (handlers = Vcondition_handlers;
1866        CONSP (handlers);
1867        handlers = XCDR (handlers))
1868     {
1869       Lisp_Object handler_fun = XCAR (XCAR (handlers));
1870       Lisp_Object handler_data = XCDR (XCAR (handlers));
1871       Lisp_Object outer_handlers = XCDR (handlers);
1872
1873       if (!UNBOUNDP (handler_fun))
1874         {
1875           /* call-with-condition-handler */
1876           Lisp_Object tem;
1877           Lisp_Object all_handlers = Vcondition_handlers;
1878           struct gcpro ngcpro1;
1879           NGCPRO1 (all_handlers);
1880           Vcondition_handlers = outer_handlers;
1881
1882           tem = signal_call_debugger (conditions, sig, data,
1883                                       outer_handlers, 1,
1884                                       &stack_trace_displayed,
1885                                       &debugger_entered);
1886           if (!UNBOUNDP (tem))
1887             RETURN_NUNGCPRO (return_from_signal (tem));
1888
1889           tem = Fcons (sig, data);
1890           if (NILP (handler_data))
1891             tem = call1 (handler_fun, tem);
1892           else
1893             {
1894               /* (This code won't be used (for now?).) */
1895               struct gcpro nngcpro1;
1896               Lisp_Object args[3];
1897               NNGCPRO1 (args[0]);
1898               nngcpro1.nvars = 3;
1899               args[0] = handler_fun;
1900               args[1] = tem;
1901               args[2] = handler_data;
1902               nngcpro1.var = args;
1903               tem = Fapply (3, args);
1904               NNUNGCPRO;
1905             }
1906           NUNGCPRO;
1907 #if 0
1908           if (!EQ (tem, Qsignal))
1909             return return_from_signal (tem);
1910 #endif
1911           /* If handler didn't throw, try another handler */
1912           Vcondition_handlers = all_handlers;
1913         }
1914
1915       /* It's a condition-case handler */
1916
1917       /* t is used by handlers for all conditions, set up by C code.
1918        *  debugger is not called even if debug_on_error */
1919       else if (EQ (handler_data, Qt))
1920         {
1921           UNGCPRO;
1922           return Fthrow (handlers, Fcons (sig, data));
1923         }
1924       /* `error' is used similarly to the way `t' is used, but in
1925          addition it invokes the debugger if debug_on_error.
1926          This is normally used for the outer command-loop error
1927          handler. */
1928       else if (EQ (handler_data, Qerror))
1929         {
1930           Lisp_Object tem = signal_call_debugger (conditions, sig, data,
1931                                                   outer_handlers, 0,
1932                                                   &stack_trace_displayed,
1933                                                   &debugger_entered);
1934
1935           UNGCPRO;
1936           if (!UNBOUNDP (tem))
1937             return return_from_signal (tem);
1938
1939           tem = Fcons (sig, data);
1940           return Fthrow (handlers, tem);
1941         }
1942       else
1943         {
1944           /* handler established by real (Lisp) condition-case */
1945           Lisp_Object h;
1946
1947           for (h = handler_data; CONSP (h); h = Fcdr (h))
1948             {
1949               Lisp_Object clause = Fcar (h);
1950               Lisp_Object tem = Fcar (clause);
1951
1952               if (condition_type_p (tem, conditions))
1953                 {
1954                   tem = signal_call_debugger (conditions, sig, data,
1955                                               outer_handlers, 1,
1956                                               &stack_trace_displayed,
1957                                               &debugger_entered);
1958                   UNGCPRO;
1959                   if (!UNBOUNDP (tem))
1960                     return return_from_signal (tem);
1961
1962                   /* Doesn't return */
1963                   tem = Fcons (Fcons (sig, data), Fcdr (clause));
1964                   return Fthrow (handlers, tem);
1965                 }
1966             }
1967         }
1968     }
1969
1970   /* If no handler is present now, try to run the debugger,
1971      and if that fails, throw to top level.
1972
1973      #### The only time that no handler is present is during
1974      temacs or perhaps very early in XEmacs.  In both cases,
1975      there is no 'top-level catch. (That's why the
1976      "bomb-out" hack was added.)
1977
1978      #### Fix this horrifitude!
1979      */
1980   signal_call_debugger (conditions, sig, data, Qnil, 0,
1981                         &stack_trace_displayed,
1982                         &debugger_entered);
1983   UNGCPRO;
1984   throw_or_bomb_out (Qtop_level, Qt, 1, sig, data); /* Doesn't return */
1985   return Qnil;
1986 }
1987
1988 \f
1989 /****************** Error functions class 1 ******************/
1990
1991 /* Class 1: General functions that signal an error.
1992    These functions take an error type and a list of associated error
1993    data. */
1994
1995 /* The simplest external error function: it would be called
1996    signal_continuable_error() in the terminology below, but it's
1997    Lisp-callable. */
1998
1999 DEFUN ("signal", Fsignal, 2, 2, 0, /*
2000 Signal a continuable error.  Args are ERROR-SYMBOL, and associated DATA.
2001 An error symbol is a symbol defined using `define-error'.
2002 DATA should be a list.  Its elements are printed as part of the error message.
2003 If the signal is handled, DATA is made available to the handler.
2004 See also the function `signal-error', and the functions to handle errors:
2005 `condition-case' and `call-with-condition-handler'.
2006
2007 Note that this function can return, if the debugger is invoked and the
2008 user invokes the "return from signal" option.
2009 */
2010        (error_symbol, data))
2011 {
2012   /* Fsignal() is one of these functions that's called all the time
2013      with newly-created Lisp objects.  We allow this; but we must GC-
2014      protect the objects because all sorts of weird stuff could
2015      happen. */
2016
2017   struct gcpro gcpro1;
2018
2019   GCPRO1 (data);
2020   if (!NILP (Vcurrent_error_state))
2021     {
2022       if (!NILP (Vcurrent_warning_class))
2023         warn_when_safe_lispobj (Vcurrent_warning_class, Qwarning,
2024                                 Fcons (error_symbol, data));
2025       Fthrow (Qunbound_suspended_errors_tag, Qnil);
2026       abort (); /* Better not get here! */
2027     }
2028   RETURN_UNGCPRO (signal_1 (error_symbol, data));
2029 }
2030
2031 /* Signal a non-continuable error. */
2032
2033 DOESNT_RETURN
2034 signal_error (Lisp_Object sig, Lisp_Object data)
2035 {
2036   for (;;)
2037     Fsignal (sig, data);
2038 }
2039
2040 static Lisp_Object
2041 call_with_suspended_errors_1 (Lisp_Object opaque_arg)
2042 {
2043   Lisp_Object val;
2044   Lisp_Object *kludgy_args = (Lisp_Object *) get_opaque_ptr (opaque_arg);
2045   PRIMITIVE_FUNCALL (val, get_opaque_ptr (kludgy_args[0]),
2046                      kludgy_args + 2, XINT (kludgy_args[1]));
2047   return val;
2048 }
2049
2050 static Lisp_Object
2051 restore_current_warning_class (Lisp_Object warning_class)
2052 {
2053   Vcurrent_warning_class = warning_class;
2054   return Qnil;
2055 }
2056
2057 static Lisp_Object
2058 restore_current_error_state (Lisp_Object error_state)
2059 {
2060   Vcurrent_error_state = error_state;
2061   return Qnil;
2062 }
2063
2064 /* Many functions would like to do one of three things if an error
2065    occurs:
2066
2067    (1) signal the error, as usual.
2068    (2) silently fail and return some error value.
2069    (3) do as (2) but issue a warning in the process.
2070
2071    Currently there's lots of stuff that passes an Error_behavior
2072    value and calls maybe_signal_error() and other such functions.
2073    This approach is inherently error-prone and broken.  A much
2074    more robust and easier approach is to use call_with_suspended_errors().
2075    Wrap this around any function in which you might want errors
2076    to not be errors.
2077 */
2078
2079 Lisp_Object
2080 call_with_suspended_errors (lisp_fn_t fun, volatile Lisp_Object retval,
2081                             Lisp_Object class, Error_behavior errb,
2082                             int nargs, ...)
2083 {
2084   va_list vargs;
2085   int speccount;
2086   Lisp_Object kludgy_args[22];
2087   Lisp_Object *args = kludgy_args + 2;
2088   int i;
2089   Lisp_Object no_error;
2090
2091   assert (SYMBOLP (class)); /* sanity-check */
2092   assert (!NILP (class));
2093   assert (nargs >= 0 && nargs < 20);
2094
2095   /* ERROR_ME means don't trap errors. (However, if errors are
2096      already trapped, we leave them trapped.)
2097
2098      Otherwise, we trap errors, and trap warnings if ERROR_ME_WARN.
2099
2100      If ERROR_ME_NOT, it causes no warnings even if warnings
2101      were previously enabled.  However, we never change the
2102      warning class from one to another. */
2103   if (!ERRB_EQ (errb, ERROR_ME))
2104     {
2105       if (ERRB_EQ (errb, ERROR_ME_NOT)) /* person wants no warnings */
2106         class = Qnil;
2107       errb = ERROR_ME_NOT;
2108       no_error = Qt;
2109     }
2110   else
2111     no_error = Qnil;
2112
2113   va_start (vargs, nargs);
2114   for (i = 0; i < nargs; i++)
2115     args[i] = va_arg (vargs, Lisp_Object);
2116   va_end (vargs);
2117
2118   /* If error-checking is not disabled, just call the function.
2119      It's important not to override disabled error-checking with
2120      enabled error-checking. */
2121
2122   if (ERRB_EQ (errb, ERROR_ME))
2123     {
2124       Lisp_Object val;
2125       PRIMITIVE_FUNCALL (val, fun, args, nargs);
2126       return val;
2127     }
2128
2129   speccount = specpdl_depth();
2130   if (NILP (class) || NILP (Vcurrent_warning_class))
2131     {
2132       /* If we're currently calling for no warnings, then make it so.
2133          If we're currently calling for warnings and we weren't
2134          previously, then set our warning class; otherwise, leave
2135          the existing one alone. */
2136       record_unwind_protect (restore_current_warning_class,
2137                              Vcurrent_warning_class);
2138       Vcurrent_warning_class = class;
2139     }
2140   if (!EQ (Vcurrent_error_state, no_error))
2141     {
2142       record_unwind_protect (restore_current_error_state,
2143                              Vcurrent_error_state);
2144       Vcurrent_error_state = no_error;
2145     }
2146
2147   {
2148     int threw;
2149     Lisp_Object the_retval;
2150     Lisp_Object opaque1 = make_opaque_ptr (kludgy_args);
2151     Lisp_Object opaque2 = make_opaque_ptr ((void *) fun);
2152     struct gcpro gcpro1, gcpro2;
2153
2154     GCPRO2 (opaque1, opaque2);
2155     kludgy_args[0] = opaque2;
2156     kludgy_args[1] = make_int (nargs);
2157     the_retval = internal_catch (Qunbound_suspended_errors_tag,
2158                                  call_with_suspended_errors_1,
2159                                  opaque1, &threw);
2160     free_opaque_ptr (opaque1);
2161     free_opaque_ptr (opaque2);
2162     UNGCPRO;
2163     /* Use the returned value except in non-local exit, when
2164        RETVAL applies. */
2165     /* Some perverse compilers require the perverse cast below.  */
2166     return unbind_to (speccount,
2167                       threw ? *((Lisp_Object*) &(retval)) : the_retval);
2168   }
2169 }
2170
2171 /* Signal a non-continuable error or display a warning or do nothing,
2172    according to ERRB.  CLASS is the class of warning and should
2173    refer to what sort of operation is being done (e.g. Qtoolbar,
2174    Qresource, etc.). */
2175
2176 void
2177 maybe_signal_error (Lisp_Object sig, Lisp_Object data, Lisp_Object class,
2178                     Error_behavior errb)
2179 {
2180   if (ERRB_EQ (errb, ERROR_ME_NOT))
2181     return;
2182   else if (ERRB_EQ (errb, ERROR_ME_WARN))
2183     warn_when_safe_lispobj (class, Qwarning, Fcons (sig, data));
2184   else
2185     for (;;)
2186       Fsignal (sig, data);
2187 }
2188
2189 /* Signal a continuable error or display a warning or do nothing,
2190    according to ERRB. */
2191
2192 Lisp_Object
2193 maybe_signal_continuable_error (Lisp_Object sig, Lisp_Object data,
2194                                 Lisp_Object class, Error_behavior errb)
2195 {
2196   if (ERRB_EQ (errb, ERROR_ME_NOT))
2197     return Qnil;
2198   else if (ERRB_EQ (errb, ERROR_ME_WARN))
2199     {
2200       warn_when_safe_lispobj (class, Qwarning, Fcons (sig, data));
2201       return Qnil;
2202     }
2203   else
2204     return Fsignal (sig, data);
2205 }
2206
2207 \f
2208 /****************** Error functions class 2 ******************/
2209
2210 /* Class 2: Printf-like functions that signal an error.
2211    These functions signal an error of type Qerror, whose data
2212    is a single string, created using the arguments. */
2213
2214 /* dump an error message; called like printf */
2215
2216 DOESNT_RETURN
2217 error (const char *fmt, ...)
2218 {
2219   Lisp_Object obj;
2220   va_list args;
2221
2222   va_start (args, fmt);
2223   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2224                                 args);
2225   va_end (args);
2226
2227   /* Fsignal GC-protects its args */
2228   signal_error (Qerror, list1 (obj));
2229 }
2230
2231 void
2232 maybe_error (Lisp_Object class, Error_behavior errb, const char *fmt, ...)
2233 {
2234   Lisp_Object obj;
2235   va_list args;
2236
2237   /* Optimization: */
2238   if (ERRB_EQ (errb, ERROR_ME_NOT))
2239     return;
2240
2241   va_start (args, fmt);
2242   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2243                                 args);
2244   va_end (args);
2245
2246   /* Fsignal GC-protects its args */
2247   maybe_signal_error (Qerror, list1 (obj), class, errb);
2248 }
2249
2250 Lisp_Object
2251 continuable_error (const char *fmt, ...)
2252 {
2253   Lisp_Object obj;
2254   va_list args;
2255
2256   va_start (args, fmt);
2257   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2258                                 args);
2259   va_end (args);
2260
2261   /* Fsignal GC-protects its args */
2262   return Fsignal (Qerror, list1 (obj));
2263 }
2264
2265 Lisp_Object
2266 maybe_continuable_error (Lisp_Object class, Error_behavior errb,
2267                          const char *fmt, ...)
2268 {
2269   Lisp_Object obj;
2270   va_list args;
2271
2272   /* Optimization: */
2273   if (ERRB_EQ (errb, ERROR_ME_NOT))
2274     return Qnil;
2275
2276   va_start (args, fmt);
2277   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2278                                 args);
2279   va_end (args);
2280
2281   /* Fsignal GC-protects its args */
2282   return maybe_signal_continuable_error (Qerror, list1 (obj), class, errb);
2283 }
2284
2285 \f
2286 /****************** Error functions class 3 ******************/
2287
2288 /* Class 3: Signal an error with a string and an associated object.
2289    These functions signal an error of type Qerror, whose data
2290    is two objects, a string and a related Lisp object (usually the object
2291    where the error is occurring). */
2292
2293 DOESNT_RETURN
2294 signal_simple_error (const char *reason, Lisp_Object frob)
2295 {
2296   signal_error (Qerror, list2 (build_translated_string (reason), frob));
2297 }
2298
2299 void
2300 maybe_signal_simple_error (const char *reason, Lisp_Object frob,
2301                            Lisp_Object class, Error_behavior errb)
2302 {
2303   /* Optimization: */
2304   if (ERRB_EQ (errb, ERROR_ME_NOT))
2305     return;
2306   maybe_signal_error (Qerror, list2 (build_translated_string (reason), frob),
2307                                      class, errb);
2308 }
2309
2310 Lisp_Object
2311 signal_simple_continuable_error (const char *reason, Lisp_Object frob)
2312 {
2313   return Fsignal (Qerror, list2 (build_translated_string (reason), frob));
2314 }
2315
2316 Lisp_Object
2317 maybe_signal_simple_continuable_error (const char *reason, Lisp_Object frob,
2318                                        Lisp_Object class, Error_behavior errb)
2319 {
2320   /* Optimization: */
2321   if (ERRB_EQ (errb, ERROR_ME_NOT))
2322     return Qnil;
2323   return maybe_signal_continuable_error
2324     (Qerror, list2 (build_translated_string (reason),
2325                     frob), class, errb);
2326 }
2327
2328 \f
2329 /****************** Error functions class 4 ******************/
2330
2331 /* Class 4: Printf-like functions that signal an error.
2332    These functions signal an error of type Qerror, whose data
2333    is a two objects, a string (created using the arguments) and a
2334    Lisp object.
2335 */
2336
2337 DOESNT_RETURN
2338 error_with_frob (Lisp_Object frob, const char *fmt, ...)
2339 {
2340   Lisp_Object obj;
2341   va_list args;
2342
2343   va_start (args, fmt);
2344   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2345                                 args);
2346   va_end (args);
2347
2348   /* Fsignal GC-protects its args */
2349   signal_error (Qerror, list2 (obj, frob));
2350 }
2351
2352 void
2353 maybe_error_with_frob (Lisp_Object frob, Lisp_Object class,
2354                        Error_behavior errb, const char *fmt, ...)
2355 {
2356   Lisp_Object obj;
2357   va_list args;
2358
2359   /* Optimization: */
2360   if (ERRB_EQ (errb, ERROR_ME_NOT))
2361     return;
2362
2363   va_start (args, fmt);
2364   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2365                                 args);
2366   va_end (args);
2367
2368   /* Fsignal GC-protects its args */
2369   maybe_signal_error (Qerror, list2 (obj, frob), class, errb);
2370 }
2371
2372 Lisp_Object
2373 continuable_error_with_frob (Lisp_Object frob, const char *fmt, ...)
2374 {
2375   Lisp_Object obj;
2376   va_list args;
2377
2378   va_start (args, fmt);
2379   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2380                                 args);
2381   va_end (args);
2382
2383   /* Fsignal GC-protects its args */
2384   return Fsignal (Qerror, list2 (obj, frob));
2385 }
2386
2387 Lisp_Object
2388 maybe_continuable_error_with_frob (Lisp_Object frob, Lisp_Object class,
2389                                    Error_behavior errb, const char *fmt, ...)
2390 {
2391   Lisp_Object obj;
2392   va_list args;
2393
2394   /* Optimization: */
2395   if (ERRB_EQ (errb, ERROR_ME_NOT))
2396     return Qnil;
2397
2398   va_start (args, fmt);
2399   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt), Qnil, -1,
2400                                 args);
2401   va_end (args);
2402
2403   /* Fsignal GC-protects its args */
2404   return maybe_signal_continuable_error (Qerror, list2 (obj, frob),
2405                                          class, errb);
2406 }
2407
2408 \f
2409 /****************** Error functions class 5 ******************/
2410
2411 /* Class 5: Signal an error with a string and two associated objects.
2412    These functions signal an error of type Qerror, whose data
2413    is three objects, a string and two related Lisp objects. */
2414
2415 DOESNT_RETURN
2416 signal_simple_error_2 (const char *reason,
2417                        Lisp_Object frob0, Lisp_Object frob1)
2418 {
2419   signal_error (Qerror, list3 (build_translated_string (reason), frob0,
2420                                frob1));
2421 }
2422
2423 void
2424 maybe_signal_simple_error_2 (const char *reason, Lisp_Object frob0,
2425                              Lisp_Object frob1, Lisp_Object class,
2426                              Error_behavior errb)
2427 {
2428   /* Optimization: */
2429   if (ERRB_EQ (errb, ERROR_ME_NOT))
2430     return;
2431   maybe_signal_error (Qerror, list3 (build_translated_string (reason), frob0,
2432                                      frob1), class, errb);
2433 }
2434
2435
2436 Lisp_Object
2437 signal_simple_continuable_error_2 (const char *reason, Lisp_Object frob0,
2438                                    Lisp_Object frob1)
2439 {
2440   return Fsignal (Qerror, list3 (build_translated_string (reason), frob0,
2441                                  frob1));
2442 }
2443
2444 Lisp_Object
2445 maybe_signal_simple_continuable_error_2 (const char *reason, Lisp_Object frob0,
2446                                          Lisp_Object frob1, Lisp_Object class,
2447                                          Error_behavior errb)
2448 {
2449   /* Optimization: */
2450   if (ERRB_EQ (errb, ERROR_ME_NOT))
2451     return Qnil;
2452   return maybe_signal_continuable_error
2453     (Qerror, list3 (build_translated_string (reason), frob0,
2454                     frob1),
2455      class, errb);
2456 }
2457
2458 \f
2459 /* This is what the QUIT macro calls to signal a quit */
2460 void
2461 signal_quit (void)
2462 {
2463   /* This function can GC */
2464   if (EQ (Vquit_flag, Qcritical))
2465     debug_on_quit |= 2;         /* set critical bit. */
2466   Vquit_flag = Qnil;
2467   /* note that this is continuable. */
2468   Fsignal (Qquit, Qnil);
2469 }
2470
2471 \f
2472 /* Used in core lisp functions for efficiency */
2473 Lisp_Object
2474 signal_void_function_error (Lisp_Object function)
2475 {
2476   return Fsignal (Qvoid_function, list1 (function));
2477 }
2478
2479 Lisp_Object
2480 signal_invalid_function_error (Lisp_Object function)
2481 {
2482   return Fsignal (Qinvalid_function, list1 (function));
2483 }
2484
2485 Lisp_Object
2486 signal_wrong_number_of_arguments_error (Lisp_Object function, int nargs)
2487 {
2488   return Fsignal (Qwrong_number_of_arguments,
2489                   list2 (function, make_int (nargs)));
2490 }
2491
2492 /* Used in list traversal macros for efficiency. */
2493 DOESNT_RETURN
2494 signal_malformed_list_error (Lisp_Object list)
2495 {
2496   signal_error (Qmalformed_list, list1 (list));
2497 }
2498
2499 DOESNT_RETURN
2500 signal_malformed_property_list_error (Lisp_Object list)
2501 {
2502   signal_error (Qmalformed_property_list, list1 (list));
2503 }
2504
2505 DOESNT_RETURN
2506 signal_circular_list_error (Lisp_Object list)
2507 {
2508   signal_error (Qcircular_list, list1 (list));
2509 }
2510
2511 DOESNT_RETURN
2512 signal_circular_property_list_error (Lisp_Object list)
2513 {
2514   signal_error (Qcircular_property_list, list1 (list));
2515 }
2516 \f
2517 /************************************************************************/
2518 /*                            User commands                             */
2519 /************************************************************************/
2520
2521 DEFUN ("commandp", Fcommandp, 1, 1, 0, /*
2522 Return t if FUNCTION makes provisions for interactive calling.
2523 This means it contains a description for how to read arguments to give it.
2524 The value is nil for an invalid function or a symbol with no function
2525 definition.
2526
2527 Interactively callable functions include
2528
2529 -- strings and vectors (treated as keyboard macros)
2530 -- lambda-expressions that contain a top-level call to `interactive'
2531 -- autoload definitions made by `autoload' with non-nil fourth argument
2532    (i.e. the interactive flag)
2533 -- compiled-function objects with a non-nil `compiled-function-interactive'
2534    value
2535 -- subrs (built-in functions) that are interactively callable
2536
2537 Also, a symbol satisfies `commandp' if its function definition does so.
2538 */
2539        (function))
2540 {
2541   Lisp_Object fun = indirect_function (function, 0);
2542
2543   if (COMPILED_FUNCTIONP (fun))
2544     return XCOMPILED_FUNCTION (fun)->flags.interactivep ? Qt : Qnil;
2545
2546   /* Lists may represent commands.  */
2547   if (CONSP (fun))
2548     {
2549       Lisp_Object funcar = XCAR (fun);
2550       if (EQ (funcar, Qlambda))
2551         return Fassq (Qinteractive, Fcdr (Fcdr (fun)));
2552       if (EQ (funcar, Qautoload))
2553         return Fcar (Fcdr (Fcdr (Fcdr (fun))));
2554       else
2555         return Qnil;
2556     }
2557
2558   /* Emacs primitives are interactive if their DEFUN specifies an
2559      interactive spec.  */
2560   if (SUBRP (fun))
2561     return XSUBR (fun)->prompt ? Qt : Qnil;
2562
2563   /* Strings and vectors are keyboard macros.  */
2564   if (VECTORP (fun) || STRINGP (fun))
2565     return Qt;
2566
2567   /* Everything else (including Qunbound) is not a command.  */
2568   return Qnil;
2569 }
2570
2571 DEFUN ("command-execute", Fcommand_execute, 1, 3, 0, /*
2572 Execute CMD as an editor command.
2573 CMD must be an object that satisfies the `commandp' predicate.
2574 Optional second arg RECORD-FLAG is as in `call-interactively'.
2575 The argument KEYS specifies the value to use instead of (this-command-keys)
2576 when reading the arguments.
2577 */
2578        (cmd, record, keys))
2579 {
2580   /* This function can GC */
2581   Lisp_Object prefixarg;
2582   Lisp_Object final = cmd;
2583   struct backtrace backtrace;
2584   struct console *con = XCONSOLE (Vselected_console);
2585
2586   prefixarg = con->prefix_arg;
2587   con->prefix_arg = Qnil;
2588   Vcurrent_prefix_arg = prefixarg;
2589   debug_on_next_call = 0; /* #### from FSFmacs; correct? */
2590
2591   if (SYMBOLP (cmd) && !NILP (Fget (cmd, Qdisabled, Qnil)))
2592     return run_hook (Vdisabled_command_hook);
2593
2594   for (;;)
2595     {
2596       final = indirect_function (cmd, 1);
2597       if (CONSP (final) && EQ (Fcar (final), Qautoload))
2598         do_autoload (final, cmd);
2599       else
2600         break;
2601     }
2602
2603   if (CONSP (final) || SUBRP (final) || COMPILED_FUNCTIONP (final))
2604     {
2605       backtrace.function = &Qcall_interactively;
2606       backtrace.args = &cmd;
2607       backtrace.nargs = 1;
2608       backtrace.evalargs = 0;
2609       backtrace.pdlcount = specpdl_depth();
2610       backtrace.debug_on_exit = 0;
2611       PUSH_BACKTRACE (backtrace);
2612
2613       final = Fcall_interactively (cmd, record, keys);
2614
2615       POP_BACKTRACE (backtrace);
2616       return final;
2617     }
2618   else if (STRINGP (final) || VECTORP (final))
2619     {
2620       return Fexecute_kbd_macro (final, prefixarg);
2621     }
2622   else
2623     {
2624       Fsignal (Qwrong_type_argument,
2625                Fcons (Qcommandp,
2626                       (EQ (cmd, final)
2627                        ? list1 (cmd)
2628                        : list2 (cmd, final))));
2629       return Qnil;
2630     }
2631 }
2632
2633 DEFUN ("interactive-p", Finteractive_p, 0, 0, 0, /*
2634 Return t if function in which this appears was called interactively.
2635 This means that the function was called with call-interactively (which
2636 includes being called as the binding of a key)
2637 and input is currently coming from the keyboard (not in keyboard macro).
2638 */
2639        ())
2640 {
2641   REGISTER struct backtrace *btp;
2642   REGISTER Lisp_Object fun;
2643
2644   if (!INTERACTIVE)
2645     return Qnil;
2646
2647   /*  Unless the object was compiled, skip the frame of interactive-p itself
2648       (if interpreted) or the frame of byte-code (if called from a compiled
2649       function).  Note that *btp->function may be a symbol pointing at a
2650       compiled function. */
2651   btp = backtrace_list;
2652
2653 #if 0 /* FSFmacs */
2654
2655   /* #### FSFmacs does the following instead.  I can't figure
2656      out which one is more correct. */
2657   /* If this isn't a byte-compiled function, there may be a frame at
2658      the top for Finteractive_p itself.  If so, skip it.  */
2659   fun = Findirect_function (*btp->function);
2660   if (SUBRP (fun) && XSUBR (fun) == &Sinteractive_p)
2661     btp = btp->next;
2662
2663   /* If we're running an Emacs 18-style byte-compiled function, there
2664      may be a frame for Fbyte_code.  Now, given the strictest
2665      definition, this function isn't really being called
2666      interactively, but because that's the way Emacs 18 always builds
2667      byte-compiled functions, we'll accept it for now.  */
2668   if (EQ (*btp->function, Qbyte_code))
2669     btp = btp->next;
2670
2671   /* If this isn't a byte-compiled function, then we may now be
2672      looking at several frames for special forms.  Skip past them.  */
2673   while (btp &&
2674          btp->nargs == UNEVALLED)
2675     btp = btp->next;
2676
2677 #else
2678
2679   if (! (COMPILED_FUNCTIONP (Findirect_function (*btp->function))))
2680     btp = btp->next;
2681   for (;
2682        btp && (btp->nargs == UNEVALLED
2683                || EQ (*btp->function, Qbyte_code));
2684        btp = btp->next)
2685     {}
2686   /* btp now points at the frame of the innermost function
2687      that DOES eval its args.
2688      If it is a built-in function (such as load or eval-region)
2689      return nil.  */
2690   /* Beats me why this is necessary, but it is */
2691   if (btp && EQ (*btp->function, Qcall_interactively))
2692     return Qt;
2693
2694 #endif
2695
2696   fun = Findirect_function (*btp->function);
2697   if (SUBRP (fun))
2698     return Qnil;
2699   /* btp points to the frame of a Lisp function that called interactive-p.
2700      Return t if that function was called interactively.  */
2701   if (btp && btp->next && EQ (*btp->next->function, Qcall_interactively))
2702     return Qt;
2703   return Qnil;
2704 }
2705
2706 \f
2707 /************************************************************************/
2708 /*                            Autoloading                               */
2709 /************************************************************************/
2710
2711 DEFUN ("autoload", Fautoload, 2, 5, 0, /*
2712 Define FUNCTION to autoload from FILE.
2713 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
2714 Third arg DOCSTRING is documentation for the function.
2715 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
2716 Fifth arg TYPE indicates the type of the object:
2717    nil or omitted says FUNCTION is a function,
2718    `keymap' says FUNCTION is really a keymap, and
2719    `macro' or t says FUNCTION is really a macro.
2720 Third through fifth args give info about the real definition.
2721 They default to nil.
2722 If FUNCTION is already defined other than as an autoload,
2723 this does nothing and returns nil.
2724 */
2725        (function, file, docstring, interactive, type))
2726 {
2727   /* This function can GC */
2728   CHECK_SYMBOL (function);
2729   CHECK_STRING (file);
2730
2731   /* If function is defined and not as an autoload, don't override */
2732   {
2733     Lisp_Object f = XSYMBOL (function)->function;
2734     if (!UNBOUNDP (f) && !(CONSP (f) && EQ (XCAR (f), Qautoload)))
2735       return Qnil;
2736   }
2737
2738   if (purify_flag)
2739     {
2740       /* Attempt to avoid consing identical (string=) pure strings. */
2741       file = Fsymbol_name (Fintern (file, Qnil));
2742     }
2743
2744   return Ffset (function, Fcons (Qautoload, list4 (file,
2745                                                    docstring,
2746                                                    interactive,
2747                                                    type)));
2748 }
2749
2750 Lisp_Object
2751 un_autoload (Lisp_Object oldqueue)
2752 {
2753   /* This function can GC */
2754   REGISTER Lisp_Object queue, first, second;
2755
2756   /* Queue to unwind is current value of Vautoload_queue.
2757      oldqueue is the shadowed value to leave in Vautoload_queue.  */
2758   queue = Vautoload_queue;
2759   Vautoload_queue = oldqueue;
2760   while (CONSP (queue))
2761     {
2762       first = XCAR (queue);
2763       second = Fcdr (first);
2764       first = Fcar (first);
2765       if (NILP (second))
2766         Vfeatures = first;
2767       else
2768         Ffset (first, second);
2769       queue = Fcdr (queue);
2770     }
2771   return Qnil;
2772 }
2773
2774 void
2775 do_autoload (Lisp_Object fundef,
2776              Lisp_Object funname)
2777 {
2778   /* This function can GC */
2779   int speccount = specpdl_depth();
2780   Lisp_Object fun = funname;
2781   struct gcpro gcpro1, gcpro2;
2782
2783   CHECK_SYMBOL (funname);
2784   GCPRO2 (fun, funname);
2785
2786   /* Value saved here is to be restored into Vautoload_queue */
2787   record_unwind_protect (un_autoload, Vautoload_queue);
2788   Vautoload_queue = Qt;
2789   call4 (Qload, Fcar (Fcdr (fundef)), Qnil, noninteractive ? Qt : Qnil, Qnil);
2790
2791   {
2792     Lisp_Object queue;
2793
2794     /* Save the old autoloads, in case we ever do an unload. */
2795     for (queue = Vautoload_queue; CONSP (queue); queue = XCDR (queue))
2796       {
2797         Lisp_Object first  = XCAR (queue);
2798         Lisp_Object second = Fcdr (first);
2799
2800         first = Fcar (first);
2801
2802         /* Note: This test is subtle.  The cdr of an autoload-queue entry
2803            may be an atom if the autoload entry was generated by a defalias
2804            or fset. */
2805         if (CONSP (second))
2806           Fput (first, Qautoload, (XCDR (second)));
2807       }
2808   }
2809
2810   /* Once loading finishes, don't undo it.  */
2811   Vautoload_queue = Qt;
2812   unbind_to (speccount, Qnil);
2813
2814   fun = indirect_function (fun, 0);
2815
2816 #if 0 /* FSFmacs */
2817   if (!NILP (Fequal (fun, fundef)))
2818 #else
2819   if (UNBOUNDP (fun)
2820       || (CONSP (fun)
2821           && EQ (XCAR (fun), Qautoload)))
2822 #endif
2823     error ("Autoloading failed to define function %s",
2824            string_data (XSYMBOL (funname)->name));
2825   UNGCPRO;
2826 }
2827
2828 \f
2829 /************************************************************************/
2830 /*                         eval, funcall, apply                         */
2831 /************************************************************************/
2832
2833 static Lisp_Object funcall_lambda (Lisp_Object fun,
2834                                    int nargs, Lisp_Object args[]);
2835 static int in_warnings;
2836
2837 static Lisp_Object
2838 in_warnings_restore (Lisp_Object minimus)
2839 {
2840   in_warnings = 0;
2841   return Qnil;
2842 }
2843
2844 DEFUN ("eval", Feval, 1, 1, 0, /*
2845 Evaluate FORM and return its value.
2846 */
2847        (form))
2848 {
2849   /* This function can GC */
2850   Lisp_Object fun, val, original_fun, original_args;
2851   int nargs;
2852   struct backtrace backtrace;
2853
2854   /* I think this is a pretty safe place to call Lisp code, don't you? */
2855   while (!in_warnings && !NILP (Vpending_warnings))
2856     {
2857       struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
2858       int speccount = specpdl_depth();
2859       Lisp_Object this_warning_cons, this_warning, class, level, messij;
2860
2861       record_unwind_protect (in_warnings_restore, Qnil);
2862       in_warnings = 1;
2863       this_warning_cons = Vpending_warnings;
2864       this_warning = XCAR (this_warning_cons);
2865       /* in case an error occurs in the warn function, at least
2866          it won't happen infinitely */
2867       Vpending_warnings = XCDR (Vpending_warnings);
2868       free_cons (XCONS (this_warning_cons));
2869       class = XCAR (this_warning);
2870       level = XCAR (XCDR (this_warning));
2871       messij = XCAR (XCDR (XCDR (this_warning)));
2872       free_list (this_warning);
2873
2874       if (NILP (Vpending_warnings))
2875         Vpending_warnings_tail = Qnil; /* perhaps not strictly necessary,
2876                                           but safer */
2877
2878       GCPRO4 (form, class, level, messij);
2879       if (!STRINGP (messij))
2880         messij = Fprin1_to_string (messij, Qnil);
2881       call3 (Qdisplay_warning, class, messij, level);
2882       UNGCPRO;
2883       unbind_to (speccount, Qnil);
2884     }
2885
2886   if (!CONSP (form))
2887     {
2888       if (SYMBOLP (form))
2889         return Fsymbol_value (form);
2890       else
2891         return form;
2892     }
2893
2894   QUIT;
2895   if ((consing_since_gc > gc_cons_threshold) || always_gc)
2896     {
2897       struct gcpro gcpro1;
2898       GCPRO1 (form);
2899       garbage_collect_1 ();
2900       UNGCPRO;
2901     }
2902
2903   if (++lisp_eval_depth > max_lisp_eval_depth)
2904     {
2905       if (max_lisp_eval_depth < 100)
2906         max_lisp_eval_depth = 100;
2907       if (lisp_eval_depth > max_lisp_eval_depth)
2908         error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2909     }
2910
2911   /* We guaranteed CONSP (form) above */
2912   original_fun  = XCAR (form);
2913   original_args = XCDR (form);
2914
2915   GET_EXTERNAL_LIST_LENGTH (original_args, nargs);
2916
2917   backtrace.pdlcount = specpdl_depth();
2918   backtrace.function = &original_fun; /* This also protects them from gc */
2919   backtrace.args = &original_args;
2920   backtrace.nargs = UNEVALLED;
2921   backtrace.evalargs = 1;
2922   backtrace.debug_on_exit = 0;
2923   PUSH_BACKTRACE (backtrace);
2924
2925   if (debug_on_next_call)
2926     do_debug_on_call (Qt);
2927
2928   if (profiling_active)
2929     profile_increase_call_count (original_fun);
2930
2931   /* At this point, only original_fun and original_args
2932      have values that will be used below. */
2933  retry:
2934   fun = indirect_function (original_fun, 1);
2935
2936   if (SUBRP (fun))
2937     {
2938       Lisp_Subr *subr = XSUBR (fun);
2939       int max_args = subr->max_args;
2940
2941       if (nargs < subr->min_args)
2942         goto wrong_number_of_arguments;
2943
2944       if (max_args == UNEVALLED) /* Optimize for the common case */
2945         {
2946           backtrace.evalargs = 0;
2947           val = (((Lisp_Object (*) (Lisp_Object)) subr_function (subr))
2948                  (original_args));
2949         }
2950       else if (nargs <= max_args)
2951         {
2952           struct gcpro gcpro1;
2953           Lisp_Object args[SUBR_MAX_ARGS];
2954           REGISTER Lisp_Object *p = args;
2955
2956           GCPRO1 (args[0]);
2957           gcpro1.nvars = 0;
2958
2959           {
2960             REGISTER Lisp_Object arg;
2961             LIST_LOOP_2 (arg, original_args)
2962               {
2963                 *p++ = Feval (arg);
2964                 gcpro1.nvars++;
2965               }
2966           }
2967
2968           /* &optional args default to nil. */
2969           while (p - args < max_args)
2970             *p++ = Qnil;
2971
2972           backtrace.args  = args;
2973           backtrace.nargs = nargs;
2974
2975           FUNCALL_SUBR (val, subr, args, max_args);
2976
2977           UNGCPRO;
2978         }
2979       else if (max_args == MANY)
2980         {
2981           /* Pass a vector of evaluated arguments */
2982           struct gcpro gcpro1;
2983           Lisp_Object *args = alloca_array (Lisp_Object, nargs);
2984           REGISTER Lisp_Object *p = args;
2985
2986           GCPRO1 (args[0]);
2987           gcpro1.nvars = 0;
2988
2989           {
2990             REGISTER Lisp_Object arg;
2991             LIST_LOOP_2 (arg, original_args)
2992               {
2993                 *p++ = Feval (arg);
2994                 gcpro1.nvars++;
2995               }
2996           }
2997
2998           backtrace.args  = args;
2999           backtrace.nargs = nargs;
3000
3001           val = (((Lisp_Object (*) (int, Lisp_Object *)) subr_function (subr))
3002                  (nargs, args));
3003
3004           UNGCPRO;
3005         }
3006       else
3007         {
3008         wrong_number_of_arguments:
3009           val = signal_wrong_number_of_arguments_error (original_fun, nargs);
3010         }
3011     }
3012   else if (COMPILED_FUNCTIONP (fun))
3013     {
3014       struct gcpro gcpro1;
3015       Lisp_Object *args = alloca_array (Lisp_Object, nargs);
3016       REGISTER Lisp_Object *p = args;
3017
3018       GCPRO1 (args[0]);
3019       gcpro1.nvars = 0;
3020
3021       {
3022         REGISTER Lisp_Object arg;
3023         LIST_LOOP_2 (arg, original_args)
3024           {
3025             *p++ = Feval (arg);
3026             gcpro1.nvars++;
3027           }
3028       }
3029
3030       backtrace.args     = args;
3031       backtrace.nargs    = nargs;
3032       backtrace.evalargs = 0;
3033
3034       val = funcall_compiled_function (fun, nargs, args);
3035
3036       /* Do the debug-on-exit now, while args is still GCPROed.  */
3037       if (backtrace.debug_on_exit)
3038         val = do_debug_on_exit (val);
3039       /* Don't do it again when we return to eval.  */
3040       backtrace.debug_on_exit = 0;
3041
3042       UNGCPRO;
3043     }
3044   else if (CONSP (fun))
3045     {
3046       Lisp_Object funcar = XCAR (fun);
3047
3048       if (EQ (funcar, Qautoload))
3049         {
3050           do_autoload (fun, original_fun);
3051           goto retry;
3052         }
3053       else if (EQ (funcar, Qmacro))
3054         {
3055           val = Feval (apply1 (XCDR (fun), original_args));
3056         }
3057       else if (EQ (funcar, Qlambda))
3058         {
3059           struct gcpro gcpro1;
3060           Lisp_Object *args = alloca_array (Lisp_Object, nargs);
3061           REGISTER Lisp_Object *p = args;
3062
3063           GCPRO1 (args[0]);
3064           gcpro1.nvars = 0;
3065
3066           {
3067             REGISTER Lisp_Object arg;
3068             LIST_LOOP_2 (arg, original_args)
3069               {
3070                 *p++ = Feval (arg);
3071                 gcpro1.nvars++;
3072               }
3073           }
3074
3075           UNGCPRO;
3076
3077           backtrace.args     = args; /* this also GCPROs `args' */
3078           backtrace.nargs    = nargs;
3079           backtrace.evalargs = 0;
3080
3081           val = funcall_lambda (fun, nargs, args);
3082
3083           /* Do the debug-on-exit now, while args is still GCPROed.  */
3084           if (backtrace.debug_on_exit)
3085             val = do_debug_on_exit (val);
3086           /* Don't do it again when we return to eval.  */
3087           backtrace.debug_on_exit = 0;
3088         }
3089       else
3090         {
3091           goto invalid_function;
3092         }
3093     }
3094   else /* ! (SUBRP (fun) || COMPILED_FUNCTIONP (fun) || CONSP (fun)) */
3095     {
3096     invalid_function:
3097       val = signal_invalid_function_error (fun);
3098     }
3099
3100   lisp_eval_depth--;
3101   if (backtrace.debug_on_exit)
3102     val = do_debug_on_exit (val);
3103   POP_BACKTRACE (backtrace);
3104   return val;
3105 }
3106
3107 \f
3108 DEFUN ("funcall", Ffuncall, 1, MANY, 0, /*
3109 Call first argument as a function, passing the remaining arguments to it.
3110 Thus, (funcall 'cons 'x 'y) returns (x . y).
3111 */
3112        (int nargs, Lisp_Object *args))
3113 {
3114   /* This function can GC */
3115   Lisp_Object fun;
3116   Lisp_Object val;
3117   struct backtrace backtrace;
3118   int fun_nargs = nargs - 1;
3119   Lisp_Object *fun_args = args + 1;
3120
3121   QUIT;
3122   if ((consing_since_gc > gc_cons_threshold) || always_gc)
3123     /* Callers should gcpro lexpr args */
3124     garbage_collect_1 ();
3125
3126   if (++lisp_eval_depth > max_lisp_eval_depth)
3127     {
3128       if (max_lisp_eval_depth < 100)
3129         max_lisp_eval_depth = 100;
3130       if (lisp_eval_depth > max_lisp_eval_depth)
3131         error ("Lisp nesting exceeds `max-lisp-eval-depth'");
3132     }
3133
3134   backtrace.pdlcount = specpdl_depth();
3135   backtrace.function = &args[0];
3136   backtrace.args  = fun_args;
3137   backtrace.nargs = fun_nargs;
3138   backtrace.evalargs = 0;
3139   backtrace.debug_on_exit = 0;
3140   PUSH_BACKTRACE (backtrace);
3141
3142   if (debug_on_next_call)
3143     do_debug_on_call (Qlambda);
3144
3145  retry:
3146
3147   fun = args[0];
3148
3149   /* It might be useful to place this *after* all the checks.  */
3150   if (profiling_active)
3151     profile_increase_call_count (fun);
3152
3153   /* We could call indirect_function directly, but profiling shows
3154      this is worth optimizing by partially unrolling the loop.  */
3155   if (SYMBOLP (fun))
3156     {
3157       fun = XSYMBOL (fun)->function;
3158       if (SYMBOLP (fun))
3159         {
3160           fun = XSYMBOL (fun)->function;
3161           if (SYMBOLP (fun))
3162             fun = indirect_function (fun, 1);
3163         }
3164     }
3165
3166   if (SUBRP (fun))
3167     {
3168       Lisp_Subr *subr = XSUBR (fun);
3169       int max_args = subr->max_args;
3170       Lisp_Object spacious_args[SUBR_MAX_ARGS];
3171
3172       if (fun_nargs == max_args) /* Optimize for the common case */
3173         {
3174         funcall_subr:
3175           FUNCALL_SUBR (val, subr, fun_args, max_args);
3176         }
3177       else if (fun_nargs < subr->min_args)
3178         {
3179           goto wrong_number_of_arguments;
3180         }
3181       else if (fun_nargs < max_args)
3182         {
3183           Lisp_Object *p = spacious_args;
3184
3185           /* Default optionals to nil */
3186           while (fun_nargs--)
3187             *p++ = *fun_args++;
3188           while (p - spacious_args < max_args)
3189             *p++ = Qnil;
3190
3191           fun_args = spacious_args;
3192           goto funcall_subr;
3193         }
3194       else if (max_args == MANY)
3195         {
3196           val = SUBR_FUNCTION (subr, MANY) (fun_nargs, fun_args);
3197         }
3198       else if (max_args == UNEVALLED) /* Can't funcall a special form */
3199         {
3200           goto invalid_function;
3201         }
3202       else
3203         {
3204         wrong_number_of_arguments:
3205           val = signal_wrong_number_of_arguments_error (fun, fun_nargs);
3206         }
3207     }
3208   else if (COMPILED_FUNCTIONP (fun))
3209     {
3210       val = funcall_compiled_function (fun, fun_nargs, fun_args);
3211     }
3212   else if (CONSP (fun))
3213     {
3214       Lisp_Object funcar = XCAR (fun);
3215
3216       if (EQ (funcar, Qlambda))
3217         {
3218           val = funcall_lambda (fun, fun_nargs, fun_args);
3219         }
3220       else if (EQ (funcar, Qautoload))
3221         {
3222           do_autoload (fun, args[0]);
3223           goto retry;
3224         }
3225       else /* Can't funcall a macro */
3226         {
3227           goto invalid_function;
3228         }
3229     }
3230   else if (UNBOUNDP (fun))
3231     {
3232       val = signal_void_function_error (args[0]);
3233     }
3234   else
3235     {
3236     invalid_function:
3237       val = signal_invalid_function_error (fun);
3238     }
3239
3240   lisp_eval_depth--;
3241   if (backtrace.debug_on_exit)
3242     val = do_debug_on_exit (val);
3243   POP_BACKTRACE (backtrace);
3244   return val;
3245 }
3246
3247 DEFUN ("functionp", Ffunctionp, 1, 1, 0, /*
3248 Return t if OBJECT can be called as a function, else nil.
3249 A function is an object that can be applied to arguments,
3250 using for example `funcall' or `apply'.
3251 */
3252        (object))
3253 {
3254   if (SYMBOLP (object))
3255     object = indirect_function (object, 0);
3256
3257   return
3258     (SUBRP (object) ||
3259      COMPILED_FUNCTIONP (object) ||
3260      (CONSP (object) &&
3261       (EQ (XCAR (object), Qlambda) ||
3262        EQ (XCAR (object), Qautoload))))
3263     ? Qt : Qnil;
3264 }
3265
3266 static Lisp_Object
3267 function_argcount (Lisp_Object function, int function_min_args_p)
3268 {
3269   Lisp_Object orig_function = function;
3270   Lisp_Object arglist;
3271
3272  retry:
3273
3274   if (SYMBOLP (function))
3275     function = indirect_function (function, 1);
3276
3277   if (SUBRP (function))
3278     {
3279       return function_min_args_p ?
3280         Fsubr_min_args (function):
3281         Fsubr_max_args (function);
3282    }
3283   else if (COMPILED_FUNCTIONP (function))
3284     {
3285       arglist = compiled_function_arglist (XCOMPILED_FUNCTION (function));
3286     }
3287   else if (CONSP (function))
3288     {
3289       Lisp_Object funcar = XCAR (function);
3290
3291       if (EQ (funcar, Qmacro))
3292         {
3293           function = XCDR (function);
3294           goto retry;
3295         }
3296       else if (EQ (funcar, Qautoload))
3297         {
3298           do_autoload (function, orig_function);
3299           goto retry;
3300         }
3301       else if (EQ (funcar, Qlambda))
3302         {
3303           arglist = Fcar (XCDR (function));
3304         }
3305       else
3306         {
3307           goto invalid_function;
3308         }
3309     }
3310   else
3311     {
3312     invalid_function:
3313       return signal_invalid_function_error (function);
3314     }
3315
3316   {
3317     int argcount = 0;
3318     Lisp_Object arg;
3319
3320     EXTERNAL_LIST_LOOP_2 (arg, arglist)
3321       {
3322         if (EQ (arg, Qand_optional))
3323           {
3324             if (function_min_args_p)
3325               break;
3326           }
3327         else if (EQ (arg, Qand_rest))
3328           {
3329             if (function_min_args_p)
3330               break;
3331             else
3332               return Qnil;
3333           }
3334         else
3335           {
3336             argcount++;
3337           }
3338       }
3339
3340     return make_int (argcount);
3341   }
3342 }
3343
3344 DEFUN ("function-min-args", Ffunction_min_args, 1, 1, 0, /*
3345 Return the number of arguments a function may be called with.
3346 The function may be any form that can be passed to `funcall',
3347 any special form, or any macro.
3348 */
3349        (function))
3350 {
3351   return function_argcount (function, 1);
3352 }
3353
3354 DEFUN ("function-max-args", Ffunction_max_args, 1, 1, 0, /*
3355 Return the number of arguments a function may be called with.
3356 The function may be any form that can be passed to `funcall',
3357 any special form, or any macro.
3358 If the function takes an arbitrary number of arguments or is
3359 a built-in special form, nil is returned.
3360 */
3361        (function))
3362 {
3363   return function_argcount (function, 0);
3364 }
3365
3366 \f
3367 DEFUN ("apply", Fapply, 2, MANY, 0, /*
3368 Call FUNCTION with the remaining args, using the last arg as a list of args.
3369 Thus, (apply '+ 1 2 '(3 4)) returns 10.
3370 */
3371        (int nargs, Lisp_Object *args))
3372 {
3373   /* This function can GC */
3374   Lisp_Object fun = args[0];
3375   Lisp_Object spread_arg = args [nargs - 1];
3376   int numargs;
3377   int funcall_nargs;
3378
3379   GET_EXTERNAL_LIST_LENGTH (spread_arg, numargs);
3380
3381   if (numargs == 0)
3382     /* (apply foo 0 1 '()) */
3383     return Ffuncall (nargs - 1, args);
3384   else if (numargs == 1)
3385     {
3386       /* (apply foo 0 1 '(2)) */
3387       args [nargs - 1] = XCAR (spread_arg);
3388       return Ffuncall (nargs, args);
3389     }
3390
3391   /* -1 for function, -1 for spread arg */
3392   numargs = nargs - 2 + numargs;
3393   /* +1 for function */
3394   funcall_nargs = 1 + numargs;
3395
3396   if (SYMBOLP (fun))
3397     fun = indirect_function (fun, 0);
3398
3399   if (SUBRP (fun))
3400     {
3401       Lisp_Subr *subr = XSUBR (fun);
3402       int max_args = subr->max_args;
3403
3404       if (numargs < subr->min_args
3405           || (max_args >= 0 && max_args < numargs))
3406         {
3407           /* Let funcall get the error */
3408         }
3409       else if (max_args > numargs)
3410         {
3411           /* Avoid having funcall cons up yet another new vector of arguments
3412              by explicitly supplying nil's for optional values */
3413           funcall_nargs += (max_args - numargs);
3414         }
3415     }
3416   else if (UNBOUNDP (fun))
3417     {
3418       /* Let funcall get the error */
3419       fun = args[0];
3420     }
3421
3422   {
3423     REGISTER int i;
3424     Lisp_Object *funcall_args = alloca_array (Lisp_Object, funcall_nargs);
3425     struct gcpro gcpro1;
3426
3427     GCPRO1 (*funcall_args);
3428     gcpro1.nvars = funcall_nargs;
3429
3430     /* Copy in the unspread args */
3431     memcpy (funcall_args, args, (nargs - 1) * sizeof (Lisp_Object));
3432     /* Spread the last arg we got.  Its first element goes in
3433        the slot that it used to occupy, hence this value of I.  */
3434     for (i = nargs - 1;
3435          !NILP (spread_arg);    /* i < 1 + numargs */
3436          i++, spread_arg = XCDR (spread_arg))
3437       {
3438         funcall_args [i] = XCAR (spread_arg);
3439       }
3440     /* Supply nil for optional args (to subrs) */
3441     for (; i < funcall_nargs; i++)
3442       funcall_args[i] = Qnil;
3443
3444
3445     RETURN_UNGCPRO (Ffuncall (funcall_nargs, funcall_args));
3446   }
3447 }
3448
3449 \f
3450 /* Apply lambda list FUN to the NARGS evaluated arguments in ARGS and
3451    return the result of evaluation. */
3452
3453 static Lisp_Object
3454 funcall_lambda (Lisp_Object fun, int nargs, Lisp_Object args[])
3455 {
3456   /* This function can GC */
3457   Lisp_Object symbol, arglist, body, tail;
3458   int speccount = specpdl_depth();
3459   REGISTER int i = 0;
3460
3461   tail = XCDR (fun);
3462
3463   if (!CONSP (tail))
3464     goto invalid_function;
3465
3466   arglist = XCAR (tail);
3467   body    = XCDR (tail);
3468
3469   {
3470     int optional = 0, rest = 0;
3471
3472     EXTERNAL_LIST_LOOP_3 (symbol, arglist, tail)
3473       {
3474         if (!SYMBOLP (symbol))
3475           goto invalid_function;
3476         if (EQ (symbol, Qand_rest))
3477           rest = 1;
3478         else if (EQ (symbol, Qand_optional))
3479           optional = 1;
3480         else if (rest)
3481           {
3482             specbind (symbol, Flist (nargs - i, &args[i]));
3483             i = nargs;
3484           }
3485         else if (i < nargs)
3486           specbind (symbol, args[i++]);
3487         else if (!optional)
3488           goto wrong_number_of_arguments;
3489         else
3490           specbind (symbol, Qnil);
3491       }
3492   }
3493
3494   if (i < nargs)
3495     goto wrong_number_of_arguments;
3496
3497   return unbind_to (speccount, Fprogn (body));
3498
3499  wrong_number_of_arguments:
3500   return signal_wrong_number_of_arguments_error (fun, nargs);
3501
3502  invalid_function:
3503   return signal_invalid_function_error (fun);
3504 }
3505
3506 \f
3507 /************************************************************************/
3508 /*                   Run hook variables in various ways.                */
3509 /************************************************************************/
3510
3511 DEFUN ("run-hooks", Frun_hooks, 1, MANY, 0, /*
3512 Run each hook in HOOKS.  Major mode functions use this.
3513 Each argument should be a symbol, a hook variable.
3514 These symbols are processed in the order specified.
3515 If a hook symbol has a non-nil value, that value may be a function
3516 or a list of functions to be called to run the hook.
3517 If the value is a function, it is called with no arguments.
3518 If it is a list, the elements are called, in order, with no arguments.
3519
3520 To make a hook variable buffer-local, use `make-local-hook',
3521 not `make-local-variable'.
3522 */
3523        (int nargs, Lisp_Object *args))
3524 {
3525   REGISTER int i;
3526
3527   for (i = 0; i < nargs; i++)
3528     run_hook_with_args (1, args + i, RUN_HOOKS_TO_COMPLETION);
3529
3530   return Qnil;
3531 }
3532
3533 DEFUN ("run-hook-with-args", Frun_hook_with_args, 1, MANY, 0, /*
3534 Run HOOK with the specified arguments ARGS.
3535 HOOK should be a symbol, a hook variable.  If HOOK has a non-nil
3536 value, that value may be a function or a list of functions to be
3537 called to run the hook.  If the value is a function, it is called with
3538 the given arguments and its return value is returned.  If it is a list
3539 of functions, those functions are called, in order,
3540 with the given arguments ARGS.
3541 It is best not to depend on the value return by `run-hook-with-args',
3542 as that may change.
3543
3544 To make a hook variable buffer-local, use `make-local-hook',
3545 not `make-local-variable'.
3546 */
3547        (int nargs, Lisp_Object *args))
3548 {
3549   return run_hook_with_args (nargs, args, RUN_HOOKS_TO_COMPLETION);
3550 }
3551
3552 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success, 1, MANY, 0, /*
3553 Run HOOK with the specified arguments ARGS.
3554 HOOK should be a symbol, a hook variable.  Its value should
3555 be a list of functions.  We call those functions, one by one,
3556 passing arguments ARGS to each of them, until one of them
3557 returns a non-nil value.  Then we return that value.
3558 If all the functions return nil, we return nil.
3559
3560 To make a hook variable buffer-local, use `make-local-hook',
3561 not `make-local-variable'.
3562 */
3563        (int nargs, Lisp_Object *args))
3564 {
3565   return run_hook_with_args (nargs, args, RUN_HOOKS_UNTIL_SUCCESS);
3566 }
3567
3568 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure, 1, MANY, 0, /*
3569 Run HOOK with the specified arguments ARGS.
3570 HOOK should be a symbol, a hook variable.  Its value should
3571 be a list of functions.  We call those functions, one by one,
3572 passing arguments ARGS to each of them, until one of them
3573 returns nil.  Then we return nil.
3574 If all the functions return non-nil, we return non-nil.
3575
3576 To make a hook variable buffer-local, use `make-local-hook',
3577 not `make-local-variable'.
3578 */
3579        (int nargs, Lisp_Object *args))
3580 {
3581   return run_hook_with_args (nargs, args, RUN_HOOKS_UNTIL_FAILURE);
3582 }
3583
3584 /* ARGS[0] should be a hook symbol.
3585    Call each of the functions in the hook value, passing each of them
3586    as arguments all the rest of ARGS (all NARGS - 1 elements).
3587    COND specifies a condition to test after each call
3588    to decide whether to stop.
3589    The caller (or its caller, etc) must gcpro all of ARGS,
3590    except that it isn't necessary to gcpro ARGS[0].  */
3591
3592 Lisp_Object
3593 run_hook_with_args_in_buffer (struct buffer *buf, int nargs, Lisp_Object *args,
3594                               enum run_hooks_condition cond)
3595 {
3596   Lisp_Object sym, val, ret;
3597
3598   if (!initialized || preparing_for_armageddon)
3599     /* We need to bail out of here pronto. */
3600     return Qnil;
3601
3602   /* Whenever gc_in_progress is true, preparing_for_armageddon
3603      will also be true unless something is really hosed. */
3604   assert (!gc_in_progress);
3605
3606   sym = args[0];
3607   val = symbol_value_in_buffer (sym, make_buffer (buf));
3608   ret = (cond == RUN_HOOKS_UNTIL_FAILURE ? Qt : Qnil);
3609
3610   if (UNBOUNDP (val) || NILP (val))
3611     return ret;
3612   else if (!CONSP (val) || EQ (XCAR (val), Qlambda))
3613     {
3614       args[0] = val;
3615       return Ffuncall (nargs, args);
3616     }
3617   else
3618     {
3619       struct gcpro gcpro1, gcpro2, gcpro3;
3620       Lisp_Object globals = Qnil;
3621       GCPRO3 (sym, val, globals);
3622
3623       for (;
3624            CONSP (val) && ((cond == RUN_HOOKS_TO_COMPLETION)
3625                            || (cond == RUN_HOOKS_UNTIL_SUCCESS ? NILP (ret)
3626                                : !NILP (ret)));
3627            val = XCDR (val))
3628         {
3629           if (EQ (XCAR (val), Qt))
3630             {
3631               /* t indicates this hook has a local binding;
3632                  it means to run the global binding too.  */
3633               globals = Fdefault_value (sym);
3634
3635               if ((! CONSP (globals) || EQ (XCAR (globals), Qlambda)) &&
3636                   ! NILP (globals))
3637                 {
3638                   args[0] = globals;
3639                   ret = Ffuncall (nargs, args);
3640                 }
3641               else
3642                 {
3643                   for (;
3644                        CONSP (globals) && ((cond == RUN_HOOKS_TO_COMPLETION)
3645                                            || (cond == RUN_HOOKS_UNTIL_SUCCESS
3646                                                ? NILP (ret)
3647                                                : !NILP (ret)));
3648                        globals = XCDR (globals))
3649                     {
3650                       args[0] = XCAR (globals);
3651                       /* In a global value, t should not occur.  If it does, we
3652                          must ignore it to avoid an endless loop.  */
3653                       if (!EQ (args[0], Qt))
3654                         ret = Ffuncall (nargs, args);
3655                     }
3656                 }
3657             }
3658           else
3659             {
3660               args[0] = XCAR (val);
3661               ret = Ffuncall (nargs, args);
3662             }
3663         }
3664
3665       UNGCPRO;
3666       return ret;
3667     }
3668 }
3669
3670 Lisp_Object
3671 run_hook_with_args (int nargs, Lisp_Object *args,
3672                     enum run_hooks_condition cond)
3673 {
3674   return run_hook_with_args_in_buffer (current_buffer, nargs, args, cond);
3675 }
3676
3677 #if 0
3678
3679 /* From FSF 19.30, not currently used */
3680
3681 /* Run a hook symbol ARGS[0], but use FUNLIST instead of the actual
3682    present value of that symbol.
3683    Call each element of FUNLIST,
3684    passing each of them the rest of ARGS.
3685    The caller (or its caller, etc) must gcpro all of ARGS,
3686    except that it isn't necessary to gcpro ARGS[0].  */
3687
3688 Lisp_Object
3689 run_hook_list_with_args (Lisp_Object funlist, int nargs, Lisp_Object *args)
3690 {
3691   Lisp_Object sym = args[0];
3692   Lisp_Object val;
3693   struct gcpro gcpro1, gcpro2;
3694
3695   GCPRO2 (sym, val);
3696
3697   for (val = funlist; CONSP (val); val = XCDR (val))
3698     {
3699       if (EQ (XCAR (val), Qt))
3700         {
3701           /* t indicates this hook has a local binding;
3702              it means to run the global binding too.  */
3703           Lisp_Object globals;
3704
3705           for (globals = Fdefault_value (sym);
3706                CONSP (globals);
3707                globals = XCDR (globals))
3708             {
3709               args[0] = XCAR (globals);
3710               /* In a global value, t should not occur.  If it does, we
3711                  must ignore it to avoid an endless loop.  */
3712               if (!EQ (args[0], Qt))
3713                 Ffuncall (nargs, args);
3714             }
3715         }
3716       else
3717         {
3718           args[0] = XCAR (val);
3719           Ffuncall (nargs, args);
3720         }
3721     }
3722   UNGCPRO;
3723   return Qnil;
3724 }
3725
3726 #endif /* 0 */
3727
3728 void
3729 va_run_hook_with_args (Lisp_Object hook_var, int nargs, ...)
3730 {
3731   /* This function can GC */
3732   struct gcpro gcpro1;
3733   int i;
3734   va_list vargs;
3735   Lisp_Object *funcall_args = alloca_array (Lisp_Object, 1 + nargs);
3736
3737   va_start (vargs, nargs);
3738   funcall_args[0] = hook_var;
3739   for (i = 0; i < nargs; i++)
3740     funcall_args[i + 1] = va_arg (vargs, Lisp_Object);
3741   va_end (vargs);
3742
3743   GCPRO1 (*funcall_args);
3744   gcpro1.nvars = nargs + 1;
3745   run_hook_with_args (nargs + 1, funcall_args, RUN_HOOKS_TO_COMPLETION);
3746   UNGCPRO;
3747 }
3748
3749 void
3750 va_run_hook_with_args_in_buffer (struct buffer *buf, Lisp_Object hook_var,
3751                                  int nargs, ...)
3752 {
3753   /* This function can GC */
3754   struct gcpro gcpro1;
3755   int i;
3756   va_list vargs;
3757   Lisp_Object *funcall_args = alloca_array (Lisp_Object, 1 + nargs);
3758
3759   va_start (vargs, nargs);
3760   funcall_args[0] = hook_var;
3761   for (i = 0; i < nargs; i++)
3762     funcall_args[i + 1] = va_arg (vargs, Lisp_Object);
3763   va_end (vargs);
3764
3765   GCPRO1 (*funcall_args);
3766   gcpro1.nvars = nargs + 1;
3767   run_hook_with_args_in_buffer (buf, nargs + 1, funcall_args,
3768                                 RUN_HOOKS_TO_COMPLETION);
3769   UNGCPRO;
3770 }
3771
3772 Lisp_Object
3773 run_hook (Lisp_Object hook)
3774 {
3775   Frun_hooks (1, &hook);
3776   return Qnil;
3777 }
3778
3779 \f
3780 /************************************************************************/
3781 /*                  Front-ends to eval, funcall, apply                  */
3782 /************************************************************************/
3783
3784 /* Apply fn to arg */
3785 Lisp_Object
3786 apply1 (Lisp_Object fn, Lisp_Object arg)
3787 {
3788   /* This function can GC */
3789   struct gcpro gcpro1;
3790   Lisp_Object args[2];
3791
3792   if (NILP (arg))
3793     return Ffuncall (1, &fn);
3794   GCPRO1 (args[0]);
3795   gcpro1.nvars = 2;
3796   args[0] = fn;
3797   args[1] = arg;
3798   RETURN_UNGCPRO (Fapply (2, args));
3799 }
3800
3801 /* Call function fn on no arguments */
3802 Lisp_Object
3803 call0 (Lisp_Object fn)
3804 {
3805   /* This function can GC */
3806   struct gcpro gcpro1;
3807
3808   GCPRO1 (fn);
3809   RETURN_UNGCPRO (Ffuncall (1, &fn));
3810 }
3811
3812 /* Call function fn with argument arg0 */
3813 Lisp_Object
3814 call1 (Lisp_Object fn,
3815        Lisp_Object arg0)
3816 {
3817   /* This function can GC */
3818   struct gcpro gcpro1;
3819   Lisp_Object args[2];
3820   args[0] = fn;
3821   args[1] = arg0;
3822   GCPRO1 (args[0]);
3823   gcpro1.nvars = 2;
3824   RETURN_UNGCPRO (Ffuncall (2, args));
3825 }
3826
3827 /* Call function fn with arguments arg0, arg1 */
3828 Lisp_Object
3829 call2 (Lisp_Object fn,
3830        Lisp_Object arg0, Lisp_Object arg1)
3831 {
3832   /* This function can GC */
3833   struct gcpro gcpro1;
3834   Lisp_Object args[3];
3835   args[0] = fn;
3836   args[1] = arg0;
3837   args[2] = arg1;
3838   GCPRO1 (args[0]);
3839   gcpro1.nvars = 3;
3840   RETURN_UNGCPRO (Ffuncall (3, args));
3841 }
3842
3843 /* Call function fn with arguments arg0, arg1, arg2 */
3844 Lisp_Object
3845 call3 (Lisp_Object fn,
3846        Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2)
3847 {
3848   /* This function can GC */
3849   struct gcpro gcpro1;
3850   Lisp_Object args[4];
3851   args[0] = fn;
3852   args[1] = arg0;
3853   args[2] = arg1;
3854   args[3] = arg2;
3855   GCPRO1 (args[0]);
3856   gcpro1.nvars = 4;
3857   RETURN_UNGCPRO (Ffuncall (4, args));
3858 }
3859
3860 /* Call function fn with arguments arg0, arg1, arg2, arg3 */
3861 Lisp_Object
3862 call4 (Lisp_Object fn,
3863        Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2,
3864        Lisp_Object arg3)
3865 {
3866   /* This function can GC */
3867   struct gcpro gcpro1;
3868   Lisp_Object args[5];
3869   args[0] = fn;
3870   args[1] = arg0;
3871   args[2] = arg1;
3872   args[3] = arg2;
3873   args[4] = arg3;
3874   GCPRO1 (args[0]);
3875   gcpro1.nvars = 5;
3876   RETURN_UNGCPRO (Ffuncall (5, args));
3877 }
3878
3879 /* Call function fn with arguments arg0, arg1, arg2, arg3, arg4 */
3880 Lisp_Object
3881 call5 (Lisp_Object fn,
3882        Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2,
3883        Lisp_Object arg3, Lisp_Object arg4)
3884 {
3885   /* This function can GC */
3886   struct gcpro gcpro1;
3887   Lisp_Object args[6];
3888   args[0] = fn;
3889   args[1] = arg0;
3890   args[2] = arg1;
3891   args[3] = arg2;
3892   args[4] = arg3;
3893   args[5] = arg4;
3894   GCPRO1 (args[0]);
3895   gcpro1.nvars = 6;
3896   RETURN_UNGCPRO (Ffuncall (6, args));
3897 }
3898
3899 Lisp_Object
3900 call6 (Lisp_Object fn,
3901        Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2,
3902        Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
3903 {
3904   /* This function can GC */
3905   struct gcpro gcpro1;
3906   Lisp_Object args[7];
3907   args[0] = fn;
3908   args[1] = arg0;
3909   args[2] = arg1;
3910   args[3] = arg2;
3911   args[4] = arg3;
3912   args[5] = arg4;
3913   args[6] = arg5;
3914   GCPRO1 (args[0]);
3915   gcpro1.nvars = 7;
3916   RETURN_UNGCPRO (Ffuncall (7, args));
3917 }
3918
3919 Lisp_Object
3920 call7 (Lisp_Object fn,
3921        Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2,
3922        Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5,
3923        Lisp_Object arg6)
3924 {
3925   /* This function can GC */
3926   struct gcpro gcpro1;
3927   Lisp_Object args[8];
3928   args[0] = fn;
3929   args[1] = arg0;
3930   args[2] = arg1;
3931   args[3] = arg2;
3932   args[4] = arg3;
3933   args[5] = arg4;
3934   args[6] = arg5;
3935   args[7] = arg6;
3936   GCPRO1 (args[0]);
3937   gcpro1.nvars = 8;
3938   RETURN_UNGCPRO (Ffuncall (8, args));
3939 }
3940
3941 Lisp_Object
3942 call8 (Lisp_Object fn,
3943        Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2,
3944        Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5,
3945        Lisp_Object arg6, Lisp_Object arg7)
3946 {
3947   /* This function can GC */
3948   struct gcpro gcpro1;
3949   Lisp_Object args[9];
3950   args[0] = fn;
3951   args[1] = arg0;
3952   args[2] = arg1;
3953   args[3] = arg2;
3954   args[4] = arg3;
3955   args[5] = arg4;
3956   args[6] = arg5;
3957   args[7] = arg6;
3958   args[8] = arg7;
3959   GCPRO1 (args[0]);
3960   gcpro1.nvars = 9;
3961   RETURN_UNGCPRO (Ffuncall (9, args));
3962 }
3963
3964 Lisp_Object
3965 call0_in_buffer (struct buffer *buf, Lisp_Object fn)
3966 {
3967   if (current_buffer == buf)
3968     return call0 (fn);
3969   else
3970     {
3971       Lisp_Object val;
3972       int speccount = specpdl_depth();
3973       record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3974       set_buffer_internal (buf);
3975       val = call0 (fn);
3976       unbind_to (speccount, Qnil);
3977       return val;
3978     }
3979 }
3980
3981 Lisp_Object
3982 call1_in_buffer (struct buffer *buf, Lisp_Object fn,
3983                  Lisp_Object arg0)
3984 {
3985   if (current_buffer == buf)
3986     return call1 (fn, arg0);
3987   else
3988     {
3989       Lisp_Object val;
3990       int speccount = specpdl_depth();
3991       record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
3992       set_buffer_internal (buf);
3993       val = call1 (fn, arg0);
3994       unbind_to (speccount, Qnil);
3995       return val;
3996     }
3997 }
3998
3999 Lisp_Object
4000 call2_in_buffer (struct buffer *buf, Lisp_Object fn,
4001                  Lisp_Object arg0, Lisp_Object arg1)
4002 {
4003   if (current_buffer == buf)
4004     return call2 (fn, arg0, arg1);
4005   else
4006     {
4007       Lisp_Object val;
4008       int speccount = specpdl_depth();
4009       record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4010       set_buffer_internal (buf);
4011       val = call2 (fn, arg0, arg1);
4012       unbind_to (speccount, Qnil);
4013       return val;
4014     }
4015 }
4016
4017 Lisp_Object
4018 call3_in_buffer (struct buffer *buf, Lisp_Object fn,
4019                  Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2)
4020 {
4021   if (current_buffer == buf)
4022     return call3 (fn, arg0, arg1, arg2);
4023   else
4024     {
4025       Lisp_Object val;
4026       int speccount = specpdl_depth();
4027       record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4028       set_buffer_internal (buf);
4029       val = call3 (fn, arg0, arg1, arg2);
4030       unbind_to (speccount, Qnil);
4031       return val;
4032     }
4033 }
4034
4035 Lisp_Object
4036 call4_in_buffer (struct buffer *buf, Lisp_Object fn,
4037                  Lisp_Object arg0, Lisp_Object arg1, Lisp_Object arg2,
4038                  Lisp_Object arg3)
4039 {
4040   if (current_buffer == buf)
4041     return call4 (fn, arg0, arg1, arg2, arg3);
4042   else
4043     {
4044       Lisp_Object val;
4045       int speccount = specpdl_depth();
4046       record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4047       set_buffer_internal (buf);
4048       val = call4 (fn, arg0, arg1, arg2, arg3);
4049       unbind_to (speccount, Qnil);
4050       return val;
4051     }
4052 }
4053
4054 Lisp_Object
4055 eval_in_buffer (struct buffer *buf, Lisp_Object form)
4056 {
4057   if (current_buffer == buf)
4058     return Feval (form);
4059   else
4060     {
4061       Lisp_Object val;
4062       int speccount = specpdl_depth();
4063       record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
4064       set_buffer_internal (buf);
4065       val = Feval (form);
4066       unbind_to (speccount, Qnil);
4067       return val;
4068     }
4069 }
4070
4071 \f
4072 /************************************************************************/
4073 /*         Error-catching front-ends to eval, funcall, apply            */
4074 /************************************************************************/
4075
4076 /* Call function fn on no arguments, with condition handler */
4077 Lisp_Object
4078 call0_with_handler (Lisp_Object handler, Lisp_Object fn)
4079 {
4080   /* This function can GC */
4081   struct gcpro gcpro1;
4082   Lisp_Object args[2];
4083   args[0] = handler;
4084   args[1] = fn;
4085   GCPRO1 (args[0]);
4086   gcpro1.nvars = 2;
4087   RETURN_UNGCPRO (Fcall_with_condition_handler (2, args));
4088 }
4089
4090 /* Call function fn with argument arg0, with condition handler */
4091 Lisp_Object
4092 call1_with_handler (Lisp_Object handler, Lisp_Object fn,
4093                     Lisp_Object arg0)
4094 {
4095   /* This function can GC */
4096   struct gcpro gcpro1;
4097   Lisp_Object args[3];
4098   args[0] = handler;
4099   args[1] = fn;
4100   args[2] = arg0;
4101   GCPRO1 (args[0]);
4102   gcpro1.nvars = 3;
4103   RETURN_UNGCPRO (Fcall_with_condition_handler (3, args));
4104 }
4105
4106 \f
4107 /* The following functions provide you with error-trapping versions
4108    of the various front-ends above.  They take an additional
4109    "warning_string" argument; if non-zero, a warning with this
4110    string and the actual error that occurred will be displayed
4111    in the *Warnings* buffer if an error occurs.  In all cases,
4112    QUIT is inhibited while these functions are running, and if
4113    an error occurs, Qunbound is returned instead of the normal
4114    return value.
4115    */
4116
4117 /* #### This stuff needs to catch throws as well.  We need to
4118    improve internal_catch() so it can take a "catch anything"
4119    argument similar to Qt or Qerror for condition_case_1(). */
4120
4121 static Lisp_Object
4122 caught_a_squirmer (Lisp_Object errordata, Lisp_Object arg)
4123 {
4124   if (!NILP (errordata))
4125     {
4126       Lisp_Object args[2];
4127
4128       if (!NILP (arg))
4129         {
4130           char *str = (char *) get_opaque_ptr (arg);
4131           args[0] = build_string (str);
4132         }
4133       else
4134         args[0] = build_string ("error");
4135       /* #### This should call
4136          (with-output-to-string (display-error errordata))
4137          but that stuff is all in Lisp currently. */
4138       args[1] = errordata;
4139       warn_when_safe_lispobj
4140         (Qerror, Qwarning,
4141          emacs_doprnt_string_lisp ((const Bufbyte *) "%s: %s",
4142                                    Qnil, -1, 2, args));
4143     }
4144   return Qunbound;
4145 }
4146
4147 static Lisp_Object
4148 allow_quit_caught_a_squirmer (Lisp_Object errordata, Lisp_Object arg)
4149 {
4150   if (CONSP (errordata) && EQ (XCAR (errordata), Qquit))
4151     return Fsignal (Qquit, XCDR (errordata));
4152   return caught_a_squirmer (errordata, arg);
4153 }
4154
4155 static Lisp_Object
4156 safe_run_hook_caught_a_squirmer (Lisp_Object errordata, Lisp_Object arg)
4157 {
4158   Lisp_Object hook = Fcar (arg);
4159   arg = Fcdr (arg);
4160   /* Clear out the hook. */
4161   Fset (hook, Qnil);
4162   return caught_a_squirmer (errordata, arg);
4163 }
4164
4165 static Lisp_Object
4166 allow_quit_safe_run_hook_caught_a_squirmer (Lisp_Object errordata,
4167                                             Lisp_Object arg)
4168 {
4169   Lisp_Object hook = Fcar (arg);
4170   arg = Fcdr (arg);
4171   if (!CONSP (errordata) || !EQ (XCAR (errordata), Qquit))
4172     /* Clear out the hook. */
4173     Fset (hook, Qnil);
4174   return allow_quit_caught_a_squirmer (errordata, arg);
4175 }
4176
4177 static Lisp_Object
4178 catch_them_squirmers_eval_in_buffer (Lisp_Object cons)
4179 {
4180   return eval_in_buffer (XBUFFER (XCAR (cons)), XCDR (cons));
4181 }
4182
4183 Lisp_Object
4184 eval_in_buffer_trapping_errors (const char *warning_string,
4185                                 struct buffer *buf, Lisp_Object form)
4186 {
4187   int speccount = specpdl_depth();
4188   Lisp_Object tem;
4189   Lisp_Object buffer;
4190   Lisp_Object cons;
4191   Lisp_Object opaque;
4192   struct gcpro gcpro1, gcpro2;
4193
4194   XSETBUFFER (buffer, buf);
4195
4196   specbind (Qinhibit_quit, Qt);
4197   /* gc_currently_forbidden = 1; Currently no reason to do this; */
4198
4199   cons = noseeum_cons (buffer, form);
4200   opaque = (warning_string ? make_opaque_ptr ((void *)warning_string) : Qnil);
4201   GCPRO2 (cons, opaque);
4202   /* Qerror not Qt, so you can get a backtrace */
4203   tem = condition_case_1 (Qerror,
4204                           catch_them_squirmers_eval_in_buffer, cons,
4205                           caught_a_squirmer, opaque);
4206   free_cons (XCONS (cons));
4207   if (OPAQUE_PTRP (opaque))
4208     free_opaque_ptr (opaque);
4209   UNGCPRO;
4210
4211   /* gc_currently_forbidden = 0; */
4212   return unbind_to (speccount, tem);
4213 }
4214
4215 static Lisp_Object
4216 catch_them_squirmers_run_hook (Lisp_Object hook_symbol)
4217 {
4218   /* This function can GC */
4219   run_hook (hook_symbol);
4220   return Qnil;
4221 }
4222
4223 Lisp_Object
4224 run_hook_trapping_errors (const char *warning_string, Lisp_Object hook_symbol)
4225 {
4226   int speccount;
4227   Lisp_Object tem;
4228   Lisp_Object opaque;
4229   struct gcpro gcpro1;
4230
4231   if (!initialized || preparing_for_armageddon)
4232     return Qnil;
4233   tem = find_symbol_value (hook_symbol);
4234   if (NILP (tem) || UNBOUNDP (tem))
4235     return Qnil;
4236
4237   speccount = specpdl_depth();
4238   specbind (Qinhibit_quit, Qt);
4239
4240   opaque = (warning_string ? make_opaque_ptr ((void *)warning_string) : Qnil);
4241   GCPRO1 (opaque);
4242   /* Qerror not Qt, so you can get a backtrace */
4243   tem = condition_case_1 (Qerror,
4244                           catch_them_squirmers_run_hook, hook_symbol,
4245                           caught_a_squirmer, opaque);
4246   if (OPAQUE_PTRP (opaque))
4247     free_opaque_ptr (opaque);
4248   UNGCPRO;
4249
4250   return unbind_to (speccount, tem);
4251 }
4252
4253 /* Same as run_hook_trapping_errors() but also set the hook to nil
4254    if an error occurs. */
4255
4256 Lisp_Object
4257 safe_run_hook_trapping_errors (const char *warning_string,
4258                                Lisp_Object hook_symbol,
4259                                int allow_quit)
4260 {
4261   int speccount = specpdl_depth();
4262   Lisp_Object tem;
4263   Lisp_Object cons = Qnil;
4264   struct gcpro gcpro1;
4265
4266   if (!initialized || preparing_for_armageddon)
4267     return Qnil;
4268   tem = find_symbol_value (hook_symbol);
4269   if (NILP (tem) || UNBOUNDP (tem))
4270     return Qnil;
4271
4272   if (!allow_quit)
4273     specbind (Qinhibit_quit, Qt);
4274
4275   cons = noseeum_cons (hook_symbol,
4276                        warning_string ? make_opaque_ptr ((void *)warning_string)
4277                        : Qnil);
4278   GCPRO1 (cons);
4279   /* Qerror not Qt, so you can get a backtrace */
4280   tem = condition_case_1 (Qerror,
4281                           catch_them_squirmers_run_hook,
4282                           hook_symbol,
4283                           allow_quit ?
4284                           allow_quit_safe_run_hook_caught_a_squirmer :
4285                           safe_run_hook_caught_a_squirmer,
4286                           cons);
4287   if (OPAQUE_PTRP (XCDR (cons)))
4288     free_opaque_ptr (XCDR (cons));
4289   free_cons (XCONS (cons));
4290   UNGCPRO;
4291
4292   return unbind_to (speccount, tem);
4293 }
4294
4295 static Lisp_Object
4296 catch_them_squirmers_call0 (Lisp_Object function)
4297 {
4298   /* This function can GC */
4299   return call0 (function);
4300 }
4301
4302 Lisp_Object
4303 call0_trapping_errors (const char *warning_string, Lisp_Object function)
4304 {
4305   int speccount;
4306   Lisp_Object tem;
4307   Lisp_Object opaque = Qnil;
4308   struct gcpro gcpro1, gcpro2;
4309
4310   if (SYMBOLP (function))
4311     {
4312       tem = XSYMBOL (function)->function;
4313       if (NILP (tem) || UNBOUNDP (tem))
4314         return Qnil;
4315     }
4316
4317   GCPRO2 (opaque, function);
4318   speccount = specpdl_depth();
4319   specbind (Qinhibit_quit, Qt);
4320   /* gc_currently_forbidden = 1; Currently no reason to do this; */
4321
4322   opaque = (warning_string ? make_opaque_ptr ((void *)warning_string) : Qnil);
4323   /* Qerror not Qt, so you can get a backtrace */
4324   tem = condition_case_1 (Qerror,
4325                           catch_them_squirmers_call0, function,
4326                           caught_a_squirmer, opaque);
4327   if (OPAQUE_PTRP (opaque))
4328     free_opaque_ptr (opaque);
4329   UNGCPRO;
4330
4331   /* gc_currently_forbidden = 0; */
4332   return unbind_to (speccount, tem);
4333 }
4334
4335 static Lisp_Object
4336 catch_them_squirmers_call1 (Lisp_Object cons)
4337 {
4338   /* This function can GC */
4339   return call1 (XCAR (cons), XCDR (cons));
4340 }
4341
4342 static Lisp_Object
4343 catch_them_squirmers_call2 (Lisp_Object cons)
4344 {
4345   /* This function can GC */
4346   return call2 (XCAR (cons), XCAR (XCDR (cons)), XCAR (XCDR (XCDR (cons))));
4347 }
4348
4349 Lisp_Object
4350 call1_trapping_errors (const char *warning_string, Lisp_Object function,
4351                        Lisp_Object object)
4352 {
4353   int speccount = specpdl_depth();
4354   Lisp_Object tem;
4355   Lisp_Object cons = Qnil;
4356   Lisp_Object opaque = Qnil;
4357   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4358
4359   if (SYMBOLP (function))
4360     {
4361       tem = XSYMBOL (function)->function;
4362       if (NILP (tem) || UNBOUNDP (tem))
4363         return Qnil;
4364     }
4365
4366   GCPRO4 (cons, opaque, function, object);
4367
4368   specbind (Qinhibit_quit, Qt);
4369   /* gc_currently_forbidden = 1; Currently no reason to do this; */
4370
4371   cons = noseeum_cons (function, object);
4372   opaque = (warning_string ? make_opaque_ptr ((void *)warning_string) : Qnil);
4373   /* Qerror not Qt, so you can get a backtrace */
4374   tem = condition_case_1 (Qerror,
4375                           catch_them_squirmers_call1, cons,
4376                           caught_a_squirmer, opaque);
4377   if (OPAQUE_PTRP (opaque))
4378     free_opaque_ptr (opaque);
4379   free_cons (XCONS (cons));
4380   UNGCPRO;
4381
4382   /* gc_currently_forbidden = 0; */
4383   return unbind_to (speccount, tem);
4384 }
4385
4386 Lisp_Object
4387 call2_trapping_errors (const char *warning_string, Lisp_Object function,
4388                        Lisp_Object object1, Lisp_Object object2)
4389 {
4390   int speccount = specpdl_depth();
4391   Lisp_Object tem;
4392   Lisp_Object cons = Qnil;
4393   Lisp_Object opaque = Qnil;
4394   struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
4395
4396   if (SYMBOLP (function))
4397     {
4398       tem = XSYMBOL (function)->function;
4399       if (NILP (tem) || UNBOUNDP (tem))
4400         return Qnil;
4401     }
4402
4403   GCPRO5 (cons, opaque, function, object1, object2);
4404   specbind (Qinhibit_quit, Qt);
4405   /* gc_currently_forbidden = 1; Currently no reason to do this; */
4406
4407   cons = list3 (function, object1, object2);
4408   opaque = (warning_string ? make_opaque_ptr ((void *)warning_string) : Qnil);
4409   /* Qerror not Qt, so you can get a backtrace */
4410   tem = condition_case_1 (Qerror,
4411                           catch_them_squirmers_call2, cons,
4412                           caught_a_squirmer, opaque);
4413   if (OPAQUE_PTRP (opaque))
4414     free_opaque_ptr (opaque);
4415   free_list (cons);
4416   UNGCPRO;
4417
4418   /* gc_currently_forbidden = 0; */
4419   return unbind_to (speccount, tem);
4420 }
4421
4422 \f
4423 /************************************************************************/
4424 /*                     The special binding stack                        */
4425 /* Most C code should simply use specbind() and unbind_to().            */
4426 /* When performance is critical, use the macros in backtrace.h.         */
4427 /************************************************************************/
4428
4429 #define min_max_specpdl_size 400
4430
4431 void
4432 grow_specpdl (size_t reserved)
4433 {
4434   size_t size_needed = specpdl_depth() + reserved;
4435   if (size_needed >= max_specpdl_size)
4436     {
4437       if (max_specpdl_size < min_max_specpdl_size)
4438         max_specpdl_size = min_max_specpdl_size;
4439       if (size_needed >= max_specpdl_size)
4440         {
4441           if (!NILP (Vdebug_on_error) ||
4442               !NILP (Vdebug_on_signal))
4443             /* Leave room for some specpdl in the debugger.  */
4444             max_specpdl_size = size_needed + 100;
4445           continuable_error
4446             ("Variable binding depth exceeds max-specpdl-size");
4447         }
4448     }
4449   while (specpdl_size < size_needed)
4450     {
4451       specpdl_size *= 2;
4452       if (specpdl_size > max_specpdl_size)
4453         specpdl_size = max_specpdl_size;
4454     }
4455   XREALLOC_ARRAY (specpdl, struct specbinding, specpdl_size);
4456   specpdl_ptr = specpdl + specpdl_depth();
4457 }
4458
4459
4460 /* Handle unbinding buffer-local variables */
4461 static Lisp_Object
4462 specbind_unwind_local (Lisp_Object ovalue)
4463 {
4464   Lisp_Object current = Fcurrent_buffer ();
4465   Lisp_Object symbol = specpdl_ptr->symbol;
4466   Lisp_Cons *victim = XCONS (ovalue);
4467   Lisp_Object buf = get_buffer (victim->car, 0);
4468   ovalue = victim->cdr;
4469
4470   free_cons (victim);
4471
4472   if (NILP (buf))
4473     {
4474       /* Deleted buffer -- do nothing */
4475     }
4476   else if (symbol_value_buffer_local_info (symbol, XBUFFER (buf)) == 0)
4477     {
4478       /* Was buffer-local when binding was made, now no longer is.
4479        *  (kill-local-variable can do this.)
4480        * Do nothing in this case.
4481        */
4482     }
4483   else if (EQ (buf, current))
4484     Fset (symbol, ovalue);
4485   else
4486   {
4487     /* Urk! Somebody switched buffers */
4488     struct gcpro gcpro1;
4489     GCPRO1 (current);
4490     Fset_buffer (buf);
4491     Fset (symbol, ovalue);
4492     Fset_buffer (current);
4493     UNGCPRO;
4494   }
4495   return symbol;
4496 }
4497
4498 static Lisp_Object
4499 specbind_unwind_wasnt_local (Lisp_Object buffer)
4500 {
4501   Lisp_Object current = Fcurrent_buffer ();
4502   Lisp_Object symbol = specpdl_ptr->symbol;
4503
4504   buffer = get_buffer (buffer, 0);
4505   if (NILP (buffer))
4506     {
4507       /* Deleted buffer -- do nothing */
4508     }
4509   else if (symbol_value_buffer_local_info (symbol, XBUFFER (buffer)) == 0)
4510     {
4511       /* Was buffer-local when binding was made, now no longer is.
4512        *  (kill-local-variable can do this.)
4513        * Do nothing in this case.
4514        */
4515     }
4516   else if (EQ (buffer, current))
4517     Fkill_local_variable (symbol);
4518   else
4519     {
4520       /* Urk! Somebody switched buffers */
4521       struct gcpro gcpro1;
4522       GCPRO1 (current);
4523       Fset_buffer (buffer);
4524       Fkill_local_variable (symbol);
4525       Fset_buffer (current);
4526       UNGCPRO;
4527     }
4528   return symbol;
4529 }
4530
4531
4532 void
4533 specbind (Lisp_Object symbol, Lisp_Object value)
4534 {
4535   SPECBIND (symbol, value);
4536 }
4537
4538 void
4539 specbind_magic (Lisp_Object symbol, Lisp_Object value)
4540 {
4541   int buffer_local =
4542     symbol_value_buffer_local_info (symbol, current_buffer);
4543
4544   if (buffer_local == 0)
4545     {
4546       specpdl_ptr->old_value = find_symbol_value (symbol);
4547       specpdl_ptr->func = 0;      /* Handled specially by unbind_to */
4548     }
4549   else if (buffer_local > 0)
4550     {
4551       /* Already buffer-local */
4552       specpdl_ptr->old_value = noseeum_cons (Fcurrent_buffer (),
4553                                              find_symbol_value (symbol));
4554       specpdl_ptr->func = specbind_unwind_local;
4555     }
4556   else
4557     {
4558       /* About to become buffer-local */
4559       specpdl_ptr->old_value = Fcurrent_buffer ();
4560       specpdl_ptr->func = specbind_unwind_wasnt_local;
4561     }
4562
4563   specpdl_ptr->symbol = symbol;
4564   specpdl_ptr++;
4565   specpdl_depth_counter++;
4566
4567   Fset (symbol, value);
4568 }
4569
4570 void
4571 record_unwind_protect (Lisp_Object (*function) (Lisp_Object arg),
4572                        Lisp_Object arg)
4573 {
4574   SPECPDL_RESERVE (1);
4575   specpdl_ptr->func = function;
4576   specpdl_ptr->symbol = Qnil;
4577   specpdl_ptr->old_value = arg;
4578   specpdl_ptr++;
4579   specpdl_depth_counter++;
4580 }
4581
4582 extern int check_sigio (void);
4583
4584 /* Unwind the stack till specpdl_depth() == COUNT.
4585    VALUE is not used, except that, purely as a convenience to the
4586    caller, it is protected from garbage-protection. */
4587 Lisp_Object
4588 unbind_to (int count, Lisp_Object value)
4589 {
4590   UNBIND_TO_GCPRO (count, value);
4591   return value;
4592 }
4593
4594 /* Don't call this directly.
4595    Only for use by UNBIND_TO* macros in backtrace.h */
4596 void
4597 unbind_to_hairy (int count)
4598 {
4599   int quitf;
4600
4601   check_quit (); /* make Vquit_flag accurate */
4602   quitf = !NILP (Vquit_flag);
4603   Vquit_flag = Qnil;
4604
4605   ++specpdl_ptr;
4606   ++specpdl_depth_counter;
4607
4608   while (specpdl_depth_counter != count)
4609     {
4610       --specpdl_ptr;
4611       --specpdl_depth_counter;
4612
4613       if (specpdl_ptr->func != 0)
4614         /* An unwind-protect */
4615         (*specpdl_ptr->func) (specpdl_ptr->old_value);
4616       else
4617         {
4618           /* We checked symbol for validity when we specbound it,
4619              so only need to call Fset if symbol has magic value.  */
4620           Lisp_Symbol *sym = XSYMBOL (specpdl_ptr->symbol);
4621           if (!SYMBOL_VALUE_MAGIC_P (sym->value))
4622             sym->value = specpdl_ptr->old_value;
4623           else
4624             Fset (specpdl_ptr->symbol, specpdl_ptr->old_value);
4625         }
4626
4627 #if 0 /* martin */
4628 #ifndef EXCEEDINGLY_QUESTIONABLE_CODE
4629       /* There should never be anything here for us to remove.
4630          If so, it indicates a logic error in Emacs.  Catches
4631          should get removed when a throw or signal occurs, or
4632          when a catch or condition-case exits normally.  But
4633          it's too dangerous to just remove this code. --ben */
4634
4635       /* Furthermore, this code is not in FSFmacs!!!
4636          Braino on mly's part? */
4637       /* If we're unwound past the pdlcount of a catch frame,
4638          that catch can't possibly still be valid. */
4639       while (catchlist && catchlist->pdlcount > specpdl_depth_counter)
4640         {
4641           catchlist = catchlist->next;
4642           /* Don't mess with gcprolist, backtrace_list here */
4643         }
4644 #endif
4645 #endif
4646     }
4647   if (quitf)
4648     Vquit_flag = Qt;
4649 }
4650
4651 \f
4652
4653 /* Get the value of symbol's global binding, even if that binding is
4654    not now dynamically visible.  May return Qunbound or magic values. */
4655
4656 Lisp_Object
4657 top_level_value (Lisp_Object symbol)
4658 {
4659   REGISTER struct specbinding *ptr = specpdl;
4660
4661   CHECK_SYMBOL (symbol);
4662   for (; ptr != specpdl_ptr; ptr++)
4663     {
4664       if (EQ (ptr->symbol, symbol))
4665         return ptr->old_value;
4666     }
4667   return XSYMBOL (symbol)->value;
4668 }
4669
4670 #if 0
4671
4672 Lisp_Object
4673 top_level_set (Lisp_Object symbol, Lisp_Object newval)
4674 {
4675   REGISTER struct specbinding *ptr = specpdl;
4676
4677   CHECK_SYMBOL (symbol);
4678   for (; ptr != specpdl_ptr; ptr++)
4679     {
4680       if (EQ (ptr->symbol, symbol))
4681         {
4682           ptr->old_value = newval;
4683           return newval;
4684         }
4685     }
4686   return Fset (symbol, newval);
4687 }
4688
4689 #endif /* 0 */
4690
4691 \f
4692 /************************************************************************/
4693 /*                            Backtraces                                */
4694 /************************************************************************/
4695
4696 DEFUN ("backtrace-debug", Fbacktrace_debug, 2, 2, 0, /*
4697 Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
4698 The debugger is entered when that frame exits, if the flag is non-nil.
4699 */
4700        (level, flag))
4701 {
4702   REGISTER struct backtrace *backlist = backtrace_list;
4703   REGISTER int i;
4704
4705   CHECK_INT (level);
4706
4707   for (i = 0; backlist && i < XINT (level); i++)
4708     {
4709       backlist = backlist->next;
4710     }
4711
4712   if (backlist)
4713     backlist->debug_on_exit = !NILP (flag);
4714
4715   return flag;
4716 }
4717
4718 static void
4719 backtrace_specials (int speccount, int speclimit, Lisp_Object stream)
4720 {
4721   int printing_bindings = 0;
4722
4723   for (; speccount > speclimit; speccount--)
4724     {
4725       if (specpdl[speccount - 1].func == 0
4726           || specpdl[speccount - 1].func == specbind_unwind_local
4727           || specpdl[speccount - 1].func == specbind_unwind_wasnt_local)
4728         {
4729           write_c_string (((!printing_bindings) ? "  # bind (" : " "),
4730                           stream);
4731           Fprin1 (specpdl[speccount - 1].symbol, stream);
4732           printing_bindings = 1;
4733         }
4734       else
4735         {
4736           if (printing_bindings) write_c_string (")\n", stream);
4737           write_c_string ("  # (unwind-protect ...)\n", stream);
4738           printing_bindings = 0;
4739         }
4740     }
4741   if (printing_bindings) write_c_string (")\n", stream);
4742 }
4743
4744 DEFUN ("backtrace", Fbacktrace, 0, 2, "", /*
4745 Print a trace of Lisp function calls currently active.
4746 Optional arg STREAM specifies the output stream to send the backtrace to,
4747 and defaults to the value of `standard-output'.  Optional second arg
4748 DETAILED means show places where currently active variable bindings,
4749 catches, condition-cases, and unwind-protects were made as well as
4750 function calls.
4751 */
4752        (stream, detailed))
4753 {
4754   /* This function can GC */
4755   struct backtrace *backlist = backtrace_list;
4756   struct catchtag *catches = catchlist;
4757   int speccount = specpdl_depth();
4758
4759   int old_nl = print_escape_newlines;
4760   int old_pr = print_readably;
4761   Lisp_Object old_level = Vprint_level;
4762   Lisp_Object oiq = Vinhibit_quit;
4763   struct gcpro gcpro1, gcpro2;
4764
4765   /* We can't allow quits in here because that could cause the values
4766      of print_readably and print_escape_newlines to get screwed up.
4767      Normally we would use a record_unwind_protect but that would
4768      screw up the functioning of this function. */
4769   Vinhibit_quit = Qt;
4770
4771   entering_debugger = 0;
4772
4773   Vprint_level = make_int (3);
4774   print_readably = 0;
4775   print_escape_newlines = 1;
4776
4777   GCPRO2 (stream, old_level);
4778
4779   if (NILP (stream))
4780     stream = Vstandard_output;
4781   if (!noninteractive && (NILP (stream) || EQ (stream, Qt)))
4782     stream = Fselected_frame (Qnil);
4783
4784   for (;;)
4785     {
4786       if (!NILP (detailed) && catches && catches->backlist == backlist)
4787         {
4788           int catchpdl = catches->pdlcount;
4789           if (speccount > catchpdl
4790               && specpdl[catchpdl].func == condition_case_unwind)
4791             /* This is a condition-case catchpoint */
4792             catchpdl = catchpdl + 1;
4793
4794           backtrace_specials (speccount, catchpdl, stream);
4795
4796           speccount = catches->pdlcount;
4797           if (catchpdl == speccount)
4798             {
4799               write_c_string ("  # (catch ", stream);
4800               Fprin1 (catches->tag, stream);
4801               write_c_string (" ...)\n", stream);
4802             }
4803           else
4804             {
4805               write_c_string ("  # (condition-case ... . ", stream);
4806               Fprin1 (Fcdr (Fcar (catches->tag)), stream);
4807               write_c_string (")\n", stream);
4808             }
4809           catches = catches->next;
4810         }
4811       else if (!backlist)
4812         break;
4813       else
4814         {
4815           if (!NILP (detailed) && backlist->pdlcount < speccount)
4816             {
4817               backtrace_specials (speccount, backlist->pdlcount, stream);
4818               speccount = backlist->pdlcount;
4819             }
4820           write_c_string (((backlist->debug_on_exit) ? "* " : "  "),
4821                           stream);
4822           if (backlist->nargs == UNEVALLED)
4823             {
4824               Fprin1 (Fcons (*backlist->function, *backlist->args), stream);
4825               write_c_string ("\n", stream); /* from FSFmacs 19.30 */
4826             }
4827           else
4828             {
4829               Lisp_Object tem = *backlist->function;
4830               Fprin1 (tem, stream); /* This can QUIT */
4831               write_c_string ("(", stream);
4832               if (backlist->nargs == MANY)
4833                 {
4834                   int i;
4835                   Lisp_Object tail = Qnil;
4836                   struct gcpro ngcpro1;
4837
4838                   NGCPRO1 (tail);
4839                   for (tail = *backlist->args, i = 0;
4840                        !NILP (tail);
4841                        tail = Fcdr (tail), i++)
4842                     {
4843                       if (i != 0) write_c_string (" ", stream);
4844                       Fprin1 (Fcar (tail), stream);
4845                     }
4846                   NUNGCPRO;
4847                 }
4848               else
4849                 {
4850                   int i;
4851                   for (i = 0; i < backlist->nargs; i++)
4852                     {
4853                       if (!i && EQ(tem, Qbyte_code)) {
4854                         write_c_string("\"...\"", stream);
4855                         continue;
4856                       }
4857                       if (i != 0) write_c_string (" ", stream);
4858                       Fprin1 (backlist->args[i], stream);
4859                     }
4860                 }
4861             }
4862           write_c_string (")\n", stream);
4863           backlist = backlist->next;
4864         }
4865     }
4866   Vprint_level = old_level;
4867   print_readably = old_pr;
4868   print_escape_newlines = old_nl;
4869   UNGCPRO;
4870   Vinhibit_quit = oiq;
4871   return Qnil;
4872 }
4873
4874
4875 DEFUN ("backtrace-frame", Fbacktrace_frame, 1, 1, "", /*
4876 Return the function and arguments N frames up from current execution point.
4877 If that frame has not evaluated the arguments yet (or is a special form),
4878 the value is (nil FUNCTION ARG-FORMS...).
4879 If that frame has evaluated its arguments and called its function already,
4880 the value is (t FUNCTION ARG-VALUES...).
4881 A &rest arg is represented as the tail of the list ARG-VALUES.
4882 FUNCTION is whatever was supplied as car of evaluated list,
4883 or a lambda expression for macro calls.
4884 If N is more than the number of frames, the value is nil.
4885 */
4886        (nframes))
4887 {
4888   REGISTER struct backtrace *backlist = backtrace_list;
4889   REGISTER int i;
4890   Lisp_Object tem;
4891
4892   CHECK_NATNUM (nframes);
4893
4894   /* Find the frame requested.  */
4895   for (i = XINT (nframes); backlist && (i-- > 0);)
4896     backlist = backlist->next;
4897
4898   if (!backlist)
4899     return Qnil;
4900   if (backlist->nargs == UNEVALLED)
4901     return Fcons (Qnil, Fcons (*backlist->function, *backlist->args));
4902   else
4903     {
4904       if (backlist->nargs == MANY)
4905         tem = *backlist->args;
4906       else
4907         tem = Flist (backlist->nargs, backlist->args);
4908
4909       return Fcons (Qt, Fcons (*backlist->function, tem));
4910     }
4911 }
4912
4913 \f
4914 /************************************************************************/
4915 /*                            Warnings                                  */
4916 /************************************************************************/
4917
4918 void
4919 warn_when_safe_lispobj (Lisp_Object class, Lisp_Object level,
4920                         Lisp_Object obj)
4921 {
4922   obj = list1 (list3 (class, level, obj));
4923   if (NILP (Vpending_warnings))
4924     Vpending_warnings = Vpending_warnings_tail = obj;
4925   else
4926     {
4927       Fsetcdr (Vpending_warnings_tail, obj);
4928       Vpending_warnings_tail = obj;
4929     }
4930 }
4931
4932 /* #### This should probably accept Lisp objects; but then we have
4933    to make sure that Feval() isn't called, since it might not be safe.
4934
4935    An alternative approach is to just pass some non-string type of
4936    Lisp_Object to warn_when_safe_lispobj(); `prin1-to-string' will
4937    automatically be called when it is safe to do so. */
4938
4939 void
4940 warn_when_safe (Lisp_Object class, Lisp_Object level, const char *fmt, ...)
4941 {
4942   Lisp_Object obj;
4943   va_list args;
4944
4945   va_start (args, fmt);
4946   obj = emacs_doprnt_string_va ((const Bufbyte *) GETTEXT (fmt),
4947                                 Qnil, -1, args);
4948   va_end (args);
4949
4950   warn_when_safe_lispobj (class, level, obj);
4951 }
4952
4953
4954
4955 \f
4956 /************************************************************************/
4957 /*                          Initialization                              */
4958 /************************************************************************/
4959
4960 void
4961 syms_of_eval (void)
4962 {
4963   defsymbol (&Qinhibit_quit, "inhibit-quit");
4964   defsymbol (&Qautoload, "autoload");
4965   defsymbol (&Qdebug_on_error, "debug-on-error");
4966   defsymbol (&Qstack_trace_on_error, "stack-trace-on-error");
4967   defsymbol (&Qdebug_on_signal, "debug-on-signal");
4968   defsymbol (&Qstack_trace_on_signal, "stack-trace-on-signal");
4969   defsymbol (&Qdebugger, "debugger");
4970   defsymbol (&Qmacro, "macro");
4971   defsymbol (&Qand_rest, "&rest");
4972   defsymbol (&Qand_optional, "&optional");
4973   /* Note that the process code also uses Qexit */
4974   defsymbol (&Qexit, "exit");
4975   defsymbol (&Qsetq, "setq");
4976   defsymbol (&Qinteractive, "interactive");
4977   defsymbol (&Qcommandp, "commandp");
4978   defsymbol (&Qdefun, "defun");
4979   defsymbol (&Qprogn, "progn");
4980   defsymbol (&Qvalues, "values");
4981   defsymbol (&Qdisplay_warning, "display-warning");
4982   defsymbol (&Qrun_hooks, "run-hooks");
4983   defsymbol (&Qif, "if");
4984
4985   DEFSUBR (For);
4986   DEFSUBR (Fand);
4987   DEFSUBR (Fif);
4988   DEFSUBR_MACRO (Fwhen);
4989   DEFSUBR_MACRO (Funless);
4990   DEFSUBR (Fcond);
4991   DEFSUBR (Fprogn);
4992   DEFSUBR (Fprog1);
4993   DEFSUBR (Fprog2);
4994   DEFSUBR (Fsetq);
4995   DEFSUBR (Fquote);
4996   DEFSUBR (Ffunction);
4997   DEFSUBR (Fdefun);
4998   DEFSUBR (Fdefmacro);
4999   DEFSUBR (Fdefvar);
5000   DEFSUBR (Fdefconst);
5001   DEFSUBR (Fuser_variable_p);
5002   DEFSUBR (Flet);
5003   DEFSUBR (FletX);
5004   DEFSUBR (Fwhile);
5005   DEFSUBR (Fmacroexpand_internal);
5006   DEFSUBR (Fcatch);
5007   DEFSUBR (Fthrow);
5008   DEFSUBR (Funwind_protect);
5009   DEFSUBR (Fcondition_case);
5010   DEFSUBR (Fcall_with_condition_handler);
5011   DEFSUBR (Fsignal);
5012   DEFSUBR (Finteractive_p);
5013   DEFSUBR (Fcommandp);
5014   DEFSUBR (Fcommand_execute);
5015   DEFSUBR (Fautoload);
5016   DEFSUBR (Feval);
5017   DEFSUBR (Fapply);
5018   DEFSUBR (Ffuncall);
5019   DEFSUBR (Ffunctionp);
5020   DEFSUBR (Ffunction_min_args);
5021   DEFSUBR (Ffunction_max_args);
5022   DEFSUBR (Frun_hooks);
5023   DEFSUBR (Frun_hook_with_args);
5024   DEFSUBR (Frun_hook_with_args_until_success);
5025   DEFSUBR (Frun_hook_with_args_until_failure);
5026   DEFSUBR (Fbacktrace_debug);
5027   DEFSUBR (Fbacktrace);
5028   DEFSUBR (Fbacktrace_frame);
5029 }
5030
5031 void
5032 reinit_eval (void)
5033 {
5034   specpdl_ptr = specpdl;
5035   specpdl_depth_counter = 0;
5036   catchlist = 0;
5037   Vcondition_handlers = Qnil;
5038   backtrace_list = 0;
5039   Vquit_flag = Qnil;
5040   debug_on_next_call = 0;
5041   lisp_eval_depth = 0;
5042   entering_debugger = 0;
5043 }
5044
5045 void
5046 reinit_vars_of_eval (void)
5047 {
5048   preparing_for_armageddon = 0;
5049   in_warnings = 0;
5050   Qunbound_suspended_errors_tag = make_opaque_ptr (&Qunbound_suspended_errors_tag);
5051   staticpro_nodump (&Qunbound_suspended_errors_tag);
5052
5053   specpdl_size = 50;
5054   specpdl = xnew_array (struct specbinding, specpdl_size);
5055   /* XEmacs change: increase these values. */
5056   max_specpdl_size = 3000;
5057   max_lisp_eval_depth = 500;
5058 #if 0 /* no longer used */
5059   throw_level = 0;
5060 #endif
5061 }
5062
5063 void
5064 vars_of_eval (void)
5065 {
5066   reinit_vars_of_eval ();
5067
5068   DEFVAR_INT ("max-specpdl-size", &max_specpdl_size /*
5069 Limit on number of Lisp variable bindings & unwind-protects before error.
5070 */ );
5071
5072   DEFVAR_INT ("max-lisp-eval-depth", &max_lisp_eval_depth /*
5073 Limit on depth in `eval', `apply' and `funcall' before error.
5074 This limit is to catch infinite recursions for you before they cause
5075 actual stack overflow in C, which would be fatal for Emacs.
5076 You can safely make it considerably larger than its default value,
5077 if that proves inconveniently small.
5078 */ );
5079
5080   DEFVAR_LISP ("quit-flag", &Vquit_flag /*
5081 Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
5082 Typing C-G sets `quit-flag' non-nil, regardless of `inhibit-quit'.
5083 */ );
5084   Vquit_flag = Qnil;
5085
5086   DEFVAR_LISP ("inhibit-quit", &Vinhibit_quit /*
5087 Non-nil inhibits C-g quitting from happening immediately.
5088 Note that `quit-flag' will still be set by typing C-g,
5089 so a quit will be signalled as soon as `inhibit-quit' is nil.
5090 To prevent this happening, set `quit-flag' to nil
5091 before making `inhibit-quit' nil.  The value of `inhibit-quit' is
5092 ignored if a critical quit is requested by typing control-shift-G in
5093 an X frame.
5094 */ );
5095   Vinhibit_quit = Qnil;
5096
5097   DEFVAR_LISP ("stack-trace-on-error", &Vstack_trace_on_error /*
5098 *Non-nil means automatically display a backtrace buffer
5099 after any error that is not handled by a `condition-case'.
5100 If the value is a list, an error only means to display a backtrace
5101 if one of its condition symbols appears in the list.
5102 See also variable `stack-trace-on-signal'.
5103 */ );
5104   Vstack_trace_on_error = Qnil;
5105
5106   DEFVAR_LISP ("stack-trace-on-signal", &Vstack_trace_on_signal /*
5107 *Non-nil means automatically display a backtrace buffer
5108 after any error that is signalled, whether or not it is handled by
5109 a `condition-case'.
5110 If the value is a list, an error only means to display a backtrace
5111 if one of its condition symbols appears in the list.
5112 See also variable `stack-trace-on-error'.
5113 */ );
5114   Vstack_trace_on_signal = Qnil;
5115
5116   DEFVAR_LISP ("debug-ignored-errors", &Vdebug_ignored_errors /*
5117 *List of errors for which the debugger should not be called.
5118 Each element may be a condition-name or a regexp that matches error messages.
5119 If any element applies to a given error, that error skips the debugger
5120 and just returns to top level.
5121 This overrides the variable `debug-on-error'.
5122 It does not apply to errors handled by `condition-case'.
5123 */ );
5124   Vdebug_ignored_errors = Qnil;
5125
5126   DEFVAR_LISP ("debug-on-error", &Vdebug_on_error /*
5127 *Non-nil means enter debugger if an unhandled error is signalled.
5128 The debugger will not be entered if the error is handled by
5129 a `condition-case'.
5130 If the value is a list, an error only means to enter the debugger
5131 if one of its condition symbols appears in the list.
5132 This variable is overridden by `debug-ignored-errors'.
5133 See also variables `debug-on-quit' and `debug-on-signal'.
5134 */ );
5135   Vdebug_on_error = Qnil;
5136
5137   DEFVAR_LISP ("debug-on-signal", &Vdebug_on_signal /*
5138 *Non-nil means enter debugger if an error is signalled.
5139 The debugger will be entered whether or not the error is handled by
5140 a `condition-case'.
5141 If the value is a list, an error only means to enter the debugger
5142 if one of its condition symbols appears in the list.
5143 See also variable `debug-on-quit'.
5144 */ );
5145   Vdebug_on_signal = Qnil;
5146
5147   DEFVAR_BOOL ("debug-on-quit", &debug_on_quit /*
5148 *Non-nil means enter debugger if quit is signalled (C-G, for example).
5149 Does not apply if quit is handled by a `condition-case'.  Entering the
5150 debugger can also be achieved at any time (for X11 console) by typing
5151 control-shift-G to signal a critical quit.
5152 */ );
5153   debug_on_quit = 0;
5154
5155   DEFVAR_BOOL ("debug-on-next-call", &debug_on_next_call /*
5156 Non-nil means enter debugger before next `eval', `apply' or `funcall'.
5157 */ );
5158
5159   DEFVAR_LISP ("debugger", &Vdebugger /*
5160 Function to call to invoke debugger.
5161 If due to frame exit, args are `exit' and the value being returned;
5162  this function's value will be returned instead of that.
5163 If due to error, args are `error' and a list of the args to `signal'.
5164 If due to `apply' or `funcall' entry, one arg, `lambda'.
5165 If due to `eval' entry, one arg, t.
5166 */ );
5167   Vdebugger = Qnil;
5168
5169   staticpro (&Vpending_warnings);
5170   Vpending_warnings = Qnil;
5171   pdump_wire (&Vpending_warnings_tail);
5172   Vpending_warnings_tail = Qnil;
5173
5174   staticpro (&Vautoload_queue);
5175   Vautoload_queue = Qnil;
5176
5177   staticpro (&Vcondition_handlers);
5178
5179   staticpro (&Vcurrent_warning_class);
5180   Vcurrent_warning_class = Qnil;
5181
5182   staticpro (&Vcurrent_error_state);
5183   Vcurrent_error_state = Qnil; /* errors as normal */
5184
5185   reinit_eval ();
5186 }