‘signal’ no longer returns
[emacs.git] / src / eval.c
blob33b82f74b6451a6982a41ff2ae897f310b0936e1
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2016 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include "lisp.h"
26 #include "blockinput.h"
27 #include "commands.h"
28 #include "keyboard.h"
29 #include "dispextern.h"
30 #include "buffer.h"
32 /* Chain of condition and catch handlers currently in effect. */
34 struct handler *handlerlist;
36 /* Non-nil means record all fset's and provide's, to be undone
37 if the file being autoloaded is not fully loaded.
38 They are recorded by being consed onto the front of Vautoload_queue:
39 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
41 Lisp_Object Vautoload_queue;
43 /* This holds either the symbol `run-hooks' or nil.
44 It is nil at an early stage of startup, and when Emacs
45 is shutting down. */
46 Lisp_Object Vrun_hooks;
48 /* Current number of specbindings allocated in specpdl, not counting
49 the dummy entry specpdl[-1]. */
51 ptrdiff_t specpdl_size;
53 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
54 only so that its address can be taken. */
56 union specbinding *specpdl;
58 /* Pointer to first unused element in specpdl. */
60 union specbinding *specpdl_ptr;
62 /* Depth in Lisp evaluations and function calls. */
64 static EMACS_INT lisp_eval_depth;
66 /* The value of num_nonmacro_input_events as of the last time we
67 started to enter the debugger. If we decide to enter the debugger
68 again when this is still equal to num_nonmacro_input_events, then we
69 know that the debugger itself has an error, and we should just
70 signal the error instead of entering an infinite loop of debugger
71 invocations. */
73 static EMACS_INT when_entered_debugger;
75 /* The function from which the last `signal' was called. Set in
76 Fsignal. */
77 /* FIXME: We should probably get rid of this! */
78 Lisp_Object Vsignaling_function;
80 /* If non-nil, Lisp code must not be run since some part of Emacs is in
81 an inconsistent state. Currently unused. */
82 Lisp_Object inhibit_lisp_code;
84 /* These would ordinarily be static, but they need to be visible to GDB. */
85 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
86 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
87 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
88 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
89 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
91 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
92 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
93 static Lisp_Object lambda_arity (Lisp_Object);
95 static Lisp_Object
96 specpdl_symbol (union specbinding *pdl)
98 eassert (pdl->kind >= SPECPDL_LET);
99 return pdl->let.symbol;
102 static Lisp_Object
103 specpdl_old_value (union specbinding *pdl)
105 eassert (pdl->kind >= SPECPDL_LET);
106 return pdl->let.old_value;
109 static void
110 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
112 eassert (pdl->kind >= SPECPDL_LET);
113 pdl->let.old_value = val;
116 static Lisp_Object
117 specpdl_where (union specbinding *pdl)
119 eassert (pdl->kind > SPECPDL_LET);
120 return pdl->let.where;
123 static Lisp_Object
124 specpdl_arg (union specbinding *pdl)
126 eassert (pdl->kind == SPECPDL_UNWIND);
127 return pdl->unwind.arg;
130 Lisp_Object
131 backtrace_function (union specbinding *pdl)
133 eassert (pdl->kind == SPECPDL_BACKTRACE);
134 return pdl->bt.function;
137 static ptrdiff_t
138 backtrace_nargs (union specbinding *pdl)
140 eassert (pdl->kind == SPECPDL_BACKTRACE);
141 return pdl->bt.nargs;
144 Lisp_Object *
145 backtrace_args (union specbinding *pdl)
147 eassert (pdl->kind == SPECPDL_BACKTRACE);
148 return pdl->bt.args;
151 static bool
152 backtrace_debug_on_exit (union specbinding *pdl)
154 eassert (pdl->kind == SPECPDL_BACKTRACE);
155 return pdl->bt.debug_on_exit;
158 /* Functions to modify slots of backtrace records. */
160 static void
161 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
163 eassert (pdl->kind == SPECPDL_BACKTRACE);
164 pdl->bt.args = args;
165 pdl->bt.nargs = nargs;
168 static void
169 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
171 eassert (pdl->kind == SPECPDL_BACKTRACE);
172 pdl->bt.debug_on_exit = doe;
175 /* Helper functions to scan the backtrace. */
177 bool
178 backtrace_p (union specbinding *pdl)
179 { return pdl >= specpdl; }
181 union specbinding *
182 backtrace_top (void)
184 union specbinding *pdl = specpdl_ptr - 1;
185 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
186 pdl--;
187 return pdl;
190 union specbinding *
191 backtrace_next (union specbinding *pdl)
193 pdl--;
194 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
195 pdl--;
196 return pdl;
199 /* Return a pointer to somewhere near the top of the C stack. */
200 void *
201 near_C_stack_top (void)
203 return backtrace_args (backtrace_top ());
206 void
207 init_eval_once (void)
209 enum { size = 50 };
210 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
211 specpdl_size = size;
212 specpdl = specpdl_ptr = pdlvec + 1;
213 /* Don't forget to update docs (lispref node "Local Variables"). */
214 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
215 max_lisp_eval_depth = 800;
217 Vrun_hooks = Qnil;
220 static struct handler handlerlist_sentinel;
222 void
223 init_eval (void)
225 byte_stack_list = 0;
226 specpdl_ptr = specpdl;
227 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
228 This is important since handlerlist->nextfree holds the freelist
229 which would otherwise leak every time we unwind back to top-level. */
230 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
231 struct handler *c = push_handler (Qunbound, CATCHER);
232 eassert (c == &handlerlist_sentinel);
233 handlerlist_sentinel.nextfree = NULL;
234 handlerlist_sentinel.next = NULL;
236 Vquit_flag = Qnil;
237 debug_on_next_call = 0;
238 lisp_eval_depth = 0;
239 /* This is less than the initial value of num_nonmacro_input_events. */
240 when_entered_debugger = -1;
243 /* Unwind-protect function used by call_debugger. */
245 static void
246 restore_stack_limits (Lisp_Object data)
248 max_specpdl_size = XINT (XCAR (data));
249 max_lisp_eval_depth = XINT (XCDR (data));
252 static void grow_specpdl (void);
254 /* Call the Lisp debugger, giving it argument ARG. */
256 Lisp_Object
257 call_debugger (Lisp_Object arg)
259 bool debug_while_redisplaying;
260 ptrdiff_t count = SPECPDL_INDEX ();
261 Lisp_Object val;
262 EMACS_INT old_depth = max_lisp_eval_depth;
263 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
264 EMACS_INT old_max = max (max_specpdl_size, count);
266 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
267 max_lisp_eval_depth = lisp_eval_depth + 40;
269 /* While debugging Bug#16603, previous value of 100 was found
270 too small to avoid specpdl overflow in the debugger itself. */
271 if (max_specpdl_size - 200 < count)
272 max_specpdl_size = count + 200;
274 if (old_max == count)
276 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
277 specpdl_ptr--;
278 grow_specpdl ();
281 /* Restore limits after leaving the debugger. */
282 record_unwind_protect (restore_stack_limits,
283 Fcons (make_number (old_max),
284 make_number (old_depth)));
286 #ifdef HAVE_WINDOW_SYSTEM
287 if (display_hourglass_p)
288 cancel_hourglass ();
289 #endif
291 debug_on_next_call = 0;
292 when_entered_debugger = num_nonmacro_input_events;
294 /* Resetting redisplaying_p to 0 makes sure that debug output is
295 displayed if the debugger is invoked during redisplay. */
296 debug_while_redisplaying = redisplaying_p;
297 redisplaying_p = 0;
298 specbind (intern ("debugger-may-continue"),
299 debug_while_redisplaying ? Qnil : Qt);
300 specbind (Qinhibit_redisplay, Qnil);
301 specbind (Qinhibit_debugger, Qt);
303 #if 0 /* Binding this prevents execution of Lisp code during
304 redisplay, which necessarily leads to display problems. */
305 specbind (Qinhibit_eval_during_redisplay, Qt);
306 #endif
308 val = apply1 (Vdebugger, arg);
310 /* Interrupting redisplay and resuming it later is not safe under
311 all circumstances. So, when the debugger returns, abort the
312 interrupted redisplay by going back to the top-level. */
313 if (debug_while_redisplaying)
314 Ftop_level ();
316 return unbind_to (count, val);
319 static void
320 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
322 debug_on_next_call = 0;
323 set_backtrace_debug_on_exit (specpdl + count, true);
324 call_debugger (list1 (code));
327 /* NOTE!!! Every function that can call EVAL must protect its args
328 and temporaries from garbage collection while it needs them.
329 The definition of `For' shows what you have to do. */
331 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
332 doc: /* Eval args until one of them yields non-nil, then return that value.
333 The remaining args are not evalled at all.
334 If all args return nil, return nil.
335 usage: (or CONDITIONS...) */)
336 (Lisp_Object args)
338 Lisp_Object val = Qnil;
340 while (CONSP (args))
342 val = eval_sub (XCAR (args));
343 if (!NILP (val))
344 break;
345 args = XCDR (args);
348 return val;
351 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
352 doc: /* Eval args until one of them yields nil, then return nil.
353 The remaining args are not evalled at all.
354 If no arg yields nil, return the last arg's value.
355 usage: (and CONDITIONS...) */)
356 (Lisp_Object args)
358 Lisp_Object val = Qt;
360 while (CONSP (args))
362 val = eval_sub (XCAR (args));
363 if (NILP (val))
364 break;
365 args = XCDR (args);
368 return val;
371 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
372 doc: /* If COND yields non-nil, do THEN, else do ELSE...
373 Returns the value of THEN or the value of the last of the ELSE's.
374 THEN must be one expression, but ELSE... can be zero or more expressions.
375 If COND yields nil, and there are no ELSE's, the value is nil.
376 usage: (if COND THEN ELSE...) */)
377 (Lisp_Object args)
379 Lisp_Object cond;
381 cond = eval_sub (XCAR (args));
383 if (!NILP (cond))
384 return eval_sub (Fcar (XCDR (args)));
385 return Fprogn (XCDR (XCDR (args)));
388 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
389 doc: /* Try each clause until one succeeds.
390 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
391 and, if the value is non-nil, this clause succeeds:
392 then the expressions in BODY are evaluated and the last one's
393 value is the value of the cond-form.
394 If a clause has one element, as in (CONDITION), then the cond-form
395 returns CONDITION's value, if that is non-nil.
396 If no clause succeeds, cond returns nil.
397 usage: (cond CLAUSES...) */)
398 (Lisp_Object args)
400 Lisp_Object val = args;
402 while (CONSP (args))
404 Lisp_Object clause = XCAR (args);
405 val = eval_sub (Fcar (clause));
406 if (!NILP (val))
408 if (!NILP (XCDR (clause)))
409 val = Fprogn (XCDR (clause));
410 break;
412 args = XCDR (args);
415 return val;
418 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
419 doc: /* Eval BODY forms sequentially and return value of last one.
420 usage: (progn BODY...) */)
421 (Lisp_Object body)
423 Lisp_Object val = Qnil;
425 while (CONSP (body))
427 val = eval_sub (XCAR (body));
428 body = XCDR (body);
431 return val;
434 /* Evaluate BODY sequentially, discarding its value. Suitable for
435 record_unwind_protect. */
437 void
438 unwind_body (Lisp_Object body)
440 Fprogn (body);
443 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
444 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
445 The value of FIRST is saved during the evaluation of the remaining args,
446 whose values are discarded.
447 usage: (prog1 FIRST BODY...) */)
448 (Lisp_Object args)
450 Lisp_Object val;
451 Lisp_Object args_left;
453 args_left = args;
454 val = args;
456 val = eval_sub (XCAR (args_left));
457 while (CONSP (args_left = XCDR (args_left)))
458 eval_sub (XCAR (args_left));
460 return val;
463 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
464 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
465 The value of FORM2 is saved during the evaluation of the
466 remaining args, whose values are discarded.
467 usage: (prog2 FORM1 FORM2 BODY...) */)
468 (Lisp_Object args)
470 eval_sub (XCAR (args));
471 return Fprog1 (XCDR (args));
474 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
475 doc: /* Set each SYM to the value of its VAL.
476 The symbols SYM are variables; they are literal (not evaluated).
477 The values VAL are expressions; they are evaluated.
478 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
479 The second VAL is not computed until after the first SYM is set, and so on;
480 each VAL can use the new value of variables set earlier in the `setq'.
481 The return value of the `setq' form is the value of the last VAL.
482 usage: (setq [SYM VAL]...) */)
483 (Lisp_Object args)
485 Lisp_Object val, sym, lex_binding;
487 val = args;
488 if (CONSP (args))
490 Lisp_Object args_left = args;
491 Lisp_Object numargs = Flength (args);
493 if (XINT (numargs) & 1)
494 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
498 val = eval_sub (Fcar (XCDR (args_left)));
499 sym = XCAR (args_left);
501 /* Like for eval_sub, we do not check declared_special here since
502 it's been done when let-binding. */
503 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
504 && SYMBOLP (sym)
505 && !NILP (lex_binding
506 = Fassq (sym, Vinternal_interpreter_environment)))
507 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
508 else
509 Fset (sym, val); /* SYM is dynamically bound. */
511 args_left = Fcdr (XCDR (args_left));
513 while (CONSP (args_left));
516 return val;
519 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
520 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
521 Warning: `quote' does not construct its return value, but just returns
522 the value that was pre-constructed by the Lisp reader (see info node
523 `(elisp)Printed Representation').
524 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
525 does not cons. Quoting should be reserved for constants that will
526 never be modified by side-effects, unless you like self-modifying code.
527 See the common pitfall in info node `(elisp)Rearrangement' for an example
528 of unexpected results when a quoted object is modified.
529 usage: (quote ARG) */)
530 (Lisp_Object args)
532 if (CONSP (XCDR (args)))
533 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
534 return XCAR (args);
537 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
538 doc: /* Like `quote', but preferred for objects which are functions.
539 In byte compilation, `function' causes its argument to be compiled.
540 `quote' cannot do that.
541 usage: (function ARG) */)
542 (Lisp_Object args)
544 Lisp_Object quoted = XCAR (args);
546 if (CONSP (XCDR (args)))
547 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
549 if (!NILP (Vinternal_interpreter_environment)
550 && CONSP (quoted)
551 && EQ (XCAR (quoted), Qlambda))
552 { /* This is a lambda expression within a lexical environment;
553 return an interpreted closure instead of a simple lambda. */
554 Lisp_Object cdr = XCDR (quoted);
555 Lisp_Object tmp = cdr;
556 if (CONSP (tmp)
557 && (tmp = XCDR (tmp), CONSP (tmp))
558 && (tmp = XCAR (tmp), CONSP (tmp))
559 && (EQ (QCdocumentation, XCAR (tmp))))
560 { /* Handle the special (:documentation <form>) to build the docstring
561 dynamically. */
562 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
563 CHECK_STRING (docstring);
564 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
566 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
567 cdr));
569 else
570 /* Simply quote the argument. */
571 return quoted;
575 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
576 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
577 Aliased variables always have the same value; setting one sets the other.
578 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
579 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
580 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
581 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
582 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
583 The return value is BASE-VARIABLE. */)
584 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
586 struct Lisp_Symbol *sym;
588 CHECK_SYMBOL (new_alias);
589 CHECK_SYMBOL (base_variable);
591 sym = XSYMBOL (new_alias);
593 if (sym->constant)
594 /* Not sure why, but why not? */
595 error ("Cannot make a constant an alias");
597 switch (sym->redirect)
599 case SYMBOL_FORWARDED:
600 error ("Cannot make an internal variable an alias");
601 case SYMBOL_LOCALIZED:
602 error ("Don't know how to make a localized variable an alias");
603 case SYMBOL_PLAINVAL:
604 case SYMBOL_VARALIAS:
605 break;
606 default:
607 emacs_abort ();
610 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
611 If n_a is bound, but b_v is not, set the value of b_v to n_a,
612 so that old-code that affects n_a before the aliasing is setup
613 still works. */
614 if (NILP (Fboundp (base_variable)))
615 set_internal (base_variable, find_symbol_value (new_alias), Qnil, 1);
618 union specbinding *p;
620 for (p = specpdl_ptr; p > specpdl; )
621 if ((--p)->kind >= SPECPDL_LET
622 && (EQ (new_alias, specpdl_symbol (p))))
623 error ("Don't know how to make a let-bound variable an alias");
626 sym->declared_special = 1;
627 XSYMBOL (base_variable)->declared_special = 1;
628 sym->redirect = SYMBOL_VARALIAS;
629 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
630 sym->constant = SYMBOL_CONSTANT_P (base_variable);
631 LOADHIST_ATTACH (new_alias);
632 /* Even if docstring is nil: remove old docstring. */
633 Fput (new_alias, Qvariable_documentation, docstring);
635 return base_variable;
638 static union specbinding *
639 default_toplevel_binding (Lisp_Object symbol)
641 union specbinding *binding = NULL;
642 union specbinding *pdl = specpdl_ptr;
643 while (pdl > specpdl)
645 switch ((--pdl)->kind)
647 case SPECPDL_LET_DEFAULT:
648 case SPECPDL_LET:
649 if (EQ (specpdl_symbol (pdl), symbol))
650 binding = pdl;
651 break;
653 case SPECPDL_UNWIND:
654 case SPECPDL_UNWIND_PTR:
655 case SPECPDL_UNWIND_INT:
656 case SPECPDL_UNWIND_VOID:
657 case SPECPDL_BACKTRACE:
658 case SPECPDL_LET_LOCAL:
659 break;
661 default:
662 emacs_abort ();
665 return binding;
668 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
669 doc: /* Return SYMBOL's toplevel default value.
670 "Toplevel" means outside of any let binding. */)
671 (Lisp_Object symbol)
673 union specbinding *binding = default_toplevel_binding (symbol);
674 Lisp_Object value
675 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
676 if (!EQ (value, Qunbound))
677 return value;
678 xsignal1 (Qvoid_variable, symbol);
681 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
682 Sset_default_toplevel_value, 2, 2, 0,
683 doc: /* Set SYMBOL's toplevel default value to VALUE.
684 "Toplevel" means outside of any let binding. */)
685 (Lisp_Object symbol, Lisp_Object value)
687 union specbinding *binding = default_toplevel_binding (symbol);
688 if (binding)
689 set_specpdl_old_value (binding, value);
690 else
691 Fset_default (symbol, value);
692 return Qnil;
695 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
696 doc: /* Define SYMBOL as a variable, and return SYMBOL.
697 You are not required to define a variable in order to use it, but
698 defining it lets you supply an initial value and documentation, which
699 can be referred to by the Emacs help facilities and other programming
700 tools. The `defvar' form also declares the variable as \"special\",
701 so that it is always dynamically bound even if `lexical-binding' is t.
703 The optional argument INITVALUE is evaluated, and used to set SYMBOL,
704 only if SYMBOL's value is void. If SYMBOL is buffer-local, its
705 default value is what is set; buffer-local values are not affected.
706 If INITVALUE is missing, SYMBOL's value is not set.
708 If SYMBOL has a local binding, then this form affects the local
709 binding. This is usually not what you want. Thus, if you need to
710 load a file defining variables, with this form or with `defconst' or
711 `defcustom', you should always load that file _outside_ any bindings
712 for these variables. (`defconst' and `defcustom' behave similarly in
713 this respect.)
715 The optional argument DOCSTRING is a documentation string for the
716 variable.
718 To define a user option, use `defcustom' instead of `defvar'.
719 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
720 (Lisp_Object args)
722 Lisp_Object sym, tem, tail;
724 sym = XCAR (args);
725 tail = XCDR (args);
727 if (CONSP (tail))
729 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
730 error ("Too many arguments");
732 tem = Fdefault_boundp (sym);
734 /* Do it before evaluating the initial value, for self-references. */
735 XSYMBOL (sym)->declared_special = 1;
737 if (NILP (tem))
738 Fset_default (sym, eval_sub (XCAR (tail)));
739 else
740 { /* Check if there is really a global binding rather than just a let
741 binding that shadows the global unboundness of the var. */
742 union specbinding *binding = default_toplevel_binding (sym);
743 if (binding && EQ (specpdl_old_value (binding), Qunbound))
745 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
748 tail = XCDR (tail);
749 tem = Fcar (tail);
750 if (!NILP (tem))
752 if (!NILP (Vpurify_flag))
753 tem = Fpurecopy (tem);
754 Fput (sym, Qvariable_documentation, tem);
756 LOADHIST_ATTACH (sym);
758 else if (!NILP (Vinternal_interpreter_environment)
759 && !XSYMBOL (sym)->declared_special)
760 /* A simple (defvar foo) with lexical scoping does "nothing" except
761 declare that var to be dynamically scoped *locally* (i.e. within
762 the current file or let-block). */
763 Vinternal_interpreter_environment
764 = Fcons (sym, Vinternal_interpreter_environment);
765 else
767 /* Simple (defvar <var>) should not count as a definition at all.
768 It could get in the way of other definitions, and unloading this
769 package could try to make the variable unbound. */
772 return sym;
775 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
776 doc: /* Define SYMBOL as a constant variable.
777 This declares that neither programs nor users should ever change the
778 value. This constancy is not actually enforced by Emacs Lisp, but
779 SYMBOL is marked as a special variable so that it is never lexically
780 bound.
782 The `defconst' form always sets the value of SYMBOL to the result of
783 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
784 what is set; buffer-local values are not affected. If SYMBOL has a
785 local binding, then this form sets the local binding's value.
786 However, you should normally not make local bindings for variables
787 defined with this form.
789 The optional DOCSTRING specifies the variable's documentation string.
790 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
791 (Lisp_Object args)
793 Lisp_Object sym, tem;
795 sym = XCAR (args);
796 if (CONSP (Fcdr (XCDR (XCDR (args)))))
797 error ("Too many arguments");
799 tem = eval_sub (Fcar (XCDR (args)));
800 if (!NILP (Vpurify_flag))
801 tem = Fpurecopy (tem);
802 Fset_default (sym, tem);
803 XSYMBOL (sym)->declared_special = 1;
804 tem = Fcar (XCDR (XCDR (args)));
805 if (!NILP (tem))
807 if (!NILP (Vpurify_flag))
808 tem = Fpurecopy (tem);
809 Fput (sym, Qvariable_documentation, tem);
811 Fput (sym, Qrisky_local_variable, Qt);
812 LOADHIST_ATTACH (sym);
813 return sym;
816 /* Make SYMBOL lexically scoped. */
817 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
818 Smake_var_non_special, 1, 1, 0,
819 doc: /* Internal function. */)
820 (Lisp_Object symbol)
822 CHECK_SYMBOL (symbol);
823 XSYMBOL (symbol)->declared_special = 0;
824 return Qnil;
828 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
829 doc: /* Bind variables according to VARLIST then eval BODY.
830 The value of the last form in BODY is returned.
831 Each element of VARLIST is a symbol (which is bound to nil)
832 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
833 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
834 usage: (let* VARLIST BODY...) */)
835 (Lisp_Object args)
837 Lisp_Object varlist, var, val, elt, lexenv;
838 ptrdiff_t count = SPECPDL_INDEX ();
840 lexenv = Vinternal_interpreter_environment;
842 varlist = XCAR (args);
843 while (CONSP (varlist))
845 QUIT;
847 elt = XCAR (varlist);
848 if (SYMBOLP (elt))
850 var = elt;
851 val = Qnil;
853 else if (! NILP (Fcdr (Fcdr (elt))))
854 signal_error ("`let' bindings can have only one value-form", elt);
855 else
857 var = Fcar (elt);
858 val = eval_sub (Fcar (Fcdr (elt)));
861 if (!NILP (lexenv) && SYMBOLP (var)
862 && !XSYMBOL (var)->declared_special
863 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
864 /* Lexically bind VAR by adding it to the interpreter's binding
865 alist. */
867 Lisp_Object newenv
868 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
869 if (EQ (Vinternal_interpreter_environment, lexenv))
870 /* Save the old lexical environment on the specpdl stack,
871 but only for the first lexical binding, since we'll never
872 need to revert to one of the intermediate ones. */
873 specbind (Qinternal_interpreter_environment, newenv);
874 else
875 Vinternal_interpreter_environment = newenv;
877 else
878 specbind (var, val);
880 varlist = XCDR (varlist);
883 val = Fprogn (XCDR (args));
884 return unbind_to (count, val);
887 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
888 doc: /* Bind variables according to VARLIST then eval BODY.
889 The value of the last form in BODY is returned.
890 Each element of VARLIST is a symbol (which is bound to nil)
891 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
892 All the VALUEFORMs are evalled before any symbols are bound.
893 usage: (let VARLIST BODY...) */)
894 (Lisp_Object args)
896 Lisp_Object *temps, tem, lexenv;
897 Lisp_Object elt, varlist;
898 ptrdiff_t count = SPECPDL_INDEX ();
899 ptrdiff_t argnum;
900 USE_SAFE_ALLOCA;
902 varlist = XCAR (args);
904 /* Make space to hold the values to give the bound variables. */
905 elt = Flength (varlist);
906 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
908 /* Compute the values and store them in `temps'. */
910 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
912 QUIT;
913 elt = XCAR (varlist);
914 if (SYMBOLP (elt))
915 temps [argnum++] = Qnil;
916 else if (! NILP (Fcdr (Fcdr (elt))))
917 signal_error ("`let' bindings can have only one value-form", elt);
918 else
919 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
922 lexenv = Vinternal_interpreter_environment;
924 varlist = XCAR (args);
925 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
927 Lisp_Object var;
929 elt = XCAR (varlist);
930 var = SYMBOLP (elt) ? elt : Fcar (elt);
931 tem = temps[argnum++];
933 if (!NILP (lexenv) && SYMBOLP (var)
934 && !XSYMBOL (var)->declared_special
935 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
936 /* Lexically bind VAR by adding it to the lexenv alist. */
937 lexenv = Fcons (Fcons (var, tem), lexenv);
938 else
939 /* Dynamically bind VAR. */
940 specbind (var, tem);
943 if (!EQ (lexenv, Vinternal_interpreter_environment))
944 /* Instantiate a new lexical environment. */
945 specbind (Qinternal_interpreter_environment, lexenv);
947 elt = Fprogn (XCDR (args));
948 SAFE_FREE ();
949 return unbind_to (count, elt);
952 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
953 doc: /* If TEST yields non-nil, eval BODY... and repeat.
954 The order of execution is thus TEST, BODY, TEST, BODY and so on
955 until TEST returns nil.
956 usage: (while TEST BODY...) */)
957 (Lisp_Object args)
959 Lisp_Object test, body;
961 test = XCAR (args);
962 body = XCDR (args);
963 while (!NILP (eval_sub (test)))
965 QUIT;
966 Fprogn (body);
969 return Qnil;
972 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
973 doc: /* Return result of expanding macros at top level of FORM.
974 If FORM is not a macro call, it is returned unchanged.
975 Otherwise, the macro is expanded and the expansion is considered
976 in place of FORM. When a non-macro-call results, it is returned.
978 The second optional arg ENVIRONMENT specifies an environment of macro
979 definitions to shadow the loaded ones for use in file byte-compilation. */)
980 (Lisp_Object form, Lisp_Object environment)
982 /* With cleanups from Hallvard Furuseth. */
983 register Lisp_Object expander, sym, def, tem;
985 while (1)
987 /* Come back here each time we expand a macro call,
988 in case it expands into another macro call. */
989 if (!CONSP (form))
990 break;
991 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
992 def = sym = XCAR (form);
993 tem = Qnil;
994 /* Trace symbols aliases to other symbols
995 until we get a symbol that is not an alias. */
996 while (SYMBOLP (def))
998 QUIT;
999 sym = def;
1000 tem = Fassq (sym, environment);
1001 if (NILP (tem))
1003 def = XSYMBOL (sym)->function;
1004 if (!NILP (def))
1005 continue;
1007 break;
1009 /* Right now TEM is the result from SYM in ENVIRONMENT,
1010 and if TEM is nil then DEF is SYM's function definition. */
1011 if (NILP (tem))
1013 /* SYM is not mentioned in ENVIRONMENT.
1014 Look at its function definition. */
1015 def = Fautoload_do_load (def, sym, Qmacro);
1016 if (!CONSP (def))
1017 /* Not defined or definition not suitable. */
1018 break;
1019 if (!EQ (XCAR (def), Qmacro))
1020 break;
1021 else expander = XCDR (def);
1023 else
1025 expander = XCDR (tem);
1026 if (NILP (expander))
1027 break;
1030 Lisp_Object newform = apply1 (expander, XCDR (form));
1031 if (EQ (form, newform))
1032 break;
1033 else
1034 form = newform;
1037 return form;
1040 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1041 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1042 TAG is evalled to get the tag to use; it must not be nil.
1044 Then the BODY is executed.
1045 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1046 If no throw happens, `catch' returns the value of the last BODY form.
1047 If a throw happens, it specifies the value to return from `catch'.
1048 usage: (catch TAG BODY...) */)
1049 (Lisp_Object args)
1051 Lisp_Object tag = eval_sub (XCAR (args));
1052 return internal_catch (tag, Fprogn, XCDR (args));
1055 /* Assert that E is true, as a comment only. Use this instead of
1056 eassert (E) when E contains variables that might be clobbered by a
1057 longjmp. */
1059 #define clobbered_eassert(E) ((void) 0)
1061 /* Set up a catch, then call C function FUNC on argument ARG.
1062 FUNC should return a Lisp_Object.
1063 This is how catches are done from within C code. */
1065 Lisp_Object
1066 internal_catch (Lisp_Object tag,
1067 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1069 /* This structure is made part of the chain `catchlist'. */
1070 struct handler *c = push_handler (tag, CATCHER);
1072 /* Call FUNC. */
1073 if (! sys_setjmp (c->jmp))
1075 Lisp_Object val = func (arg);
1076 clobbered_eassert (handlerlist == c);
1077 handlerlist = handlerlist->next;
1078 return val;
1080 else
1081 { /* Throw works by a longjmp that comes right here. */
1082 Lisp_Object val = handlerlist->val;
1083 clobbered_eassert (handlerlist == c);
1084 handlerlist = handlerlist->next;
1085 return val;
1089 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1090 jump to that CATCH, returning VALUE as the value of that catch.
1092 This is the guts of Fthrow and Fsignal; they differ only in the way
1093 they choose the catch tag to throw to. A catch tag for a
1094 condition-case form has a TAG of Qnil.
1096 Before each catch is discarded, unbind all special bindings and
1097 execute all unwind-protect clauses made above that catch. Unwind
1098 the handler stack as we go, so that the proper handlers are in
1099 effect for each unwind-protect clause we run. At the end, restore
1100 some static info saved in CATCH, and longjmp to the location
1101 specified there.
1103 This is used for correct unwinding in Fthrow and Fsignal. */
1105 static _Noreturn void
1106 unwind_to_catch (struct handler *catch, Lisp_Object value)
1108 bool last_time;
1110 eassert (catch->next);
1112 /* Save the value in the tag. */
1113 catch->val = value;
1115 /* Restore certain special C variables. */
1116 set_poll_suppress_count (catch->poll_suppress_count);
1117 unblock_input_to (catch->interrupt_input_blocked);
1118 immediate_quit = 0;
1122 /* Unwind the specpdl stack, and then restore the proper set of
1123 handlers. */
1124 unbind_to (handlerlist->pdlcount, Qnil);
1125 last_time = handlerlist == catch;
1126 if (! last_time)
1127 handlerlist = handlerlist->next;
1129 while (! last_time);
1131 eassert (handlerlist == catch);
1133 byte_stack_list = catch->byte_stack;
1134 lisp_eval_depth = catch->lisp_eval_depth;
1136 sys_longjmp (catch->jmp, 1);
1139 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1140 doc: /* Throw to the catch for TAG and return VALUE from it.
1141 Both TAG and VALUE are evalled. */
1142 attributes: noreturn)
1143 (register Lisp_Object tag, Lisp_Object value)
1145 struct handler *c;
1147 if (!NILP (tag))
1148 for (c = handlerlist; c; c = c->next)
1150 if (c->type == CATCHER_ALL)
1151 unwind_to_catch (c, Fcons (tag, value));
1152 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1153 unwind_to_catch (c, value);
1155 xsignal2 (Qno_catch, tag, value);
1159 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1160 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1161 If BODYFORM completes normally, its value is returned
1162 after executing the UNWINDFORMS.
1163 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1164 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1165 (Lisp_Object args)
1167 Lisp_Object val;
1168 ptrdiff_t count = SPECPDL_INDEX ();
1170 record_unwind_protect (unwind_body, XCDR (args));
1171 val = eval_sub (XCAR (args));
1172 return unbind_to (count, val);
1175 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1176 doc: /* Regain control when an error is signaled.
1177 Executes BODYFORM and returns its value if no error happens.
1178 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1179 where the BODY is made of Lisp expressions.
1181 A handler is applicable to an error
1182 if CONDITION-NAME is one of the error's condition names.
1183 If an error happens, the first applicable handler is run.
1185 The car of a handler may be a list of condition names instead of a
1186 single condition name; then it handles all of them. If the special
1187 condition name `debug' is present in this list, it allows another
1188 condition in the list to run the debugger if `debug-on-error' and the
1189 other usual mechanisms says it should (otherwise, `condition-case'
1190 suppresses the debugger).
1192 When a handler handles an error, control returns to the `condition-case'
1193 and it executes the handler's BODY...
1194 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1195 \(If VAR is nil, the handler can't access that information.)
1196 Then the value of the last BODY form is returned from the `condition-case'
1197 expression.
1199 See also the function `signal' for more info.
1200 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1201 (Lisp_Object args)
1203 Lisp_Object var = XCAR (args);
1204 Lisp_Object bodyform = XCAR (XCDR (args));
1205 Lisp_Object handlers = XCDR (XCDR (args));
1207 return internal_lisp_condition_case (var, bodyform, handlers);
1210 /* Like Fcondition_case, but the args are separate
1211 rather than passed in a list. Used by Fbyte_code. */
1213 Lisp_Object
1214 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1215 Lisp_Object handlers)
1217 Lisp_Object val;
1218 struct handler *oldhandlerlist = handlerlist;
1219 int clausenb = 0;
1221 CHECK_SYMBOL (var);
1223 for (val = handlers; CONSP (val); val = XCDR (val))
1225 Lisp_Object tem = XCAR (val);
1226 clausenb++;
1227 if (! (NILP (tem)
1228 || (CONSP (tem)
1229 && (SYMBOLP (XCAR (tem))
1230 || CONSP (XCAR (tem))))))
1231 error ("Invalid condition handler: %s",
1232 SDATA (Fprin1_to_string (tem, Qt)));
1235 { /* The first clause is the one that should be checked first, so it should
1236 be added to handlerlist last. So we build in `clauses' a table that
1237 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1238 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1239 if (MAX_ALLOCA / word_size < clausenb)
1240 memory_full (SIZE_MAX);
1241 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1242 Lisp_Object *volatile clauses_volatile = clauses;
1243 int i = clausenb;
1244 for (val = handlers; CONSP (val); val = XCDR (val))
1245 clauses[--i] = XCAR (val);
1246 for (i = 0; i < clausenb; i++)
1248 Lisp_Object clause = clauses[i];
1249 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1250 if (!CONSP (condition))
1251 condition = Fcons (condition, Qnil);
1252 struct handler *c = push_handler (condition, CONDITION_CASE);
1253 if (sys_setjmp (c->jmp))
1255 ptrdiff_t count = SPECPDL_INDEX ();
1256 Lisp_Object val = handlerlist->val;
1257 Lisp_Object *chosen_clause = clauses_volatile;
1258 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1259 chosen_clause++;
1260 handlerlist = oldhandlerlist;
1261 if (!NILP (var))
1263 if (!NILP (Vinternal_interpreter_environment))
1264 specbind (Qinternal_interpreter_environment,
1265 Fcons (Fcons (var, val),
1266 Vinternal_interpreter_environment));
1267 else
1268 specbind (var, val);
1270 val = Fprogn (XCDR (*chosen_clause));
1271 /* Note that this just undoes the binding of var; whoever
1272 longjumped to us unwound the stack to c.pdlcount before
1273 throwing. */
1274 if (!NILP (var))
1275 unbind_to (count, Qnil);
1276 return val;
1281 val = eval_sub (bodyform);
1282 handlerlist = oldhandlerlist;
1283 return val;
1286 /* Call the function BFUN with no arguments, catching errors within it
1287 according to HANDLERS. If there is an error, call HFUN with
1288 one argument which is the data that describes the error:
1289 (SIGNALNAME . DATA)
1291 HANDLERS can be a list of conditions to catch.
1292 If HANDLERS is Qt, catch all errors.
1293 If HANDLERS is Qerror, catch all errors
1294 but allow the debugger to run if that is enabled. */
1296 Lisp_Object
1297 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1298 Lisp_Object (*hfun) (Lisp_Object))
1300 struct handler *c = push_handler (handlers, CONDITION_CASE);
1301 if (sys_setjmp (c->jmp))
1303 Lisp_Object val = handlerlist->val;
1304 clobbered_eassert (handlerlist == c);
1305 handlerlist = handlerlist->next;
1306 return hfun (val);
1308 else
1310 Lisp_Object val = bfun ();
1311 clobbered_eassert (handlerlist == c);
1312 handlerlist = handlerlist->next;
1313 return val;
1317 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1319 Lisp_Object
1320 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1321 Lisp_Object handlers,
1322 Lisp_Object (*hfun) (Lisp_Object))
1324 struct handler *c = push_handler (handlers, CONDITION_CASE);
1325 if (sys_setjmp (c->jmp))
1327 Lisp_Object val = handlerlist->val;
1328 clobbered_eassert (handlerlist == c);
1329 handlerlist = handlerlist->next;
1330 return hfun (val);
1332 else
1334 Lisp_Object val = bfun (arg);
1335 clobbered_eassert (handlerlist == c);
1336 handlerlist = handlerlist->next;
1337 return val;
1341 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1342 its arguments. */
1344 Lisp_Object
1345 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1346 Lisp_Object arg1,
1347 Lisp_Object arg2,
1348 Lisp_Object handlers,
1349 Lisp_Object (*hfun) (Lisp_Object))
1351 struct handler *c = push_handler (handlers, CONDITION_CASE);
1352 if (sys_setjmp (c->jmp))
1354 Lisp_Object val = handlerlist->val;
1355 clobbered_eassert (handlerlist == c);
1356 handlerlist = handlerlist->next;
1357 return hfun (val);
1359 else
1361 Lisp_Object val = bfun (arg1, arg2);
1362 clobbered_eassert (handlerlist == c);
1363 handlerlist = handlerlist->next;
1364 return val;
1368 /* Like internal_condition_case but call BFUN with NARGS as first,
1369 and ARGS as second argument. */
1371 Lisp_Object
1372 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1373 ptrdiff_t nargs,
1374 Lisp_Object *args,
1375 Lisp_Object handlers,
1376 Lisp_Object (*hfun) (Lisp_Object err,
1377 ptrdiff_t nargs,
1378 Lisp_Object *args))
1380 struct handler *c = push_handler (handlers, CONDITION_CASE);
1381 if (sys_setjmp (c->jmp))
1383 Lisp_Object val = handlerlist->val;
1384 clobbered_eassert (handlerlist == c);
1385 handlerlist = handlerlist->next;
1386 return hfun (val, nargs, args);
1388 else
1390 Lisp_Object val = bfun (nargs, args);
1391 clobbered_eassert (handlerlist == c);
1392 handlerlist = handlerlist->next;
1393 return val;
1397 struct handler *
1398 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1400 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1401 if (!c)
1402 memory_full (sizeof *c);
1403 return c;
1406 struct handler *
1407 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1409 struct handler *c = handlerlist->nextfree;
1410 if (!c)
1412 c = malloc (sizeof *c);
1413 if (!c)
1414 return c;
1415 if (profiler_memory_running)
1416 malloc_probe (sizeof *c);
1417 c->nextfree = NULL;
1418 handlerlist->nextfree = c;
1420 c->type = handlertype;
1421 c->tag_or_ch = tag_ch_val;
1422 c->val = Qnil;
1423 c->next = handlerlist;
1424 c->lisp_eval_depth = lisp_eval_depth;
1425 c->pdlcount = SPECPDL_INDEX ();
1426 c->poll_suppress_count = poll_suppress_count;
1427 c->interrupt_input_blocked = interrupt_input_blocked;
1428 c->byte_stack = byte_stack_list;
1429 handlerlist = c;
1430 return c;
1434 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1435 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1436 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1437 Lisp_Object data);
1439 void
1440 process_quit_flag (void)
1442 Lisp_Object flag = Vquit_flag;
1443 Vquit_flag = Qnil;
1444 if (EQ (flag, Qkill_emacs))
1445 Fkill_emacs (Qnil);
1446 if (EQ (Vthrow_on_input, flag))
1447 Fthrow (Vthrow_on_input, Qt);
1448 quit ();
1451 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1452 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1453 This function does not return.
1455 An error symbol is a symbol with an `error-conditions' property
1456 that is a list of condition names.
1457 A handler for any of those names will get to handle this signal.
1458 The symbol `error' should normally be one of them.
1460 DATA should be a list. Its elements are printed as part of the error message.
1461 See Info anchor `(elisp)Definition of signal' for some details on how this
1462 error message is constructed.
1463 If the signal is handled, DATA is made available to the handler.
1464 See also the function `condition-case'. */
1465 attributes: noreturn)
1466 (Lisp_Object error_symbol, Lisp_Object data)
1468 signal_or_quit (error_symbol, data, false);
1469 eassume (false);
1472 /* Quit, in response to a keyboard quit request. */
1473 Lisp_Object
1474 quit (void)
1476 return signal_or_quit (Qquit, Qnil, true);
1479 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1480 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1481 Qquit and DATA should be Qnil, and this function may return.
1482 Otherwise this function is like Fsignal and does not return. */
1484 static Lisp_Object
1485 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1487 /* When memory is full, ERROR-SYMBOL is nil,
1488 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1489 That is a special case--don't do this in other situations. */
1490 Lisp_Object conditions;
1491 Lisp_Object string;
1492 Lisp_Object real_error_symbol
1493 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1494 register Lisp_Object clause = Qnil;
1495 struct handler *h;
1497 immediate_quit = 0;
1498 abort_on_gc = 0;
1499 if (gc_in_progress || waiting_for_input)
1500 emacs_abort ();
1502 #if 0 /* rms: I don't know why this was here,
1503 but it is surely wrong for an error that is handled. */
1504 #ifdef HAVE_WINDOW_SYSTEM
1505 if (display_hourglass_p)
1506 cancel_hourglass ();
1507 #endif
1508 #endif
1510 /* This hook is used by edebug. */
1511 if (! NILP (Vsignal_hook_function)
1512 && ! NILP (error_symbol))
1514 /* Edebug takes care of restoring these variables when it exits. */
1515 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1516 max_lisp_eval_depth = lisp_eval_depth + 20;
1518 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1519 max_specpdl_size = SPECPDL_INDEX () + 40;
1521 call2 (Vsignal_hook_function, error_symbol, data);
1524 conditions = Fget (real_error_symbol, Qerror_conditions);
1526 /* Remember from where signal was called. Skip over the frame for
1527 `signal' itself. If a frame for `error' follows, skip that,
1528 too. Don't do this when ERROR_SYMBOL is nil, because that
1529 is a memory-full error. */
1530 Vsignaling_function = Qnil;
1531 if (!NILP (error_symbol))
1533 union specbinding *pdl = backtrace_next (backtrace_top ());
1534 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1535 pdl = backtrace_next (pdl);
1536 if (backtrace_p (pdl))
1537 Vsignaling_function = backtrace_function (pdl);
1540 for (h = handlerlist; h; h = h->next)
1542 if (h->type != CONDITION_CASE)
1543 continue;
1544 clause = find_handler_clause (h->tag_or_ch, conditions);
1545 if (!NILP (clause))
1546 break;
1549 if (/* Don't run the debugger for a memory-full error.
1550 (There is no room in memory to do that!) */
1551 !NILP (error_symbol)
1552 && (!NILP (Vdebug_on_signal)
1553 /* If no handler is present now, try to run the debugger. */
1554 || NILP (clause)
1555 /* A `debug' symbol in the handler list disables the normal
1556 suppression of the debugger. */
1557 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1558 /* Special handler that means "print a message and run debugger
1559 if requested". */
1560 || EQ (h->tag_or_ch, Qerror)))
1562 bool debugger_called
1563 = maybe_call_debugger (conditions, error_symbol, data);
1564 /* We can't return values to code which signaled an error, but we
1565 can continue code which has signaled a quit. */
1566 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1567 return Qnil;
1570 if (!NILP (clause))
1572 Lisp_Object unwind_data
1573 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1575 unwind_to_catch (h, unwind_data);
1577 else
1579 if (handlerlist != &handlerlist_sentinel)
1580 /* FIXME: This will come right back here if there's no `top-level'
1581 catcher. A better solution would be to abort here, and instead
1582 add a catch-all condition handler so we never come here. */
1583 Fthrow (Qtop_level, Qt);
1586 if (! NILP (error_symbol))
1587 data = Fcons (error_symbol, data);
1589 string = Ferror_message_string (data);
1590 fatal ("%s", SDATA (string));
1593 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1595 void
1596 xsignal0 (Lisp_Object error_symbol)
1598 xsignal (error_symbol, Qnil);
1601 void
1602 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1604 xsignal (error_symbol, list1 (arg));
1607 void
1608 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1610 xsignal (error_symbol, list2 (arg1, arg2));
1613 void
1614 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1616 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1619 /* Signal `error' with message S, and additional arg ARG.
1620 If ARG is not a genuine list, make it a one-element list. */
1622 void
1623 signal_error (const char *s, Lisp_Object arg)
1625 Lisp_Object tortoise, hare;
1627 hare = tortoise = arg;
1628 while (CONSP (hare))
1630 hare = XCDR (hare);
1631 if (!CONSP (hare))
1632 break;
1634 hare = XCDR (hare);
1635 tortoise = XCDR (tortoise);
1637 if (EQ (hare, tortoise))
1638 break;
1641 if (!NILP (hare))
1642 arg = list1 (arg);
1644 xsignal (Qerror, Fcons (build_string (s), arg));
1648 /* Return true if LIST is a non-nil atom or
1649 a list containing one of CONDITIONS. */
1651 static bool
1652 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1654 if (NILP (list))
1655 return 0;
1656 if (! CONSP (list))
1657 return 1;
1659 while (CONSP (conditions))
1661 Lisp_Object this, tail;
1662 this = XCAR (conditions);
1663 for (tail = list; CONSP (tail); tail = XCDR (tail))
1664 if (EQ (XCAR (tail), this))
1665 return 1;
1666 conditions = XCDR (conditions);
1668 return 0;
1671 /* Return true if an error with condition-symbols CONDITIONS,
1672 and described by SIGNAL-DATA, should skip the debugger
1673 according to debugger-ignored-errors. */
1675 static bool
1676 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1678 Lisp_Object tail;
1679 bool first_string = 1;
1680 Lisp_Object error_message;
1682 error_message = Qnil;
1683 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1685 if (STRINGP (XCAR (tail)))
1687 if (first_string)
1689 error_message = Ferror_message_string (data);
1690 first_string = 0;
1693 if (fast_string_match (XCAR (tail), error_message) >= 0)
1694 return 1;
1696 else
1698 Lisp_Object contail;
1700 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1701 if (EQ (XCAR (tail), XCAR (contail)))
1702 return 1;
1706 return 0;
1709 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1710 SIG and DATA describe the signal. There are two ways to pass them:
1711 = SIG is the error symbol, and DATA is the rest of the data.
1712 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1713 This is for memory-full errors only. */
1714 static bool
1715 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1717 Lisp_Object combined_data;
1719 combined_data = Fcons (sig, data);
1721 if (
1722 /* Don't try to run the debugger with interrupts blocked.
1723 The editing loop would return anyway. */
1724 ! input_blocked_p ()
1725 && NILP (Vinhibit_debugger)
1726 /* Does user want to enter debugger for this kind of error? */
1727 && (EQ (sig, Qquit)
1728 ? debug_on_quit
1729 : wants_debugger (Vdebug_on_error, conditions))
1730 && ! skip_debugger (conditions, combined_data)
1731 /* RMS: What's this for? */
1732 && when_entered_debugger < num_nonmacro_input_events)
1734 call_debugger (list2 (Qerror, combined_data));
1735 return 1;
1738 return 0;
1741 static Lisp_Object
1742 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1744 register Lisp_Object h;
1746 /* t is used by handlers for all conditions, set up by C code. */
1747 if (EQ (handlers, Qt))
1748 return Qt;
1750 /* error is used similarly, but means print an error message
1751 and run the debugger if that is enabled. */
1752 if (EQ (handlers, Qerror))
1753 return Qt;
1755 for (h = handlers; CONSP (h); h = XCDR (h))
1757 Lisp_Object handler = XCAR (h);
1758 if (!NILP (Fmemq (handler, conditions)))
1759 return handlers;
1762 return Qnil;
1766 /* Format and return a string; called like vprintf. */
1767 Lisp_Object
1768 vformat_string (const char *m, va_list ap)
1770 char buf[4000];
1771 ptrdiff_t size = sizeof buf;
1772 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1773 char *buffer = buf;
1774 ptrdiff_t used;
1775 Lisp_Object string;
1777 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1778 string = make_string (buffer, used);
1779 if (buffer != buf)
1780 xfree (buffer);
1782 return string;
1785 /* Dump an error message; called like vprintf. */
1786 void
1787 verror (const char *m, va_list ap)
1789 xsignal1 (Qerror, vformat_string (m, ap));
1793 /* Dump an error message; called like printf. */
1795 /* VARARGS 1 */
1796 void
1797 error (const char *m, ...)
1799 va_list ap;
1800 va_start (ap, m);
1801 verror (m, ap);
1804 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1805 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1806 This means it contains a description for how to read arguments to give it.
1807 The value is nil for an invalid function or a symbol with no function
1808 definition.
1810 Interactively callable functions include strings and vectors (treated
1811 as keyboard macros), lambda-expressions that contain a top-level call
1812 to `interactive', autoload definitions made by `autoload' with non-nil
1813 fourth argument, and some of the built-in functions of Lisp.
1815 Also, a symbol satisfies `commandp' if its function definition does so.
1817 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1818 then strings and vectors are not accepted. */)
1819 (Lisp_Object function, Lisp_Object for_call_interactively)
1821 register Lisp_Object fun;
1822 register Lisp_Object funcar;
1823 Lisp_Object if_prop = Qnil;
1825 fun = function;
1827 fun = indirect_function (fun); /* Check cycles. */
1828 if (NILP (fun))
1829 return Qnil;
1831 /* Check an `interactive-form' property if present, analogous to the
1832 function-documentation property. */
1833 fun = function;
1834 while (SYMBOLP (fun))
1836 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1837 if (!NILP (tmp))
1838 if_prop = Qt;
1839 fun = Fsymbol_function (fun);
1842 /* Emacs primitives are interactive if their DEFUN specifies an
1843 interactive spec. */
1844 if (SUBRP (fun))
1845 return XSUBR (fun)->intspec ? Qt : if_prop;
1847 /* Bytecode objects are interactive if they are long enough to
1848 have an element whose index is COMPILED_INTERACTIVE, which is
1849 where the interactive spec is stored. */
1850 else if (COMPILEDP (fun))
1851 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1852 ? Qt : if_prop);
1854 /* Strings and vectors are keyboard macros. */
1855 if (STRINGP (fun) || VECTORP (fun))
1856 return (NILP (for_call_interactively) ? Qt : Qnil);
1858 /* Lists may represent commands. */
1859 if (!CONSP (fun))
1860 return Qnil;
1861 funcar = XCAR (fun);
1862 if (EQ (funcar, Qclosure))
1863 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1864 ? Qt : if_prop);
1865 else if (EQ (funcar, Qlambda))
1866 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1867 else if (EQ (funcar, Qautoload))
1868 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1869 else
1870 return Qnil;
1873 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1874 doc: /* Define FUNCTION to autoload from FILE.
1875 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1876 Third arg DOCSTRING is documentation for the function.
1877 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1878 Fifth arg TYPE indicates the type of the object:
1879 nil or omitted says FUNCTION is a function,
1880 `keymap' says FUNCTION is really a keymap, and
1881 `macro' or t says FUNCTION is really a macro.
1882 Third through fifth args give info about the real definition.
1883 They default to nil.
1884 If FUNCTION is already defined other than as an autoload,
1885 this does nothing and returns nil. */)
1886 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1888 CHECK_SYMBOL (function);
1889 CHECK_STRING (file);
1891 /* If function is defined and not as an autoload, don't override. */
1892 if (!NILP (XSYMBOL (function)->function)
1893 && !AUTOLOADP (XSYMBOL (function)->function))
1894 return Qnil;
1896 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1897 /* `read1' in lread.c has found the docstring starting with "\
1898 and assumed the docstring will be provided by Snarf-documentation, so it
1899 passed us 0 instead. But that leads to accidental sharing in purecopy's
1900 hash-consing, so we use a (hopefully) unique integer instead. */
1901 docstring = make_number (XHASH (function));
1902 return Fdefalias (function,
1903 list5 (Qautoload, file, docstring, interactive, type),
1904 Qnil);
1907 void
1908 un_autoload (Lisp_Object oldqueue)
1910 Lisp_Object queue, first, second;
1912 /* Queue to unwind is current value of Vautoload_queue.
1913 oldqueue is the shadowed value to leave in Vautoload_queue. */
1914 queue = Vautoload_queue;
1915 Vautoload_queue = oldqueue;
1916 while (CONSP (queue))
1918 first = XCAR (queue);
1919 second = Fcdr (first);
1920 first = Fcar (first);
1921 if (EQ (first, make_number (0)))
1922 Vfeatures = second;
1923 else
1924 Ffset (first, second);
1925 queue = XCDR (queue);
1929 /* Load an autoloaded function.
1930 FUNNAME is the symbol which is the function's name.
1931 FUNDEF is the autoload definition (a list). */
1933 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1934 doc: /* Load FUNDEF which should be an autoload.
1935 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1936 in which case the function returns the new autoloaded function value.
1937 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1938 it defines a macro. */)
1939 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1941 ptrdiff_t count = SPECPDL_INDEX ();
1943 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1944 return fundef;
1946 if (EQ (macro_only, Qmacro))
1948 Lisp_Object kind = Fnth (make_number (4), fundef);
1949 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1950 return fundef;
1953 /* This is to make sure that loadup.el gives a clear picture
1954 of what files are preloaded and when. */
1955 if (! NILP (Vpurify_flag))
1956 error ("Attempt to autoload %s while preparing to dump",
1957 SDATA (SYMBOL_NAME (funname)));
1959 CHECK_SYMBOL (funname);
1961 /* Preserve the match data. */
1962 record_unwind_save_match_data ();
1964 /* If autoloading gets an error (which includes the error of failing
1965 to define the function being called), we use Vautoload_queue
1966 to undo function definitions and `provide' calls made by
1967 the function. We do this in the specific case of autoloading
1968 because autoloading is not an explicit request "load this file",
1969 but rather a request to "call this function".
1971 The value saved here is to be restored into Vautoload_queue. */
1972 record_unwind_protect (un_autoload, Vautoload_queue);
1973 Vautoload_queue = Qt;
1974 /* If `macro_only', assume this autoload to be a "best-effort",
1975 so don't signal an error if autoloading fails. */
1976 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1978 /* Once loading finishes, don't undo it. */
1979 Vautoload_queue = Qt;
1980 unbind_to (count, Qnil);
1982 if (NILP (funname))
1983 return Qnil;
1984 else
1986 Lisp_Object fun = Findirect_function (funname, Qnil);
1988 if (!NILP (Fequal (fun, fundef)))
1989 error ("Autoloading failed to define function %s",
1990 SDATA (SYMBOL_NAME (funname)));
1991 else
1992 return fun;
1997 DEFUN ("eval", Feval, Seval, 1, 2, 0,
1998 doc: /* Evaluate FORM and return its value.
1999 If LEXICAL is t, evaluate using lexical scoping.
2000 LEXICAL can also be an actual lexical environment, in the form of an
2001 alist mapping symbols to their value. */)
2002 (Lisp_Object form, Lisp_Object lexical)
2004 ptrdiff_t count = SPECPDL_INDEX ();
2005 specbind (Qinternal_interpreter_environment,
2006 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2007 return unbind_to (count, eval_sub (form));
2010 /* Grow the specpdl stack by one entry.
2011 The caller should have already initialized the entry.
2012 Signal an error on stack overflow.
2014 Make sure that there is always one unused entry past the top of the
2015 stack, so that the just-initialized entry is safely unwound if
2016 memory exhausted and an error is signaled here. Also, allocate a
2017 never-used entry just before the bottom of the stack; sometimes its
2018 address is taken. */
2020 static void
2021 grow_specpdl (void)
2023 specpdl_ptr++;
2025 if (specpdl_ptr == specpdl + specpdl_size)
2027 ptrdiff_t count = SPECPDL_INDEX ();
2028 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2029 union specbinding *pdlvec = specpdl - 1;
2030 ptrdiff_t pdlvecsize = specpdl_size + 1;
2031 if (max_size <= specpdl_size)
2033 if (max_specpdl_size < 400)
2034 max_size = max_specpdl_size = 400;
2035 if (max_size <= specpdl_size)
2036 signal_error ("Variable binding depth exceeds max-specpdl-size",
2037 Qnil);
2039 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2040 specpdl = pdlvec + 1;
2041 specpdl_size = pdlvecsize - 1;
2042 specpdl_ptr = specpdl + count;
2046 ptrdiff_t
2047 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2049 ptrdiff_t count = SPECPDL_INDEX ();
2051 eassert (nargs >= UNEVALLED);
2052 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2053 specpdl_ptr->bt.debug_on_exit = false;
2054 specpdl_ptr->bt.function = function;
2055 specpdl_ptr->bt.args = args;
2056 specpdl_ptr->bt.nargs = nargs;
2057 grow_specpdl ();
2059 return count;
2062 /* Eval a sub-expression of the current expression (i.e. in the same
2063 lexical scope). */
2064 Lisp_Object
2065 eval_sub (Lisp_Object form)
2067 Lisp_Object fun, val, original_fun, original_args;
2068 Lisp_Object funcar;
2069 ptrdiff_t count;
2071 /* Declare here, as this array may be accessed by call_debugger near
2072 the end of this function. See Bug#21245. */
2073 Lisp_Object argvals[8];
2075 if (SYMBOLP (form))
2077 /* Look up its binding in the lexical environment.
2078 We do not pay attention to the declared_special flag here, since we
2079 already did that when let-binding the variable. */
2080 Lisp_Object lex_binding
2081 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2082 ? Fassq (form, Vinternal_interpreter_environment)
2083 : Qnil;
2084 if (CONSP (lex_binding))
2085 return XCDR (lex_binding);
2086 else
2087 return Fsymbol_value (form);
2090 if (!CONSP (form))
2091 return form;
2093 QUIT;
2095 maybe_gc ();
2097 if (++lisp_eval_depth > max_lisp_eval_depth)
2099 if (max_lisp_eval_depth < 100)
2100 max_lisp_eval_depth = 100;
2101 if (lisp_eval_depth > max_lisp_eval_depth)
2102 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2105 original_fun = XCAR (form);
2106 original_args = XCDR (form);
2108 /* This also protects them from gc. */
2109 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2111 if (debug_on_next_call)
2112 do_debug_on_call (Qt, count);
2114 /* At this point, only original_fun and original_args
2115 have values that will be used below. */
2116 retry:
2118 /* Optimize for no indirection. */
2119 fun = original_fun;
2120 if (!SYMBOLP (fun))
2121 fun = Ffunction (Fcons (fun, Qnil));
2122 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2123 fun = indirect_function (fun);
2125 if (SUBRP (fun))
2127 Lisp_Object args_left = original_args;
2128 Lisp_Object numargs = Flength (args_left);
2130 check_cons_list ();
2132 if (XINT (numargs) < XSUBR (fun)->min_args
2133 || (XSUBR (fun)->max_args >= 0
2134 && XSUBR (fun)->max_args < XINT (numargs)))
2135 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2137 else if (XSUBR (fun)->max_args == UNEVALLED)
2138 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2139 else if (XSUBR (fun)->max_args == MANY)
2141 /* Pass a vector of evaluated arguments. */
2142 Lisp_Object *vals;
2143 ptrdiff_t argnum = 0;
2144 USE_SAFE_ALLOCA;
2146 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2148 while (!NILP (args_left))
2150 vals[argnum++] = eval_sub (Fcar (args_left));
2151 args_left = Fcdr (args_left);
2154 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2156 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2158 check_cons_list ();
2159 lisp_eval_depth--;
2160 /* Do the debug-on-exit now, while VALS still exists. */
2161 if (backtrace_debug_on_exit (specpdl + count))
2162 val = call_debugger (list2 (Qexit, val));
2163 SAFE_FREE ();
2164 specpdl_ptr--;
2165 return val;
2167 else
2169 int i, maxargs = XSUBR (fun)->max_args;
2171 for (i = 0; i < maxargs; i++)
2173 argvals[i] = eval_sub (Fcar (args_left));
2174 args_left = Fcdr (args_left);
2177 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2179 switch (i)
2181 case 0:
2182 val = (XSUBR (fun)->function.a0 ());
2183 break;
2184 case 1:
2185 val = (XSUBR (fun)->function.a1 (argvals[0]));
2186 break;
2187 case 2:
2188 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2189 break;
2190 case 3:
2191 val = (XSUBR (fun)->function.a3
2192 (argvals[0], argvals[1], argvals[2]));
2193 break;
2194 case 4:
2195 val = (XSUBR (fun)->function.a4
2196 (argvals[0], argvals[1], argvals[2], argvals[3]));
2197 break;
2198 case 5:
2199 val = (XSUBR (fun)->function.a5
2200 (argvals[0], argvals[1], argvals[2], argvals[3],
2201 argvals[4]));
2202 break;
2203 case 6:
2204 val = (XSUBR (fun)->function.a6
2205 (argvals[0], argvals[1], argvals[2], argvals[3],
2206 argvals[4], argvals[5]));
2207 break;
2208 case 7:
2209 val = (XSUBR (fun)->function.a7
2210 (argvals[0], argvals[1], argvals[2], argvals[3],
2211 argvals[4], argvals[5], argvals[6]));
2212 break;
2214 case 8:
2215 val = (XSUBR (fun)->function.a8
2216 (argvals[0], argvals[1], argvals[2], argvals[3],
2217 argvals[4], argvals[5], argvals[6], argvals[7]));
2218 break;
2220 default:
2221 /* Someone has created a subr that takes more arguments than
2222 is supported by this code. We need to either rewrite the
2223 subr to use a different argument protocol, or add more
2224 cases to this switch. */
2225 emacs_abort ();
2229 else if (COMPILEDP (fun))
2230 return apply_lambda (fun, original_args, count);
2231 else
2233 if (NILP (fun))
2234 xsignal1 (Qvoid_function, original_fun);
2235 if (!CONSP (fun))
2236 xsignal1 (Qinvalid_function, original_fun);
2237 funcar = XCAR (fun);
2238 if (!SYMBOLP (funcar))
2239 xsignal1 (Qinvalid_function, original_fun);
2240 if (EQ (funcar, Qautoload))
2242 Fautoload_do_load (fun, original_fun, Qnil);
2243 goto retry;
2245 if (EQ (funcar, Qmacro))
2247 ptrdiff_t count1 = SPECPDL_INDEX ();
2248 Lisp_Object exp;
2249 /* Bind lexical-binding during expansion of the macro, so the
2250 macro can know reliably if the code it outputs will be
2251 interpreted using lexical-binding or not. */
2252 specbind (Qlexical_binding,
2253 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2254 exp = apply1 (Fcdr (fun), original_args);
2255 unbind_to (count1, Qnil);
2256 val = eval_sub (exp);
2258 else if (EQ (funcar, Qlambda)
2259 || EQ (funcar, Qclosure))
2260 return apply_lambda (fun, original_args, count);
2261 else
2262 xsignal1 (Qinvalid_function, original_fun);
2264 check_cons_list ();
2266 lisp_eval_depth--;
2267 if (backtrace_debug_on_exit (specpdl + count))
2268 val = call_debugger (list2 (Qexit, val));
2269 specpdl_ptr--;
2271 return val;
2274 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2275 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2276 Then return the value FUNCTION returns.
2277 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2278 usage: (apply FUNCTION &rest ARGUMENTS) */)
2279 (ptrdiff_t nargs, Lisp_Object *args)
2281 ptrdiff_t i, numargs, funcall_nargs;
2282 register Lisp_Object *funcall_args = NULL;
2283 register Lisp_Object spread_arg = args[nargs - 1];
2284 Lisp_Object fun = args[0];
2285 Lisp_Object retval;
2286 USE_SAFE_ALLOCA;
2288 CHECK_LIST (spread_arg);
2290 numargs = XINT (Flength (spread_arg));
2292 if (numargs == 0)
2293 return Ffuncall (nargs - 1, args);
2294 else if (numargs == 1)
2296 args [nargs - 1] = XCAR (spread_arg);
2297 return Ffuncall (nargs, args);
2300 numargs += nargs - 2;
2302 /* Optimize for no indirection. */
2303 if (SYMBOLP (fun) && !NILP (fun)
2304 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2306 fun = indirect_function (fun);
2307 if (NILP (fun))
2308 /* Let funcall get the error. */
2309 fun = args[0];
2312 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2313 /* Don't hide an error by adding missing arguments. */
2314 && numargs >= XSUBR (fun)->min_args)
2316 /* Avoid making funcall cons up a yet another new vector of arguments
2317 by explicitly supplying nil's for optional values. */
2318 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2319 memclear (funcall_args + numargs + 1,
2320 (XSUBR (fun)->max_args - numargs) * word_size);
2321 funcall_nargs = 1 + XSUBR (fun)->max_args;
2323 else
2324 { /* We add 1 to numargs because funcall_args includes the
2325 function itself as well as its arguments. */
2326 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2327 funcall_nargs = 1 + numargs;
2330 memcpy (funcall_args, args, nargs * word_size);
2331 /* Spread the last arg we got. Its first element goes in
2332 the slot that it used to occupy, hence this value of I. */
2333 i = nargs - 1;
2334 while (!NILP (spread_arg))
2336 funcall_args [i++] = XCAR (spread_arg);
2337 spread_arg = XCDR (spread_arg);
2340 retval = Ffuncall (funcall_nargs, funcall_args);
2342 SAFE_FREE ();
2343 return retval;
2346 /* Run hook variables in various ways. */
2348 static Lisp_Object
2349 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2351 Ffuncall (nargs, args);
2352 return Qnil;
2355 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2356 doc: /* Run each hook in HOOKS.
2357 Each argument should be a symbol, a hook variable.
2358 These symbols are processed in the order specified.
2359 If a hook symbol has a non-nil value, that value may be a function
2360 or a list of functions to be called to run the hook.
2361 If the value is a function, it is called with no arguments.
2362 If it is a list, the elements are called, in order, with no arguments.
2364 Major modes should not use this function directly to run their mode
2365 hook; they should use `run-mode-hooks' instead.
2367 Do not use `make-local-variable' to make a hook variable buffer-local.
2368 Instead, use `add-hook' and specify t for the LOCAL argument.
2369 usage: (run-hooks &rest HOOKS) */)
2370 (ptrdiff_t nargs, Lisp_Object *args)
2372 ptrdiff_t i;
2374 for (i = 0; i < nargs; i++)
2375 run_hook (args[i]);
2377 return Qnil;
2380 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2381 Srun_hook_with_args, 1, MANY, 0,
2382 doc: /* Run HOOK with the specified arguments ARGS.
2383 HOOK should be a symbol, a hook variable. The value of HOOK
2384 may be nil, a function, or a list of functions. Call each
2385 function in order with arguments ARGS. The final return value
2386 is unspecified.
2388 Do not use `make-local-variable' to make a hook variable buffer-local.
2389 Instead, use `add-hook' and specify t for the LOCAL argument.
2390 usage: (run-hook-with-args HOOK &rest ARGS) */)
2391 (ptrdiff_t nargs, Lisp_Object *args)
2393 return run_hook_with_args (nargs, args, funcall_nil);
2396 /* NB this one still documents a specific non-nil return value.
2397 (As did run-hook-with-args and run-hook-with-args-until-failure
2398 until they were changed in 24.1.) */
2399 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2400 Srun_hook_with_args_until_success, 1, MANY, 0,
2401 doc: /* Run HOOK with the specified arguments ARGS.
2402 HOOK should be a symbol, a hook variable. The value of HOOK
2403 may be nil, a function, or a list of functions. Call each
2404 function in order with arguments ARGS, stopping at the first
2405 one that returns non-nil, and return that value. Otherwise (if
2406 all functions return nil, or if there are no functions to call),
2407 return nil.
2409 Do not use `make-local-variable' to make a hook variable buffer-local.
2410 Instead, use `add-hook' and specify t for the LOCAL argument.
2411 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2412 (ptrdiff_t nargs, Lisp_Object *args)
2414 return run_hook_with_args (nargs, args, Ffuncall);
2417 static Lisp_Object
2418 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2420 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2423 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2424 Srun_hook_with_args_until_failure, 1, MANY, 0,
2425 doc: /* Run HOOK with the specified arguments ARGS.
2426 HOOK should be a symbol, a hook variable. The value of HOOK
2427 may be nil, a function, or a list of functions. Call each
2428 function in order with arguments ARGS, stopping at the first
2429 one that returns nil, and return nil. Otherwise (if all functions
2430 return non-nil, or if there are no functions to call), return non-nil
2431 \(do not rely on the precise return value in this case).
2433 Do not use `make-local-variable' to make a hook variable buffer-local.
2434 Instead, use `add-hook' and specify t for the LOCAL argument.
2435 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2436 (ptrdiff_t nargs, Lisp_Object *args)
2438 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2441 static Lisp_Object
2442 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2444 Lisp_Object tmp = args[0], ret;
2445 args[0] = args[1];
2446 args[1] = tmp;
2447 ret = Ffuncall (nargs, args);
2448 args[1] = args[0];
2449 args[0] = tmp;
2450 return ret;
2453 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2454 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2455 I.e. instead of calling each function FUN directly with arguments ARGS,
2456 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2457 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2458 aborts and returns that value.
2459 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2460 (ptrdiff_t nargs, Lisp_Object *args)
2462 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2465 /* ARGS[0] should be a hook symbol.
2466 Call each of the functions in the hook value, passing each of them
2467 as arguments all the rest of ARGS (all NARGS - 1 elements).
2468 FUNCALL specifies how to call each function on the hook. */
2470 Lisp_Object
2471 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2472 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2474 Lisp_Object sym, val, ret = Qnil;
2476 /* If we are dying or still initializing,
2477 don't do anything--it would probably crash if we tried. */
2478 if (NILP (Vrun_hooks))
2479 return Qnil;
2481 sym = args[0];
2482 val = find_symbol_value (sym);
2484 if (EQ (val, Qunbound) || NILP (val))
2485 return ret;
2486 else if (!CONSP (val) || FUNCTIONP (val))
2488 args[0] = val;
2489 return funcall (nargs, args);
2491 else
2493 Lisp_Object global_vals = Qnil;
2495 for (;
2496 CONSP (val) && NILP (ret);
2497 val = XCDR (val))
2499 if (EQ (XCAR (val), Qt))
2501 /* t indicates this hook has a local binding;
2502 it means to run the global binding too. */
2503 global_vals = Fdefault_value (sym);
2504 if (NILP (global_vals)) continue;
2506 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2508 args[0] = global_vals;
2509 ret = funcall (nargs, args);
2511 else
2513 for (;
2514 CONSP (global_vals) && NILP (ret);
2515 global_vals = XCDR (global_vals))
2517 args[0] = XCAR (global_vals);
2518 /* In a global value, t should not occur. If it does, we
2519 must ignore it to avoid an endless loop. */
2520 if (!EQ (args[0], Qt))
2521 ret = funcall (nargs, args);
2525 else
2527 args[0] = XCAR (val);
2528 ret = funcall (nargs, args);
2532 return ret;
2536 /* Run the hook HOOK, giving each function no args. */
2538 void
2539 run_hook (Lisp_Object hook)
2541 Frun_hook_with_args (1, &hook);
2544 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2546 void
2547 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2549 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2552 /* Apply fn to arg. */
2553 Lisp_Object
2554 apply1 (Lisp_Object fn, Lisp_Object arg)
2556 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2559 /* Call function fn on no arguments. */
2560 Lisp_Object
2561 call0 (Lisp_Object fn)
2563 return Ffuncall (1, &fn);
2566 /* Call function fn with 1 argument arg1. */
2567 /* ARGSUSED */
2568 Lisp_Object
2569 call1 (Lisp_Object fn, Lisp_Object arg1)
2571 return CALLN (Ffuncall, fn, arg1);
2574 /* Call function fn with 2 arguments arg1, arg2. */
2575 /* ARGSUSED */
2576 Lisp_Object
2577 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2579 return CALLN (Ffuncall, fn, arg1, arg2);
2582 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2583 /* ARGSUSED */
2584 Lisp_Object
2585 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2587 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2590 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2591 /* ARGSUSED */
2592 Lisp_Object
2593 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2594 Lisp_Object arg4)
2596 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2599 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2600 /* ARGSUSED */
2601 Lisp_Object
2602 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2603 Lisp_Object arg4, Lisp_Object arg5)
2605 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2608 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2609 /* ARGSUSED */
2610 Lisp_Object
2611 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2612 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2614 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2617 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2618 /* ARGSUSED */
2619 Lisp_Object
2620 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2621 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2623 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2626 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2627 doc: /* Non-nil if OBJECT is a function. */)
2628 (Lisp_Object object)
2630 if (FUNCTIONP (object))
2631 return Qt;
2632 return Qnil;
2635 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2636 doc: /* Call first argument as a function, passing remaining arguments to it.
2637 Return the value that function returns.
2638 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2639 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2640 (ptrdiff_t nargs, Lisp_Object *args)
2642 Lisp_Object fun, original_fun;
2643 Lisp_Object funcar;
2644 ptrdiff_t numargs = nargs - 1;
2645 Lisp_Object lisp_numargs;
2646 Lisp_Object val;
2647 Lisp_Object *internal_args;
2648 ptrdiff_t count;
2650 QUIT;
2652 if (++lisp_eval_depth > max_lisp_eval_depth)
2654 if (max_lisp_eval_depth < 100)
2655 max_lisp_eval_depth = 100;
2656 if (lisp_eval_depth > max_lisp_eval_depth)
2657 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2660 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2662 maybe_gc ();
2664 if (debug_on_next_call)
2665 do_debug_on_call (Qlambda, count);
2667 check_cons_list ();
2669 original_fun = args[0];
2671 retry:
2673 /* Optimize for no indirection. */
2674 fun = original_fun;
2675 if (SYMBOLP (fun) && !NILP (fun)
2676 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2677 fun = indirect_function (fun);
2679 if (SUBRP (fun))
2681 if (numargs < XSUBR (fun)->min_args
2682 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2684 XSETFASTINT (lisp_numargs, numargs);
2685 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2688 else if (XSUBR (fun)->max_args == UNEVALLED)
2689 xsignal1 (Qinvalid_function, original_fun);
2691 else if (XSUBR (fun)->max_args == MANY)
2692 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2693 else
2695 Lisp_Object internal_argbuf[8];
2696 if (XSUBR (fun)->max_args > numargs)
2698 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2699 internal_args = internal_argbuf;
2700 memcpy (internal_args, args + 1, numargs * word_size);
2701 memclear (internal_args + numargs,
2702 (XSUBR (fun)->max_args - numargs) * word_size);
2704 else
2705 internal_args = args + 1;
2706 switch (XSUBR (fun)->max_args)
2708 case 0:
2709 val = (XSUBR (fun)->function.a0 ());
2710 break;
2711 case 1:
2712 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2713 break;
2714 case 2:
2715 val = (XSUBR (fun)->function.a2
2716 (internal_args[0], internal_args[1]));
2717 break;
2718 case 3:
2719 val = (XSUBR (fun)->function.a3
2720 (internal_args[0], internal_args[1], internal_args[2]));
2721 break;
2722 case 4:
2723 val = (XSUBR (fun)->function.a4
2724 (internal_args[0], internal_args[1], internal_args[2],
2725 internal_args[3]));
2726 break;
2727 case 5:
2728 val = (XSUBR (fun)->function.a5
2729 (internal_args[0], internal_args[1], internal_args[2],
2730 internal_args[3], internal_args[4]));
2731 break;
2732 case 6:
2733 val = (XSUBR (fun)->function.a6
2734 (internal_args[0], internal_args[1], internal_args[2],
2735 internal_args[3], internal_args[4], internal_args[5]));
2736 break;
2737 case 7:
2738 val = (XSUBR (fun)->function.a7
2739 (internal_args[0], internal_args[1], internal_args[2],
2740 internal_args[3], internal_args[4], internal_args[5],
2741 internal_args[6]));
2742 break;
2744 case 8:
2745 val = (XSUBR (fun)->function.a8
2746 (internal_args[0], internal_args[1], internal_args[2],
2747 internal_args[3], internal_args[4], internal_args[5],
2748 internal_args[6], internal_args[7]));
2749 break;
2751 default:
2753 /* If a subr takes more than 8 arguments without using MANY
2754 or UNEVALLED, we need to extend this function to support it.
2755 Until this is done, there is no way to call the function. */
2756 emacs_abort ();
2760 else if (COMPILEDP (fun))
2761 val = funcall_lambda (fun, numargs, args + 1);
2762 else
2764 if (NILP (fun))
2765 xsignal1 (Qvoid_function, original_fun);
2766 if (!CONSP (fun))
2767 xsignal1 (Qinvalid_function, original_fun);
2768 funcar = XCAR (fun);
2769 if (!SYMBOLP (funcar))
2770 xsignal1 (Qinvalid_function, original_fun);
2771 if (EQ (funcar, Qlambda)
2772 || EQ (funcar, Qclosure))
2773 val = funcall_lambda (fun, numargs, args + 1);
2774 else if (EQ (funcar, Qautoload))
2776 Fautoload_do_load (fun, original_fun, Qnil);
2777 check_cons_list ();
2778 goto retry;
2780 else
2781 xsignal1 (Qinvalid_function, original_fun);
2783 check_cons_list ();
2784 lisp_eval_depth--;
2785 if (backtrace_debug_on_exit (specpdl + count))
2786 val = call_debugger (list2 (Qexit, val));
2787 specpdl_ptr--;
2788 return val;
2791 static Lisp_Object
2792 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2794 Lisp_Object args_left;
2795 ptrdiff_t i;
2796 EMACS_INT numargs;
2797 Lisp_Object *arg_vector;
2798 Lisp_Object tem;
2799 USE_SAFE_ALLOCA;
2801 numargs = XFASTINT (Flength (args));
2802 SAFE_ALLOCA_LISP (arg_vector, numargs);
2803 args_left = args;
2805 for (i = 0; i < numargs; )
2807 tem = Fcar (args_left), args_left = Fcdr (args_left);
2808 tem = eval_sub (tem);
2809 arg_vector[i++] = tem;
2812 set_backtrace_args (specpdl + count, arg_vector, i);
2813 tem = funcall_lambda (fun, numargs, arg_vector);
2815 check_cons_list ();
2816 lisp_eval_depth--;
2817 /* Do the debug-on-exit now, while arg_vector still exists. */
2818 if (backtrace_debug_on_exit (specpdl + count))
2819 tem = call_debugger (list2 (Qexit, tem));
2820 SAFE_FREE ();
2821 specpdl_ptr--;
2822 return tem;
2825 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2826 and return the result of evaluation.
2827 FUN must be either a lambda-expression or a compiled-code object. */
2829 static Lisp_Object
2830 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2831 register Lisp_Object *arg_vector)
2833 Lisp_Object val, syms_left, next, lexenv;
2834 ptrdiff_t count = SPECPDL_INDEX ();
2835 ptrdiff_t i;
2836 bool optional, rest;
2838 if (CONSP (fun))
2840 if (EQ (XCAR (fun), Qclosure))
2842 fun = XCDR (fun); /* Drop `closure'. */
2843 lexenv = XCAR (fun);
2844 CHECK_LIST_CONS (fun, fun);
2846 else
2847 lexenv = Qnil;
2848 syms_left = XCDR (fun);
2849 if (CONSP (syms_left))
2850 syms_left = XCAR (syms_left);
2851 else
2852 xsignal1 (Qinvalid_function, fun);
2854 else if (COMPILEDP (fun))
2856 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2857 if (size <= COMPILED_STACK_DEPTH)
2858 xsignal1 (Qinvalid_function, fun);
2859 syms_left = AREF (fun, COMPILED_ARGLIST);
2860 if (INTEGERP (syms_left))
2861 /* A byte-code object with a non-nil `push args' slot means we
2862 shouldn't bind any arguments, instead just call the byte-code
2863 interpreter directly; it will push arguments as necessary.
2865 Byte-code objects with either a non-existent, or a nil value for
2866 the `push args' slot (the default), have dynamically-bound
2867 arguments, and use the argument-binding code below instead (as do
2868 all interpreted functions, even lexically bound ones). */
2870 /* If we have not actually read the bytecode string
2871 and constants vector yet, fetch them from the file. */
2872 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2873 Ffetch_bytecode (fun);
2874 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2875 AREF (fun, COMPILED_CONSTANTS),
2876 AREF (fun, COMPILED_STACK_DEPTH),
2877 syms_left,
2878 nargs, arg_vector);
2880 lexenv = Qnil;
2882 else
2883 emacs_abort ();
2885 i = optional = rest = 0;
2886 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2888 QUIT;
2890 next = XCAR (syms_left);
2891 if (!SYMBOLP (next))
2892 xsignal1 (Qinvalid_function, fun);
2894 if (EQ (next, Qand_rest))
2895 rest = 1;
2896 else if (EQ (next, Qand_optional))
2897 optional = 1;
2898 else
2900 Lisp_Object arg;
2901 if (rest)
2903 arg = Flist (nargs - i, &arg_vector[i]);
2904 i = nargs;
2906 else if (i < nargs)
2907 arg = arg_vector[i++];
2908 else if (!optional)
2909 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2910 else
2911 arg = Qnil;
2913 /* Bind the argument. */
2914 if (!NILP (lexenv) && SYMBOLP (next))
2915 /* Lexically bind NEXT by adding it to the lexenv alist. */
2916 lexenv = Fcons (Fcons (next, arg), lexenv);
2917 else
2918 /* Dynamically bind NEXT. */
2919 specbind (next, arg);
2923 if (!NILP (syms_left))
2924 xsignal1 (Qinvalid_function, fun);
2925 else if (i < nargs)
2926 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2928 if (!EQ (lexenv, Vinternal_interpreter_environment))
2929 /* Instantiate a new lexical environment. */
2930 specbind (Qinternal_interpreter_environment, lexenv);
2932 if (CONSP (fun))
2933 val = Fprogn (XCDR (XCDR (fun)));
2934 else
2936 /* If we have not actually read the bytecode string
2937 and constants vector yet, fetch them from the file. */
2938 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2939 Ffetch_bytecode (fun);
2940 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2941 AREF (fun, COMPILED_CONSTANTS),
2942 AREF (fun, COMPILED_STACK_DEPTH),
2943 Qnil, 0, 0);
2946 return unbind_to (count, val);
2949 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
2950 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
2951 FUNCTION must be a function of some kind.
2952 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
2953 of args. MAX is the maximum number, or the symbol `many', for a
2954 function with `&rest' args, or `unevalled' for a special form. */)
2955 (Lisp_Object function)
2957 Lisp_Object original;
2958 Lisp_Object funcar;
2959 Lisp_Object result;
2961 original = function;
2963 retry:
2965 /* Optimize for no indirection. */
2966 function = original;
2967 if (SYMBOLP (function) && !NILP (function))
2969 function = XSYMBOL (function)->function;
2970 if (SYMBOLP (function))
2971 function = indirect_function (function);
2974 if (CONSP (function) && EQ (XCAR (function), Qmacro))
2975 function = XCDR (function);
2977 if (SUBRP (function))
2978 result = Fsubr_arity (function);
2979 else if (COMPILEDP (function))
2980 result = lambda_arity (function);
2981 else
2983 if (NILP (function))
2984 xsignal1 (Qvoid_function, original);
2985 if (!CONSP (function))
2986 xsignal1 (Qinvalid_function, original);
2987 funcar = XCAR (function);
2988 if (!SYMBOLP (funcar))
2989 xsignal1 (Qinvalid_function, original);
2990 if (EQ (funcar, Qlambda)
2991 || EQ (funcar, Qclosure))
2992 result = lambda_arity (function);
2993 else if (EQ (funcar, Qautoload))
2995 Fautoload_do_load (function, original, Qnil);
2996 goto retry;
2998 else
2999 xsignal1 (Qinvalid_function, original);
3001 return result;
3004 /* FUN must be either a lambda-expression or a compiled-code object. */
3005 static Lisp_Object
3006 lambda_arity (Lisp_Object fun)
3008 Lisp_Object syms_left;
3010 if (CONSP (fun))
3012 if (EQ (XCAR (fun), Qclosure))
3014 fun = XCDR (fun); /* Drop `closure'. */
3015 CHECK_LIST_CONS (fun, fun);
3017 syms_left = XCDR (fun);
3018 if (CONSP (syms_left))
3019 syms_left = XCAR (syms_left);
3020 else
3021 xsignal1 (Qinvalid_function, fun);
3023 else if (COMPILEDP (fun))
3025 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3026 if (size <= COMPILED_STACK_DEPTH)
3027 xsignal1 (Qinvalid_function, fun);
3028 syms_left = AREF (fun, COMPILED_ARGLIST);
3029 if (INTEGERP (syms_left))
3030 return get_byte_code_arity (syms_left);
3032 else
3033 emacs_abort ();
3035 EMACS_INT minargs = 0, maxargs = 0;
3036 bool optional = false;
3037 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3039 Lisp_Object next = XCAR (syms_left);
3040 if (!SYMBOLP (next))
3041 xsignal1 (Qinvalid_function, fun);
3043 if (EQ (next, Qand_rest))
3044 return Fcons (make_number (minargs), Qmany);
3045 else if (EQ (next, Qand_optional))
3046 optional = true;
3047 else
3049 if (!optional)
3050 minargs++;
3051 maxargs++;
3055 if (!NILP (syms_left))
3056 xsignal1 (Qinvalid_function, fun);
3058 return Fcons (make_number (minargs), make_number (maxargs));
3061 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3062 1, 1, 0,
3063 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3064 (Lisp_Object object)
3066 Lisp_Object tem;
3068 if (COMPILEDP (object))
3070 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3071 if (size <= COMPILED_STACK_DEPTH)
3072 xsignal1 (Qinvalid_function, object);
3073 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3075 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3076 if (!CONSP (tem))
3078 tem = AREF (object, COMPILED_BYTECODE);
3079 if (CONSP (tem) && STRINGP (XCAR (tem)))
3080 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3081 else
3082 error ("Invalid byte code");
3084 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3085 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3088 return object;
3091 /* Return true if SYMBOL currently has a let-binding
3092 which was made in the buffer that is now current. */
3094 bool
3095 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3097 union specbinding *p;
3098 Lisp_Object buf = Fcurrent_buffer ();
3100 for (p = specpdl_ptr; p > specpdl; )
3101 if ((--p)->kind > SPECPDL_LET)
3103 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3104 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3105 if (symbol == let_bound_symbol
3106 && EQ (specpdl_where (p), buf))
3107 return 1;
3110 return 0;
3113 bool
3114 let_shadows_global_binding_p (Lisp_Object symbol)
3116 union specbinding *p;
3118 for (p = specpdl_ptr; p > specpdl; )
3119 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3120 return 1;
3122 return 0;
3125 /* `specpdl_ptr' describes which variable is
3126 let-bound, so it can be properly undone when we unbind_to.
3127 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3128 - SYMBOL is the variable being bound. Note that it should not be
3129 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3130 to record V2 here).
3131 - WHERE tells us in which buffer the binding took place.
3132 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3133 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3134 i.e. bindings to the default value of a variable which can be
3135 buffer-local. */
3137 void
3138 specbind (Lisp_Object symbol, Lisp_Object value)
3140 struct Lisp_Symbol *sym;
3142 CHECK_SYMBOL (symbol);
3143 sym = XSYMBOL (symbol);
3145 start:
3146 switch (sym->redirect)
3148 case SYMBOL_VARALIAS:
3149 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3150 case SYMBOL_PLAINVAL:
3151 /* The most common case is that of a non-constant symbol with a
3152 trivial value. Make that as fast as we can. */
3153 specpdl_ptr->let.kind = SPECPDL_LET;
3154 specpdl_ptr->let.symbol = symbol;
3155 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3156 grow_specpdl ();
3157 if (!sym->constant)
3158 SET_SYMBOL_VAL (sym, value);
3159 else
3160 set_internal (symbol, value, Qnil, 1);
3161 break;
3162 case SYMBOL_LOCALIZED:
3163 if (SYMBOL_BLV (sym)->frame_local)
3164 error ("Frame-local vars cannot be let-bound");
3165 case SYMBOL_FORWARDED:
3167 Lisp_Object ovalue = find_symbol_value (symbol);
3168 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3169 specpdl_ptr->let.symbol = symbol;
3170 specpdl_ptr->let.old_value = ovalue;
3171 specpdl_ptr->let.where = Fcurrent_buffer ();
3173 eassert (sym->redirect != SYMBOL_LOCALIZED
3174 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3176 if (sym->redirect == SYMBOL_LOCALIZED)
3178 if (!blv_found (SYMBOL_BLV (sym)))
3179 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3181 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3183 /* If SYMBOL is a per-buffer variable which doesn't have a
3184 buffer-local value here, make the `let' change the global
3185 value by changing the value of SYMBOL in all buffers not
3186 having their own value. This is consistent with what
3187 happens with other buffer-local variables. */
3188 if (NILP (Flocal_variable_p (symbol, Qnil)))
3190 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3191 grow_specpdl ();
3192 Fset_default (symbol, value);
3193 return;
3196 else
3197 specpdl_ptr->let.kind = SPECPDL_LET;
3199 grow_specpdl ();
3200 set_internal (symbol, value, Qnil, 1);
3201 break;
3203 default: emacs_abort ();
3207 /* Push unwind-protect entries of various types. */
3209 void
3210 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3212 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3213 specpdl_ptr->unwind.func = function;
3214 specpdl_ptr->unwind.arg = arg;
3215 grow_specpdl ();
3218 void
3219 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3221 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3222 specpdl_ptr->unwind_ptr.func = function;
3223 specpdl_ptr->unwind_ptr.arg = arg;
3224 grow_specpdl ();
3227 void
3228 record_unwind_protect_int (void (*function) (int), int arg)
3230 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3231 specpdl_ptr->unwind_int.func = function;
3232 specpdl_ptr->unwind_int.arg = arg;
3233 grow_specpdl ();
3236 void
3237 record_unwind_protect_void (void (*function) (void))
3239 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3240 specpdl_ptr->unwind_void.func = function;
3241 grow_specpdl ();
3244 static void
3245 do_nothing (void)
3248 /* Push an unwind-protect entry that does nothing, so that
3249 set_unwind_protect_ptr can overwrite it later. */
3251 void
3252 record_unwind_protect_nothing (void)
3254 record_unwind_protect_void (do_nothing);
3257 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3258 It need not be at the top of the stack. */
3260 void
3261 clear_unwind_protect (ptrdiff_t count)
3263 union specbinding *p = specpdl + count;
3264 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3265 p->unwind_void.func = do_nothing;
3268 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3269 It need not be at the top of the stack. Discard the entry's
3270 previous value without invoking it. */
3272 void
3273 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3274 Lisp_Object arg)
3276 union specbinding *p = specpdl + count;
3277 p->unwind.kind = SPECPDL_UNWIND;
3278 p->unwind.func = func;
3279 p->unwind.arg = arg;
3282 void
3283 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3285 union specbinding *p = specpdl + count;
3286 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3287 p->unwind_ptr.func = func;
3288 p->unwind_ptr.arg = arg;
3291 /* Pop and execute entries from the unwind-protect stack until the
3292 depth COUNT is reached. Return VALUE. */
3294 Lisp_Object
3295 unbind_to (ptrdiff_t count, Lisp_Object value)
3297 Lisp_Object quitf = Vquit_flag;
3299 Vquit_flag = Qnil;
3301 while (specpdl_ptr != specpdl + count)
3303 /* Decrement specpdl_ptr before we do the work to unbind it, so
3304 that an error in unbinding won't try to unbind the same entry
3305 again. Take care to copy any parts of the binding needed
3306 before invoking any code that can make more bindings. */
3308 specpdl_ptr--;
3310 switch (specpdl_ptr->kind)
3312 case SPECPDL_UNWIND:
3313 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3314 break;
3315 case SPECPDL_UNWIND_PTR:
3316 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3317 break;
3318 case SPECPDL_UNWIND_INT:
3319 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3320 break;
3321 case SPECPDL_UNWIND_VOID:
3322 specpdl_ptr->unwind_void.func ();
3323 break;
3324 case SPECPDL_BACKTRACE:
3325 break;
3326 case SPECPDL_LET:
3327 { /* If variable has a trivial value (no forwarding), we can
3328 just set it. No need to check for constant symbols here,
3329 since that was already done by specbind. */
3330 Lisp_Object sym = specpdl_symbol (specpdl_ptr);
3331 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3333 SET_SYMBOL_VAL (XSYMBOL (sym),
3334 specpdl_old_value (specpdl_ptr));
3335 break;
3337 else
3338 { /* FALLTHROUGH!!
3339 NOTE: we only ever come here if make_local_foo was used for
3340 the first time on this var within this let. */
3343 case SPECPDL_LET_DEFAULT:
3344 Fset_default (specpdl_symbol (specpdl_ptr),
3345 specpdl_old_value (specpdl_ptr));
3346 break;
3347 case SPECPDL_LET_LOCAL:
3349 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3350 Lisp_Object where = specpdl_where (specpdl_ptr);
3351 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3352 eassert (BUFFERP (where));
3354 /* If this was a local binding, reset the value in the appropriate
3355 buffer, but only if that buffer's binding still exists. */
3356 if (!NILP (Flocal_variable_p (symbol, where)))
3357 set_internal (symbol, old_value, where, 1);
3359 break;
3363 if (NILP (Vquit_flag) && !NILP (quitf))
3364 Vquit_flag = quitf;
3366 return value;
3369 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3370 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3371 A special variable is one that will be bound dynamically, even in a
3372 context where binding is lexical by default. */)
3373 (Lisp_Object symbol)
3375 CHECK_SYMBOL (symbol);
3376 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3380 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3381 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3382 The debugger is entered when that frame exits, if the flag is non-nil. */)
3383 (Lisp_Object level, Lisp_Object flag)
3385 union specbinding *pdl = backtrace_top ();
3386 register EMACS_INT i;
3388 CHECK_NUMBER (level);
3390 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3391 pdl = backtrace_next (pdl);
3393 if (backtrace_p (pdl))
3394 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3396 return flag;
3399 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3400 doc: /* Print a trace of Lisp function calls currently active.
3401 Output stream used is value of `standard-output'. */)
3402 (void)
3404 union specbinding *pdl = backtrace_top ();
3405 Lisp_Object tem;
3406 Lisp_Object old_print_level = Vprint_level;
3408 if (NILP (Vprint_level))
3409 XSETFASTINT (Vprint_level, 8);
3411 while (backtrace_p (pdl))
3413 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ");
3414 if (backtrace_nargs (pdl) == UNEVALLED)
3416 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3417 Qnil);
3418 write_string ("\n");
3420 else
3422 tem = backtrace_function (pdl);
3423 Fprin1 (tem, Qnil); /* This can QUIT. */
3424 write_string ("(");
3426 ptrdiff_t i;
3427 for (i = 0; i < backtrace_nargs (pdl); i++)
3429 if (i) write_string (" ");
3430 Fprin1 (backtrace_args (pdl)[i], Qnil);
3433 write_string (")\n");
3435 pdl = backtrace_next (pdl);
3438 Vprint_level = old_print_level;
3439 return Qnil;
3442 static union specbinding *
3443 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3445 union specbinding *pdl = backtrace_top ();
3446 register EMACS_INT i;
3448 CHECK_NATNUM (nframes);
3450 if (!NILP (base))
3451 { /* Skip up to `base'. */
3452 base = Findirect_function (base, Qt);
3453 while (backtrace_p (pdl)
3454 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3455 pdl = backtrace_next (pdl);
3458 /* Find the frame requested. */
3459 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3460 pdl = backtrace_next (pdl);
3462 return pdl;
3465 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3466 doc: /* Return the function and arguments NFRAMES up from current execution point.
3467 If that frame has not evaluated the arguments yet (or is a special form),
3468 the value is (nil FUNCTION ARG-FORMS...).
3469 If that frame has evaluated its arguments and called its function already,
3470 the value is (t FUNCTION ARG-VALUES...).
3471 A &rest arg is represented as the tail of the list ARG-VALUES.
3472 FUNCTION is whatever was supplied as car of evaluated list,
3473 or a lambda expression for macro calls.
3474 If NFRAMES is more than the number of frames, the value is nil.
3475 If BASE is non-nil, it should be a function and NFRAMES counts from its
3476 nearest activation frame. */)
3477 (Lisp_Object nframes, Lisp_Object base)
3479 union specbinding *pdl = get_backtrace_frame (nframes, base);
3481 if (!backtrace_p (pdl))
3482 return Qnil;
3483 if (backtrace_nargs (pdl) == UNEVALLED)
3484 return Fcons (Qnil,
3485 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3486 else
3488 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3490 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3494 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3495 the specpdl stack, and then rewind them. We store the pre-unwind values
3496 directly in the pre-existing specpdl elements (i.e. we swap the current
3497 value and the old value stored in the specpdl), kind of like the inplace
3498 pointer-reversal trick. As it turns out, the rewind does the same as the
3499 unwind, except it starts from the other end of the specpdl stack, so we use
3500 the same function for both unwind and rewind. */
3501 static void
3502 backtrace_eval_unrewind (int distance)
3504 union specbinding *tmp = specpdl_ptr;
3505 int step = -1;
3506 if (distance < 0)
3507 { /* It's a rewind rather than unwind. */
3508 tmp += distance - 1;
3509 step = 1;
3510 distance = -distance;
3513 for (; distance > 0; distance--)
3515 tmp += step;
3516 switch (tmp->kind)
3518 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3519 unwind_protect, but the problem is that we don't know how to
3520 rewind them afterwards. */
3521 case SPECPDL_UNWIND:
3523 Lisp_Object oldarg = tmp->unwind.arg;
3524 if (tmp->unwind.func == set_buffer_if_live)
3525 tmp->unwind.arg = Fcurrent_buffer ();
3526 else if (tmp->unwind.func == save_excursion_restore)
3527 tmp->unwind.arg = save_excursion_save ();
3528 else
3529 break;
3530 tmp->unwind.func (oldarg);
3531 break;
3534 case SPECPDL_UNWIND_PTR:
3535 case SPECPDL_UNWIND_INT:
3536 case SPECPDL_UNWIND_VOID:
3537 case SPECPDL_BACKTRACE:
3538 break;
3539 case SPECPDL_LET:
3540 { /* If variable has a trivial value (no forwarding), we can
3541 just set it. No need to check for constant symbols here,
3542 since that was already done by specbind. */
3543 Lisp_Object sym = specpdl_symbol (tmp);
3544 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3546 Lisp_Object old_value = specpdl_old_value (tmp);
3547 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3548 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3549 break;
3551 else
3552 { /* FALLTHROUGH!!
3553 NOTE: we only ever come here if make_local_foo was used for
3554 the first time on this var within this let. */
3557 case SPECPDL_LET_DEFAULT:
3559 Lisp_Object sym = specpdl_symbol (tmp);
3560 Lisp_Object old_value = specpdl_old_value (tmp);
3561 set_specpdl_old_value (tmp, Fdefault_value (sym));
3562 Fset_default (sym, old_value);
3564 break;
3565 case SPECPDL_LET_LOCAL:
3567 Lisp_Object symbol = specpdl_symbol (tmp);
3568 Lisp_Object where = specpdl_where (tmp);
3569 Lisp_Object old_value = specpdl_old_value (tmp);
3570 eassert (BUFFERP (where));
3572 /* If this was a local binding, reset the value in the appropriate
3573 buffer, but only if that buffer's binding still exists. */
3574 if (!NILP (Flocal_variable_p (symbol, where)))
3576 set_specpdl_old_value
3577 (tmp, Fbuffer_local_value (symbol, where));
3578 set_internal (symbol, old_value, where, 1);
3581 break;
3586 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3587 doc: /* Evaluate EXP in the context of some activation frame.
3588 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3589 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3591 union specbinding *pdl = get_backtrace_frame (nframes, base);
3592 ptrdiff_t count = SPECPDL_INDEX ();
3593 ptrdiff_t distance = specpdl_ptr - pdl;
3594 eassert (distance >= 0);
3596 if (!backtrace_p (pdl))
3597 error ("Activation frame not found!");
3599 backtrace_eval_unrewind (distance);
3600 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3602 /* Use eval_sub rather than Feval since the main motivation behind
3603 backtrace-eval is to be able to get/set the value of lexical variables
3604 from the debugger. */
3605 return unbind_to (count, eval_sub (exp));
3608 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3609 doc: /* Return names and values of local variables of a stack frame.
3610 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3611 (Lisp_Object nframes, Lisp_Object base)
3613 union specbinding *frame = get_backtrace_frame (nframes, base);
3614 union specbinding *prevframe
3615 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3616 ptrdiff_t distance = specpdl_ptr - frame;
3617 Lisp_Object result = Qnil;
3618 eassert (distance >= 0);
3620 if (!backtrace_p (prevframe))
3621 error ("Activation frame not found!");
3622 if (!backtrace_p (frame))
3623 error ("Activation frame not found!");
3625 /* The specpdl entries normally contain the symbol being bound along with its
3626 `old_value', so it can be restored. The new value to which it is bound is
3627 available in one of two places: either in the current value of the
3628 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3629 next specpdl entry for it.
3630 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3631 and "new value", so we abuse it here, to fetch the new value.
3632 It's ugly (we'd rather not modify global data) and a bit inefficient,
3633 but it does the job for now. */
3634 backtrace_eval_unrewind (distance);
3636 /* Grab values. */
3638 union specbinding *tmp = prevframe;
3639 for (; tmp > frame; tmp--)
3641 switch (tmp->kind)
3643 case SPECPDL_LET:
3644 case SPECPDL_LET_DEFAULT:
3645 case SPECPDL_LET_LOCAL:
3647 Lisp_Object sym = specpdl_symbol (tmp);
3648 Lisp_Object val = specpdl_old_value (tmp);
3649 if (EQ (sym, Qinternal_interpreter_environment))
3651 Lisp_Object env = val;
3652 for (; CONSP (env); env = XCDR (env))
3654 Lisp_Object binding = XCAR (env);
3655 if (CONSP (binding))
3656 result = Fcons (Fcons (XCAR (binding),
3657 XCDR (binding)),
3658 result);
3661 else
3662 result = Fcons (Fcons (sym, val), result);
3664 break;
3666 case SPECPDL_UNWIND:
3667 case SPECPDL_UNWIND_PTR:
3668 case SPECPDL_UNWIND_INT:
3669 case SPECPDL_UNWIND_VOID:
3670 case SPECPDL_BACKTRACE:
3671 break;
3673 default:
3674 emacs_abort ();
3679 /* Restore values from specpdl to original place. */
3680 backtrace_eval_unrewind (-distance);
3682 return result;
3686 void
3687 mark_specpdl (void)
3689 union specbinding *pdl;
3690 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3692 switch (pdl->kind)
3694 case SPECPDL_UNWIND:
3695 mark_object (specpdl_arg (pdl));
3696 break;
3698 case SPECPDL_BACKTRACE:
3700 ptrdiff_t nargs = backtrace_nargs (pdl);
3701 mark_object (backtrace_function (pdl));
3702 if (nargs == UNEVALLED)
3703 nargs = 1;
3704 while (nargs--)
3705 mark_object (backtrace_args (pdl)[nargs]);
3707 break;
3709 case SPECPDL_LET_DEFAULT:
3710 case SPECPDL_LET_LOCAL:
3711 mark_object (specpdl_where (pdl));
3712 /* Fall through. */
3713 case SPECPDL_LET:
3714 mark_object (specpdl_symbol (pdl));
3715 mark_object (specpdl_old_value (pdl));
3716 break;
3718 case SPECPDL_UNWIND_PTR:
3719 case SPECPDL_UNWIND_INT:
3720 case SPECPDL_UNWIND_VOID:
3721 break;
3723 default:
3724 emacs_abort ();
3729 void
3730 get_backtrace (Lisp_Object array)
3732 union specbinding *pdl = backtrace_next (backtrace_top ());
3733 ptrdiff_t i = 0, asize = ASIZE (array);
3735 /* Copy the backtrace contents into working memory. */
3736 for (; i < asize; i++)
3738 if (backtrace_p (pdl))
3740 ASET (array, i, backtrace_function (pdl));
3741 pdl = backtrace_next (pdl);
3743 else
3744 ASET (array, i, Qnil);
3748 Lisp_Object backtrace_top_function (void)
3750 union specbinding *pdl = backtrace_top ();
3751 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3754 void
3755 syms_of_eval (void)
3757 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3758 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3759 If Lisp code tries to increase the total number past this amount,
3760 an error is signaled.
3761 You can safely use a value considerably larger than the default value,
3762 if that proves inconveniently small. However, if you increase it too far,
3763 Emacs could run out of memory trying to make the stack bigger.
3764 Note that this limit may be silently increased by the debugger
3765 if `debug-on-error' or `debug-on-quit' is set. */);
3767 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3768 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3770 This limit serves to catch infinite recursions for you before they cause
3771 actual stack overflow in C, which would be fatal for Emacs.
3772 You can safely make it considerably larger than its default value,
3773 if that proves inconveniently small. However, if you increase it too far,
3774 Emacs could overflow the real C stack, and crash. */);
3776 DEFVAR_LISP ("quit-flag", Vquit_flag,
3777 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3778 If the value is t, that means do an ordinary quit.
3779 If the value equals `throw-on-input', that means quit by throwing
3780 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3781 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3782 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3783 Vquit_flag = Qnil;
3785 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3786 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3787 Note that `quit-flag' will still be set by typing C-g,
3788 so a quit will be signaled as soon as `inhibit-quit' is nil.
3789 To prevent this happening, set `quit-flag' to nil
3790 before making `inhibit-quit' nil. */);
3791 Vinhibit_quit = Qnil;
3793 DEFSYM (Qsetq, "setq");
3794 DEFSYM (Qinhibit_quit, "inhibit-quit");
3795 DEFSYM (Qautoload, "autoload");
3796 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3797 DEFSYM (Qmacro, "macro");
3799 /* Note that the process handling also uses Qexit, but we don't want
3800 to staticpro it twice, so we just do it here. */
3801 DEFSYM (Qexit, "exit");
3803 DEFSYM (Qinteractive, "interactive");
3804 DEFSYM (Qcommandp, "commandp");
3805 DEFSYM (Qand_rest, "&rest");
3806 DEFSYM (Qand_optional, "&optional");
3807 DEFSYM (Qclosure, "closure");
3808 DEFSYM (QCdocumentation, ":documentation");
3809 DEFSYM (Qdebug, "debug");
3811 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3812 doc: /* Non-nil means never enter the debugger.
3813 Normally set while the debugger is already active, to avoid recursive
3814 invocations. */);
3815 Vinhibit_debugger = Qnil;
3817 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3818 doc: /* Non-nil means enter debugger if an error is signaled.
3819 Does not apply to errors handled by `condition-case' or those
3820 matched by `debug-ignored-errors'.
3821 If the value is a list, an error only means to enter the debugger
3822 if one of its condition symbols appears in the list.
3823 When you evaluate an expression interactively, this variable
3824 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3825 The command `toggle-debug-on-error' toggles this.
3826 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3827 Vdebug_on_error = Qnil;
3829 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3830 doc: /* List of errors for which the debugger should not be called.
3831 Each element may be a condition-name or a regexp that matches error messages.
3832 If any element applies to a given error, that error skips the debugger
3833 and just returns to top level.
3834 This overrides the variable `debug-on-error'.
3835 It does not apply to errors handled by `condition-case'. */);
3836 Vdebug_ignored_errors = Qnil;
3838 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3839 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3840 Does not apply if quit is handled by a `condition-case'. */);
3841 debug_on_quit = 0;
3843 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3844 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3846 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3847 doc: /* Non-nil means debugger may continue execution.
3848 This is nil when the debugger is called under circumstances where it
3849 might not be safe to continue. */);
3850 debugger_may_continue = 1;
3852 DEFVAR_LISP ("debugger", Vdebugger,
3853 doc: /* Function to call to invoke debugger.
3854 If due to frame exit, args are `exit' and the value being returned;
3855 this function's value will be returned instead of that.
3856 If due to error, args are `error' and a list of the args to `signal'.
3857 If due to `apply' or `funcall' entry, one arg, `lambda'.
3858 If due to `eval' entry, one arg, t. */);
3859 Vdebugger = Qnil;
3861 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3862 doc: /* If non-nil, this is a function for `signal' to call.
3863 It receives the same arguments that `signal' was given.
3864 The Edebug package uses this to regain control. */);
3865 Vsignal_hook_function = Qnil;
3867 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3868 doc: /* Non-nil means call the debugger regardless of condition handlers.
3869 Note that `debug-on-error', `debug-on-quit' and friends
3870 still determine whether to handle the particular condition. */);
3871 Vdebug_on_signal = Qnil;
3873 /* When lexical binding is being used,
3874 Vinternal_interpreter_environment is non-nil, and contains an alist
3875 of lexically-bound variable, or (t), indicating an empty
3876 environment. The lisp name of this variable would be
3877 `internal-interpreter-environment' if it weren't hidden.
3878 Every element of this list can be either a cons (VAR . VAL)
3879 specifying a lexical binding, or a single symbol VAR indicating
3880 that this variable should use dynamic scoping. */
3881 DEFSYM (Qinternal_interpreter_environment,
3882 "internal-interpreter-environment");
3883 DEFVAR_LISP ("internal-interpreter-environment",
3884 Vinternal_interpreter_environment,
3885 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3886 When lexical binding is not being used, this variable is nil.
3887 A value of `(t)' indicates an empty environment, otherwise it is an
3888 alist of active lexical bindings. */);
3889 Vinternal_interpreter_environment = Qnil;
3890 /* Don't export this variable to Elisp, so no one can mess with it
3891 (Just imagine if someone makes it buffer-local). */
3892 Funintern (Qinternal_interpreter_environment, Qnil);
3894 Vrun_hooks = intern_c_string ("run-hooks");
3895 staticpro (&Vrun_hooks);
3897 staticpro (&Vautoload_queue);
3898 Vautoload_queue = Qnil;
3899 staticpro (&Vsignaling_function);
3900 Vsignaling_function = Qnil;
3902 inhibit_lisp_code = Qnil;
3904 defsubr (&Sor);
3905 defsubr (&Sand);
3906 defsubr (&Sif);
3907 defsubr (&Scond);
3908 defsubr (&Sprogn);
3909 defsubr (&Sprog1);
3910 defsubr (&Sprog2);
3911 defsubr (&Ssetq);
3912 defsubr (&Squote);
3913 defsubr (&Sfunction);
3914 defsubr (&Sdefault_toplevel_value);
3915 defsubr (&Sset_default_toplevel_value);
3916 defsubr (&Sdefvar);
3917 defsubr (&Sdefvaralias);
3918 defsubr (&Sdefconst);
3919 defsubr (&Smake_var_non_special);
3920 defsubr (&Slet);
3921 defsubr (&SletX);
3922 defsubr (&Swhile);
3923 defsubr (&Smacroexpand);
3924 defsubr (&Scatch);
3925 defsubr (&Sthrow);
3926 defsubr (&Sunwind_protect);
3927 defsubr (&Scondition_case);
3928 defsubr (&Ssignal);
3929 defsubr (&Scommandp);
3930 defsubr (&Sautoload);
3931 defsubr (&Sautoload_do_load);
3932 defsubr (&Seval);
3933 defsubr (&Sapply);
3934 defsubr (&Sfuncall);
3935 defsubr (&Sfunc_arity);
3936 defsubr (&Srun_hooks);
3937 defsubr (&Srun_hook_with_args);
3938 defsubr (&Srun_hook_with_args_until_success);
3939 defsubr (&Srun_hook_with_args_until_failure);
3940 defsubr (&Srun_hook_wrapped);
3941 defsubr (&Sfetch_bytecode);
3942 defsubr (&Sbacktrace_debug);
3943 defsubr (&Sbacktrace);
3944 defsubr (&Sbacktrace_frame);
3945 defsubr (&Sbacktrace_eval);
3946 defsubr (&Sbacktrace__locals);
3947 defsubr (&Sspecial_variable_p);
3948 defsubr (&Sfunctionp);