; Update ChangeLog.2 and AUTHORS files
[emacs.git] / src / eval.c
blobfec46831dd7d0c0e9b6d80090f47e8d7239f40fc
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2017 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);
94 static Lisp_Object
95 specpdl_symbol (union specbinding *pdl)
97 eassert (pdl->kind >= SPECPDL_LET);
98 return pdl->let.symbol;
101 static Lisp_Object
102 specpdl_old_value (union specbinding *pdl)
104 eassert (pdl->kind >= SPECPDL_LET);
105 return pdl->let.old_value;
108 static void
109 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
111 eassert (pdl->kind >= SPECPDL_LET);
112 pdl->let.old_value = val;
115 static Lisp_Object
116 specpdl_where (union specbinding *pdl)
118 eassert (pdl->kind > SPECPDL_LET);
119 return pdl->let.where;
122 static Lisp_Object
123 specpdl_arg (union specbinding *pdl)
125 eassert (pdl->kind == SPECPDL_UNWIND);
126 return pdl->unwind.arg;
129 Lisp_Object
130 backtrace_function (union specbinding *pdl)
132 eassert (pdl->kind == SPECPDL_BACKTRACE);
133 return pdl->bt.function;
136 static ptrdiff_t
137 backtrace_nargs (union specbinding *pdl)
139 eassert (pdl->kind == SPECPDL_BACKTRACE);
140 return pdl->bt.nargs;
143 Lisp_Object *
144 backtrace_args (union specbinding *pdl)
146 eassert (pdl->kind == SPECPDL_BACKTRACE);
147 return pdl->bt.args;
150 static bool
151 backtrace_debug_on_exit (union specbinding *pdl)
153 eassert (pdl->kind == SPECPDL_BACKTRACE);
154 return pdl->bt.debug_on_exit;
157 /* Functions to modify slots of backtrace records. */
159 static void
160 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
162 eassert (pdl->kind == SPECPDL_BACKTRACE);
163 pdl->bt.args = args;
164 pdl->bt.nargs = nargs;
167 static void
168 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
170 eassert (pdl->kind == SPECPDL_BACKTRACE);
171 pdl->bt.debug_on_exit = doe;
174 /* Helper functions to scan the backtrace. */
176 bool
177 backtrace_p (union specbinding *pdl)
178 { return pdl >= specpdl; }
180 union specbinding *
181 backtrace_top (void)
183 union specbinding *pdl = specpdl_ptr - 1;
184 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
185 pdl--;
186 return pdl;
189 union specbinding *
190 backtrace_next (union specbinding *pdl)
192 pdl--;
193 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
194 pdl--;
195 return pdl;
198 /* Return a pointer to somewhere near the top of the C stack. */
199 void *
200 near_C_stack_top (void)
202 return backtrace_args (backtrace_top ());
205 void
206 init_eval_once (void)
208 enum { size = 50 };
209 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
210 specpdl_size = size;
211 specpdl = specpdl_ptr = pdlvec + 1;
212 /* Don't forget to update docs (lispref node "Local Variables"). */
213 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
214 max_lisp_eval_depth = 800;
216 Vrun_hooks = Qnil;
219 static struct handler handlerlist_sentinel;
221 void
222 init_eval (void)
224 byte_stack_list = 0;
225 specpdl_ptr = specpdl;
226 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
227 This is important since handlerlist->nextfree holds the freelist
228 which would otherwise leak every time we unwind back to top-level. */
229 handlerlist = handlerlist_sentinel.nextfree = &handlerlist_sentinel;
230 struct handler *c = push_handler (Qunbound, CATCHER);
231 eassert (c == &handlerlist_sentinel);
232 handlerlist_sentinel.nextfree = NULL;
233 handlerlist_sentinel.next = NULL;
235 Vquit_flag = Qnil;
236 debug_on_next_call = 0;
237 lisp_eval_depth = 0;
238 /* This is less than the initial value of num_nonmacro_input_events. */
239 when_entered_debugger = -1;
242 /* Unwind-protect function used by call_debugger. */
244 static void
245 restore_stack_limits (Lisp_Object data)
247 max_specpdl_size = XINT (XCAR (data));
248 max_lisp_eval_depth = XINT (XCDR (data));
251 static void grow_specpdl (void);
253 /* Call the Lisp debugger, giving it argument ARG. */
255 Lisp_Object
256 call_debugger (Lisp_Object arg)
258 bool debug_while_redisplaying;
259 ptrdiff_t count = SPECPDL_INDEX ();
260 Lisp_Object val;
261 EMACS_INT old_depth = max_lisp_eval_depth;
262 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
263 EMACS_INT old_max = max (max_specpdl_size, count);
265 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
266 max_lisp_eval_depth = lisp_eval_depth + 40;
268 /* While debugging Bug#16603, previous value of 100 was found
269 too small to avoid specpdl overflow in the debugger itself. */
270 if (max_specpdl_size - 200 < count)
271 max_specpdl_size = count + 200;
273 if (old_max == count)
275 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
276 specpdl_ptr--;
277 grow_specpdl ();
280 /* Restore limits after leaving the debugger. */
281 record_unwind_protect (restore_stack_limits,
282 Fcons (make_number (old_max),
283 make_number (old_depth)));
285 #ifdef HAVE_WINDOW_SYSTEM
286 if (display_hourglass_p)
287 cancel_hourglass ();
288 #endif
290 debug_on_next_call = 0;
291 when_entered_debugger = num_nonmacro_input_events;
293 /* Resetting redisplaying_p to 0 makes sure that debug output is
294 displayed if the debugger is invoked during redisplay. */
295 debug_while_redisplaying = redisplaying_p;
296 redisplaying_p = 0;
297 specbind (intern ("debugger-may-continue"),
298 debug_while_redisplaying ? Qnil : Qt);
299 specbind (Qinhibit_redisplay, Qnil);
300 specbind (Qinhibit_debugger, Qt);
302 /* If we are debugging an error while `inhibit-changing-match-data'
303 is bound to non-nil (e.g., within a call to `string-match-p'),
304 then make sure debugger code can still use match data. */
305 specbind (Qinhibit_changing_match_data, Qnil);
307 #if 0 /* Binding this prevents execution of Lisp code during
308 redisplay, which necessarily leads to display problems. */
309 specbind (Qinhibit_eval_during_redisplay, Qt);
310 #endif
312 val = apply1 (Vdebugger, arg);
314 /* Interrupting redisplay and resuming it later is not safe under
315 all circumstances. So, when the debugger returns, abort the
316 interrupted redisplay by going back to the top-level. */
317 if (debug_while_redisplaying)
318 Ftop_level ();
320 return unbind_to (count, val);
323 static void
324 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
326 debug_on_next_call = 0;
327 set_backtrace_debug_on_exit (specpdl + count, true);
328 call_debugger (list1 (code));
331 /* NOTE!!! Every function that can call EVAL must protect its args
332 and temporaries from garbage collection while it needs them.
333 The definition of `For' shows what you have to do. */
335 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
336 doc: /* Eval args until one of them yields non-nil, then return that value.
337 The remaining args are not evalled at all.
338 If all args return nil, return nil.
339 usage: (or CONDITIONS...) */)
340 (Lisp_Object args)
342 Lisp_Object val = Qnil;
344 while (CONSP (args))
346 val = eval_sub (XCAR (args));
347 if (!NILP (val))
348 break;
349 args = XCDR (args);
352 return val;
355 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
356 doc: /* Eval args until one of them yields nil, then return nil.
357 The remaining args are not evalled at all.
358 If no arg yields nil, return the last arg's value.
359 usage: (and CONDITIONS...) */)
360 (Lisp_Object args)
362 Lisp_Object val = Qt;
364 while (CONSP (args))
366 val = eval_sub (XCAR (args));
367 if (NILP (val))
368 break;
369 args = XCDR (args);
372 return val;
375 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
376 doc: /* If COND yields non-nil, do THEN, else do ELSE...
377 Returns the value of THEN or the value of the last of the ELSE's.
378 THEN must be one expression, but ELSE... can be zero or more expressions.
379 If COND yields nil, and there are no ELSE's, the value is nil.
380 usage: (if COND THEN ELSE...) */)
381 (Lisp_Object args)
383 Lisp_Object cond;
385 cond = eval_sub (XCAR (args));
387 if (!NILP (cond))
388 return eval_sub (Fcar (XCDR (args)));
389 return Fprogn (XCDR (XCDR (args)));
392 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
393 doc: /* Try each clause until one succeeds.
394 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
395 and, if the value is non-nil, this clause succeeds:
396 then the expressions in BODY are evaluated and the last one's
397 value is the value of the cond-form.
398 If a clause has one element, as in (CONDITION), then the cond-form
399 returns CONDITION's value, if that is non-nil.
400 If no clause succeeds, cond returns nil.
401 usage: (cond CLAUSES...) */)
402 (Lisp_Object args)
404 Lisp_Object val = args;
406 while (CONSP (args))
408 Lisp_Object clause = XCAR (args);
409 val = eval_sub (Fcar (clause));
410 if (!NILP (val))
412 if (!NILP (XCDR (clause)))
413 val = Fprogn (XCDR (clause));
414 break;
416 args = XCDR (args);
419 return val;
422 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
423 doc: /* Eval BODY forms sequentially and return value of last one.
424 usage: (progn BODY...) */)
425 (Lisp_Object body)
427 Lisp_Object val = Qnil;
429 while (CONSP (body))
431 val = eval_sub (XCAR (body));
432 body = XCDR (body);
435 return val;
438 /* Evaluate BODY sequentially, discarding its value. Suitable for
439 record_unwind_protect. */
441 void
442 unwind_body (Lisp_Object body)
444 Fprogn (body);
447 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
448 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
449 The value of FIRST is saved during the evaluation of the remaining args,
450 whose values are discarded.
451 usage: (prog1 FIRST BODY...) */)
452 (Lisp_Object args)
454 Lisp_Object val;
455 Lisp_Object args_left;
457 args_left = args;
458 val = args;
460 val = eval_sub (XCAR (args_left));
461 while (CONSP (args_left = XCDR (args_left)))
462 eval_sub (XCAR (args_left));
464 return val;
467 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
468 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
469 The value of FORM2 is saved during the evaluation of the
470 remaining args, whose values are discarded.
471 usage: (prog2 FORM1 FORM2 BODY...) */)
472 (Lisp_Object args)
474 eval_sub (XCAR (args));
475 return Fprog1 (XCDR (args));
478 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
479 doc: /* Set each SYM to the value of its VAL.
480 The symbols SYM are variables; they are literal (not evaluated).
481 The values VAL are expressions; they are evaluated.
482 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
483 The second VAL is not computed until after the first SYM is set, and so on;
484 each VAL can use the new value of variables set earlier in the `setq'.
485 The return value of the `setq' form is the value of the last VAL.
486 usage: (setq [SYM VAL]...) */)
487 (Lisp_Object args)
489 Lisp_Object val, sym, lex_binding;
491 val = args;
492 if (CONSP (args))
494 Lisp_Object args_left = args;
495 Lisp_Object numargs = Flength (args);
497 if (XINT (numargs) & 1)
498 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
502 val = eval_sub (Fcar (XCDR (args_left)));
503 sym = XCAR (args_left);
505 /* Like for eval_sub, we do not check declared_special here since
506 it's been done when let-binding. */
507 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
508 && SYMBOLP (sym)
509 && !NILP (lex_binding
510 = Fassq (sym, Vinternal_interpreter_environment)))
511 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
512 else
513 Fset (sym, val); /* SYM is dynamically bound. */
515 args_left = Fcdr (XCDR (args_left));
517 while (CONSP (args_left));
520 return val;
523 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
524 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
525 Warning: `quote' does not construct its return value, but just returns
526 the value that was pre-constructed by the Lisp reader (see info node
527 `(elisp)Printed Representation').
528 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
529 does not cons. Quoting should be reserved for constants that will
530 never be modified by side-effects, unless you like self-modifying code.
531 See the common pitfall in info node `(elisp)Rearrangement' for an example
532 of unexpected results when a quoted object is modified.
533 usage: (quote ARG) */)
534 (Lisp_Object args)
536 if (CONSP (XCDR (args)))
537 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
538 return XCAR (args);
541 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
542 doc: /* Like `quote', but preferred for objects which are functions.
543 In byte compilation, `function' causes its argument to be compiled.
544 `quote' cannot do that.
545 usage: (function ARG) */)
546 (Lisp_Object args)
548 Lisp_Object quoted = XCAR (args);
550 if (CONSP (XCDR (args)))
551 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
553 if (!NILP (Vinternal_interpreter_environment)
554 && CONSP (quoted)
555 && EQ (XCAR (quoted), Qlambda))
556 { /* This is a lambda expression within a lexical environment;
557 return an interpreted closure instead of a simple lambda. */
558 Lisp_Object cdr = XCDR (quoted);
559 Lisp_Object tmp = cdr;
560 if (CONSP (tmp)
561 && (tmp = XCDR (tmp), CONSP (tmp))
562 && (tmp = XCAR (tmp), CONSP (tmp))
563 && (EQ (QCdocumentation, XCAR (tmp))))
564 { /* Handle the special (:documentation <form>) to build the docstring
565 dynamically. */
566 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
567 CHECK_STRING (docstring);
568 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
570 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
571 cdr));
573 else
574 /* Simply quote the argument. */
575 return quoted;
579 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
580 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
581 Aliased variables always have the same value; setting one sets the other.
582 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
583 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
584 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
585 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
586 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
587 The return value is BASE-VARIABLE. */)
588 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
590 struct Lisp_Symbol *sym;
592 CHECK_SYMBOL (new_alias);
593 CHECK_SYMBOL (base_variable);
595 sym = XSYMBOL (new_alias);
597 if (sym->constant)
598 /* Not sure why, but why not? */
599 error ("Cannot make a constant an alias");
601 switch (sym->redirect)
603 case SYMBOL_FORWARDED:
604 error ("Cannot make an internal variable an alias");
605 case SYMBOL_LOCALIZED:
606 error ("Don't know how to make a localized variable an alias");
607 case SYMBOL_PLAINVAL:
608 case SYMBOL_VARALIAS:
609 break;
610 default:
611 emacs_abort ();
614 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
615 If n_a is bound, but b_v is not, set the value of b_v to n_a,
616 so that old-code that affects n_a before the aliasing is setup
617 still works. */
618 if (NILP (Fboundp (base_variable)))
619 set_internal (base_variable, find_symbol_value (new_alias), Qnil, 1);
622 union specbinding *p;
624 for (p = specpdl_ptr; p > specpdl; )
625 if ((--p)->kind >= SPECPDL_LET
626 && (EQ (new_alias, specpdl_symbol (p))))
627 error ("Don't know how to make a let-bound variable an alias");
630 sym->declared_special = 1;
631 XSYMBOL (base_variable)->declared_special = 1;
632 sym->redirect = SYMBOL_VARALIAS;
633 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
634 sym->constant = SYMBOL_CONSTANT_P (base_variable);
635 LOADHIST_ATTACH (new_alias);
636 /* Even if docstring is nil: remove old docstring. */
637 Fput (new_alias, Qvariable_documentation, docstring);
639 return base_variable;
642 static union specbinding *
643 default_toplevel_binding (Lisp_Object symbol)
645 union specbinding *binding = NULL;
646 union specbinding *pdl = specpdl_ptr;
647 while (pdl > specpdl)
649 switch ((--pdl)->kind)
651 case SPECPDL_LET_DEFAULT:
652 case SPECPDL_LET:
653 if (EQ (specpdl_symbol (pdl), symbol))
654 binding = pdl;
655 break;
657 case SPECPDL_UNWIND:
658 case SPECPDL_UNWIND_PTR:
659 case SPECPDL_UNWIND_INT:
660 case SPECPDL_UNWIND_VOID:
661 case SPECPDL_BACKTRACE:
662 case SPECPDL_LET_LOCAL:
663 break;
665 default:
666 emacs_abort ();
669 return binding;
672 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
673 doc: /* Return SYMBOL's toplevel default value.
674 "Toplevel" means outside of any let binding. */)
675 (Lisp_Object symbol)
677 union specbinding *binding = default_toplevel_binding (symbol);
678 Lisp_Object value
679 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
680 if (!EQ (value, Qunbound))
681 return value;
682 xsignal1 (Qvoid_variable, symbol);
685 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
686 Sset_default_toplevel_value, 2, 2, 0,
687 doc: /* Set SYMBOL's toplevel default value to VALUE.
688 "Toplevel" means outside of any let binding. */)
689 (Lisp_Object symbol, Lisp_Object value)
691 union specbinding *binding = default_toplevel_binding (symbol);
692 if (binding)
693 set_specpdl_old_value (binding, value);
694 else
695 Fset_default (symbol, value);
696 return Qnil;
699 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
700 doc: /* Define SYMBOL as a variable, and return SYMBOL.
701 You are not required to define a variable in order to use it, but
702 defining it lets you supply an initial value and documentation, which
703 can be referred to by the Emacs help facilities and other programming
704 tools. The `defvar' form also declares the variable as \"special\",
705 so that it is always dynamically bound even if `lexical-binding' is t.
707 If SYMBOL's value is void and the optional argument INITVALUE is
708 provided, INITVALUE is evaluated and the result used to set SYMBOL's
709 value. If SYMBOL is buffer-local, its default value is what is set;
710 buffer-local values are not affected. If INITVALUE is missing,
711 SYMBOL's value is not set.
713 If SYMBOL has a local binding, then this form affects the local
714 binding. This is usually not what you want. Thus, if you need to
715 load a file defining variables, with this form or with `defconst' or
716 `defcustom', you should always load that file _outside_ any bindings
717 for these variables. (`defconst' and `defcustom' behave similarly in
718 this respect.)
720 The optional argument DOCSTRING is a documentation string for the
721 variable.
723 To define a user option, use `defcustom' instead of `defvar'.
724 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
725 (Lisp_Object args)
727 Lisp_Object sym, tem, tail;
729 sym = XCAR (args);
730 tail = XCDR (args);
732 if (CONSP (tail))
734 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
735 error ("Too many arguments");
737 tem = Fdefault_boundp (sym);
739 /* Do it before evaluating the initial value, for self-references. */
740 XSYMBOL (sym)->declared_special = 1;
742 if (NILP (tem))
743 Fset_default (sym, eval_sub (XCAR (tail)));
744 else
745 { /* Check if there is really a global binding rather than just a let
746 binding that shadows the global unboundness of the var. */
747 union specbinding *binding = default_toplevel_binding (sym);
748 if (binding && EQ (specpdl_old_value (binding), Qunbound))
750 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
753 tail = XCDR (tail);
754 tem = Fcar (tail);
755 if (!NILP (tem))
757 if (!NILP (Vpurify_flag))
758 tem = Fpurecopy (tem);
759 Fput (sym, Qvariable_documentation, tem);
761 LOADHIST_ATTACH (sym);
763 else if (!NILP (Vinternal_interpreter_environment)
764 && !XSYMBOL (sym)->declared_special)
765 /* A simple (defvar foo) with lexical scoping does "nothing" except
766 declare that var to be dynamically scoped *locally* (i.e. within
767 the current file or let-block). */
768 Vinternal_interpreter_environment
769 = Fcons (sym, Vinternal_interpreter_environment);
770 else
772 /* Simple (defvar <var>) should not count as a definition at all.
773 It could get in the way of other definitions, and unloading this
774 package could try to make the variable unbound. */
777 return sym;
780 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
781 doc: /* Define SYMBOL as a constant variable.
782 This declares that neither programs nor users should ever change the
783 value. This constancy is not actually enforced by Emacs Lisp, but
784 SYMBOL is marked as a special variable so that it is never lexically
785 bound.
787 The `defconst' form always sets the value of SYMBOL to the result of
788 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
789 what is set; buffer-local values are not affected. If SYMBOL has a
790 local binding, then this form sets the local binding's value.
791 However, you should normally not make local bindings for variables
792 defined with this form.
794 The optional DOCSTRING specifies the variable's documentation string.
795 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
796 (Lisp_Object args)
798 Lisp_Object sym, tem;
800 sym = XCAR (args);
801 if (CONSP (Fcdr (XCDR (XCDR (args)))))
802 error ("Too many arguments");
804 tem = eval_sub (Fcar (XCDR (args)));
805 if (!NILP (Vpurify_flag))
806 tem = Fpurecopy (tem);
807 Fset_default (sym, tem);
808 XSYMBOL (sym)->declared_special = 1;
809 tem = Fcar (XCDR (XCDR (args)));
810 if (!NILP (tem))
812 if (!NILP (Vpurify_flag))
813 tem = Fpurecopy (tem);
814 Fput (sym, Qvariable_documentation, tem);
816 Fput (sym, Qrisky_local_variable, Qt);
817 LOADHIST_ATTACH (sym);
818 return sym;
821 /* Make SYMBOL lexically scoped. */
822 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
823 Smake_var_non_special, 1, 1, 0,
824 doc: /* Internal function. */)
825 (Lisp_Object symbol)
827 CHECK_SYMBOL (symbol);
828 XSYMBOL (symbol)->declared_special = 0;
829 return Qnil;
833 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
834 doc: /* Bind variables according to VARLIST then eval BODY.
835 The value of the last form in BODY is returned.
836 Each element of VARLIST is a symbol (which is bound to nil)
837 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
838 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
839 usage: (let* VARLIST BODY...) */)
840 (Lisp_Object args)
842 Lisp_Object varlist, var, val, elt, lexenv;
843 ptrdiff_t count = SPECPDL_INDEX ();
845 lexenv = Vinternal_interpreter_environment;
847 varlist = XCAR (args);
848 while (CONSP (varlist))
850 QUIT;
852 elt = XCAR (varlist);
853 if (SYMBOLP (elt))
855 var = elt;
856 val = Qnil;
858 else if (! NILP (Fcdr (Fcdr (elt))))
859 signal_error ("`let' bindings can have only one value-form", elt);
860 else
862 var = Fcar (elt);
863 val = eval_sub (Fcar (Fcdr (elt)));
866 if (!NILP (lexenv) && SYMBOLP (var)
867 && !XSYMBOL (var)->declared_special
868 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
869 /* Lexically bind VAR by adding it to the interpreter's binding
870 alist. */
872 Lisp_Object newenv
873 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
874 if (EQ (Vinternal_interpreter_environment, lexenv))
875 /* Save the old lexical environment on the specpdl stack,
876 but only for the first lexical binding, since we'll never
877 need to revert to one of the intermediate ones. */
878 specbind (Qinternal_interpreter_environment, newenv);
879 else
880 Vinternal_interpreter_environment = newenv;
882 else
883 specbind (var, val);
885 varlist = XCDR (varlist);
888 val = Fprogn (XCDR (args));
889 return unbind_to (count, val);
892 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
893 doc: /* Bind variables according to VARLIST then eval BODY.
894 The value of the last form in BODY is returned.
895 Each element of VARLIST is a symbol (which is bound to nil)
896 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
897 All the VALUEFORMs are evalled before any symbols are bound.
898 usage: (let VARLIST BODY...) */)
899 (Lisp_Object args)
901 Lisp_Object *temps, tem, lexenv;
902 Lisp_Object elt, varlist;
903 ptrdiff_t count = SPECPDL_INDEX ();
904 ptrdiff_t argnum;
905 USE_SAFE_ALLOCA;
907 varlist = XCAR (args);
909 /* Make space to hold the values to give the bound variables. */
910 elt = Flength (varlist);
911 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
913 /* Compute the values and store them in `temps'. */
915 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
917 QUIT;
918 elt = XCAR (varlist);
919 if (SYMBOLP (elt))
920 temps [argnum++] = Qnil;
921 else if (! NILP (Fcdr (Fcdr (elt))))
922 signal_error ("`let' bindings can have only one value-form", elt);
923 else
924 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
927 lexenv = Vinternal_interpreter_environment;
929 varlist = XCAR (args);
930 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
932 Lisp_Object var;
934 elt = XCAR (varlist);
935 var = SYMBOLP (elt) ? elt : Fcar (elt);
936 tem = temps[argnum++];
938 if (!NILP (lexenv) && SYMBOLP (var)
939 && !XSYMBOL (var)->declared_special
940 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
941 /* Lexically bind VAR by adding it to the lexenv alist. */
942 lexenv = Fcons (Fcons (var, tem), lexenv);
943 else
944 /* Dynamically bind VAR. */
945 specbind (var, tem);
948 if (!EQ (lexenv, Vinternal_interpreter_environment))
949 /* Instantiate a new lexical environment. */
950 specbind (Qinternal_interpreter_environment, lexenv);
952 elt = Fprogn (XCDR (args));
953 SAFE_FREE ();
954 return unbind_to (count, elt);
957 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
958 doc: /* If TEST yields non-nil, eval BODY... and repeat.
959 The order of execution is thus TEST, BODY, TEST, BODY and so on
960 until TEST returns nil.
961 usage: (while TEST BODY...) */)
962 (Lisp_Object args)
964 Lisp_Object test, body;
966 test = XCAR (args);
967 body = XCDR (args);
968 while (!NILP (eval_sub (test)))
970 QUIT;
971 Fprogn (body);
974 return Qnil;
977 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
978 doc: /* Return result of expanding macros at top level of FORM.
979 If FORM is not a macro call, it is returned unchanged.
980 Otherwise, the macro is expanded and the expansion is considered
981 in place of FORM. When a non-macro-call results, it is returned.
983 The second optional arg ENVIRONMENT specifies an environment of macro
984 definitions to shadow the loaded ones for use in file byte-compilation. */)
985 (Lisp_Object form, Lisp_Object environment)
987 /* With cleanups from Hallvard Furuseth. */
988 register Lisp_Object expander, sym, def, tem;
990 while (1)
992 /* Come back here each time we expand a macro call,
993 in case it expands into another macro call. */
994 if (!CONSP (form))
995 break;
996 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
997 def = sym = XCAR (form);
998 tem = Qnil;
999 /* Trace symbols aliases to other symbols
1000 until we get a symbol that is not an alias. */
1001 while (SYMBOLP (def))
1003 QUIT;
1004 sym = def;
1005 tem = Fassq (sym, environment);
1006 if (NILP (tem))
1008 def = XSYMBOL (sym)->function;
1009 if (!NILP (def))
1010 continue;
1012 break;
1014 /* Right now TEM is the result from SYM in ENVIRONMENT,
1015 and if TEM is nil then DEF is SYM's function definition. */
1016 if (NILP (tem))
1018 /* SYM is not mentioned in ENVIRONMENT.
1019 Look at its function definition. */
1020 def = Fautoload_do_load (def, sym, Qmacro);
1021 if (!CONSP (def))
1022 /* Not defined or definition not suitable. */
1023 break;
1024 if (!EQ (XCAR (def), Qmacro))
1025 break;
1026 else expander = XCDR (def);
1028 else
1030 expander = XCDR (tem);
1031 if (NILP (expander))
1032 break;
1035 Lisp_Object newform = apply1 (expander, XCDR (form));
1036 if (EQ (form, newform))
1037 break;
1038 else
1039 form = newform;
1042 return form;
1045 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1046 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1047 TAG is evalled to get the tag to use; it must not be nil.
1049 Then the BODY is executed.
1050 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1051 If no throw happens, `catch' returns the value of the last BODY form.
1052 If a throw happens, it specifies the value to return from `catch'.
1053 usage: (catch TAG BODY...) */)
1054 (Lisp_Object args)
1056 Lisp_Object tag = eval_sub (XCAR (args));
1057 return internal_catch (tag, Fprogn, XCDR (args));
1060 /* Assert that E is true, as a comment only. Use this instead of
1061 eassert (E) when E contains variables that might be clobbered by a
1062 longjmp. */
1064 #define clobbered_eassert(E) ((void) 0)
1066 /* Set up a catch, then call C function FUNC on argument ARG.
1067 FUNC should return a Lisp_Object.
1068 This is how catches are done from within C code. */
1070 Lisp_Object
1071 internal_catch (Lisp_Object tag,
1072 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1074 /* This structure is made part of the chain `catchlist'. */
1075 struct handler *c = push_handler (tag, CATCHER);
1077 /* Call FUNC. */
1078 if (! sys_setjmp (c->jmp))
1080 Lisp_Object val = func (arg);
1081 clobbered_eassert (handlerlist == c);
1082 handlerlist = handlerlist->next;
1083 return val;
1085 else
1086 { /* Throw works by a longjmp that comes right here. */
1087 Lisp_Object val = handlerlist->val;
1088 clobbered_eassert (handlerlist == c);
1089 handlerlist = handlerlist->next;
1090 return val;
1094 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1095 jump to that CATCH, returning VALUE as the value of that catch.
1097 This is the guts of Fthrow and Fsignal; they differ only in the way
1098 they choose the catch tag to throw to. A catch tag for a
1099 condition-case form has a TAG of Qnil.
1101 Before each catch is discarded, unbind all special bindings and
1102 execute all unwind-protect clauses made above that catch. Unwind
1103 the handler stack as we go, so that the proper handlers are in
1104 effect for each unwind-protect clause we run. At the end, restore
1105 some static info saved in CATCH, and longjmp to the location
1106 specified there.
1108 This is used for correct unwinding in Fthrow and Fsignal. */
1110 static _Noreturn void
1111 unwind_to_catch (struct handler *catch, Lisp_Object value)
1113 bool last_time;
1115 eassert (catch->next);
1117 /* Save the value in the tag. */
1118 catch->val = value;
1120 /* Restore certain special C variables. */
1121 set_poll_suppress_count (catch->poll_suppress_count);
1122 unblock_input_to (catch->interrupt_input_blocked);
1123 immediate_quit = 0;
1127 /* Unwind the specpdl stack, and then restore the proper set of
1128 handlers. */
1129 unbind_to (handlerlist->pdlcount, Qnil);
1130 last_time = handlerlist == catch;
1131 if (! last_time)
1132 handlerlist = handlerlist->next;
1134 while (! last_time);
1136 eassert (handlerlist == catch);
1138 byte_stack_list = catch->byte_stack;
1139 lisp_eval_depth = catch->lisp_eval_depth;
1141 sys_longjmp (catch->jmp, 1);
1144 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1145 doc: /* Throw to the catch for TAG and return VALUE from it.
1146 Both TAG and VALUE are evalled. */
1147 attributes: noreturn)
1148 (register Lisp_Object tag, Lisp_Object value)
1150 struct handler *c;
1152 if (!NILP (tag))
1153 for (c = handlerlist; c; c = c->next)
1155 if (c->type == CATCHER_ALL)
1156 unwind_to_catch (c, Fcons (tag, value));
1157 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1158 unwind_to_catch (c, value);
1160 xsignal2 (Qno_catch, tag, value);
1164 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1165 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1166 If BODYFORM completes normally, its value is returned
1167 after executing the UNWINDFORMS.
1168 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1169 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1170 (Lisp_Object args)
1172 Lisp_Object val;
1173 ptrdiff_t count = SPECPDL_INDEX ();
1175 record_unwind_protect (unwind_body, XCDR (args));
1176 val = eval_sub (XCAR (args));
1177 return unbind_to (count, val);
1180 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1181 doc: /* Regain control when an error is signaled.
1182 Executes BODYFORM and returns its value if no error happens.
1183 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1184 where the BODY is made of Lisp expressions.
1186 A handler is applicable to an error
1187 if CONDITION-NAME is one of the error's condition names.
1188 If an error happens, the first applicable handler is run.
1190 The car of a handler may be a list of condition names instead of a
1191 single condition name; then it handles all of them. If the special
1192 condition name `debug' is present in this list, it allows another
1193 condition in the list to run the debugger if `debug-on-error' and the
1194 other usual mechanisms says it should (otherwise, `condition-case'
1195 suppresses the debugger).
1197 When a handler handles an error, control returns to the `condition-case'
1198 and it executes the handler's BODY...
1199 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1200 \(If VAR is nil, the handler can't access that information.)
1201 Then the value of the last BODY form is returned from the `condition-case'
1202 expression.
1204 See also the function `signal' for more info.
1205 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1206 (Lisp_Object args)
1208 Lisp_Object var = XCAR (args);
1209 Lisp_Object bodyform = XCAR (XCDR (args));
1210 Lisp_Object handlers = XCDR (XCDR (args));
1212 return internal_lisp_condition_case (var, bodyform, handlers);
1215 /* Like Fcondition_case, but the args are separate
1216 rather than passed in a list. Used by Fbyte_code. */
1218 Lisp_Object
1219 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1220 Lisp_Object handlers)
1222 Lisp_Object val;
1223 struct handler *oldhandlerlist = handlerlist;
1224 int clausenb = 0;
1226 CHECK_SYMBOL (var);
1228 for (val = handlers; CONSP (val); val = XCDR (val))
1230 Lisp_Object tem = XCAR (val);
1231 clausenb++;
1232 if (! (NILP (tem)
1233 || (CONSP (tem)
1234 && (SYMBOLP (XCAR (tem))
1235 || CONSP (XCAR (tem))))))
1236 error ("Invalid condition handler: %s",
1237 SDATA (Fprin1_to_string (tem, Qt)));
1240 { /* The first clause is the one that should be checked first, so it should
1241 be added to handlerlist last. So we build in `clauses' a table that
1242 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1243 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1244 if (MAX_ALLOCA / word_size < clausenb)
1245 memory_full (SIZE_MAX);
1246 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1247 Lisp_Object *volatile clauses_volatile = clauses;
1248 int i = clausenb;
1249 for (val = handlers; CONSP (val); val = XCDR (val))
1250 clauses[--i] = XCAR (val);
1251 for (i = 0; i < clausenb; i++)
1253 Lisp_Object clause = clauses[i];
1254 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1255 if (!CONSP (condition))
1256 condition = Fcons (condition, Qnil);
1257 struct handler *c = push_handler (condition, CONDITION_CASE);
1258 if (sys_setjmp (c->jmp))
1260 ptrdiff_t count = SPECPDL_INDEX ();
1261 Lisp_Object val = handlerlist->val;
1262 Lisp_Object *chosen_clause = clauses_volatile;
1263 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1264 chosen_clause++;
1265 handlerlist = oldhandlerlist;
1266 if (!NILP (var))
1268 if (!NILP (Vinternal_interpreter_environment))
1269 specbind (Qinternal_interpreter_environment,
1270 Fcons (Fcons (var, val),
1271 Vinternal_interpreter_environment));
1272 else
1273 specbind (var, val);
1275 val = Fprogn (XCDR (*chosen_clause));
1276 /* Note that this just undoes the binding of var; whoever
1277 longjumped to us unwound the stack to c.pdlcount before
1278 throwing. */
1279 if (!NILP (var))
1280 unbind_to (count, Qnil);
1281 return val;
1286 val = eval_sub (bodyform);
1287 handlerlist = oldhandlerlist;
1288 return val;
1291 /* Call the function BFUN with no arguments, catching errors within it
1292 according to HANDLERS. If there is an error, call HFUN with
1293 one argument which is the data that describes the error:
1294 (SIGNALNAME . DATA)
1296 HANDLERS can be a list of conditions to catch.
1297 If HANDLERS is Qt, catch all errors.
1298 If HANDLERS is Qerror, catch all errors
1299 but allow the debugger to run if that is enabled. */
1301 Lisp_Object
1302 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1303 Lisp_Object (*hfun) (Lisp_Object))
1305 struct handler *c = push_handler (handlers, CONDITION_CASE);
1306 if (sys_setjmp (c->jmp))
1308 Lisp_Object val = handlerlist->val;
1309 clobbered_eassert (handlerlist == c);
1310 handlerlist = handlerlist->next;
1311 return hfun (val);
1313 else
1315 Lisp_Object val = bfun ();
1316 clobbered_eassert (handlerlist == c);
1317 handlerlist = handlerlist->next;
1318 return val;
1322 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1324 Lisp_Object
1325 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1326 Lisp_Object handlers,
1327 Lisp_Object (*hfun) (Lisp_Object))
1329 struct handler *c = push_handler (handlers, CONDITION_CASE);
1330 if (sys_setjmp (c->jmp))
1332 Lisp_Object val = handlerlist->val;
1333 clobbered_eassert (handlerlist == c);
1334 handlerlist = handlerlist->next;
1335 return hfun (val);
1337 else
1339 Lisp_Object val = bfun (arg);
1340 clobbered_eassert (handlerlist == c);
1341 handlerlist = handlerlist->next;
1342 return val;
1346 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1347 its arguments. */
1349 Lisp_Object
1350 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1351 Lisp_Object arg1,
1352 Lisp_Object arg2,
1353 Lisp_Object handlers,
1354 Lisp_Object (*hfun) (Lisp_Object))
1356 struct handler *c = push_handler (handlers, CONDITION_CASE);
1357 if (sys_setjmp (c->jmp))
1359 Lisp_Object val = handlerlist->val;
1360 clobbered_eassert (handlerlist == c);
1361 handlerlist = handlerlist->next;
1362 return hfun (val);
1364 else
1366 Lisp_Object val = bfun (arg1, arg2);
1367 clobbered_eassert (handlerlist == c);
1368 handlerlist = handlerlist->next;
1369 return val;
1373 /* Like internal_condition_case but call BFUN with NARGS as first,
1374 and ARGS as second argument. */
1376 Lisp_Object
1377 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1378 ptrdiff_t nargs,
1379 Lisp_Object *args,
1380 Lisp_Object handlers,
1381 Lisp_Object (*hfun) (Lisp_Object err,
1382 ptrdiff_t nargs,
1383 Lisp_Object *args))
1385 struct handler *c = push_handler (handlers, CONDITION_CASE);
1386 if (sys_setjmp (c->jmp))
1388 Lisp_Object val = handlerlist->val;
1389 clobbered_eassert (handlerlist == c);
1390 handlerlist = handlerlist->next;
1391 return hfun (val, nargs, args);
1393 else
1395 Lisp_Object val = bfun (nargs, args);
1396 clobbered_eassert (handlerlist == c);
1397 handlerlist = handlerlist->next;
1398 return val;
1402 struct handler *
1403 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1405 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1406 if (!c)
1407 memory_full (sizeof *c);
1408 return c;
1411 struct handler *
1412 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1414 struct handler *c = handlerlist->nextfree;
1415 if (!c)
1417 c = malloc (sizeof *c);
1418 if (!c)
1419 return c;
1420 if (profiler_memory_running)
1421 malloc_probe (sizeof *c);
1422 c->nextfree = NULL;
1423 handlerlist->nextfree = c;
1425 c->type = handlertype;
1426 c->tag_or_ch = tag_ch_val;
1427 c->val = Qnil;
1428 c->next = handlerlist;
1429 c->lisp_eval_depth = lisp_eval_depth;
1430 c->pdlcount = SPECPDL_INDEX ();
1431 c->poll_suppress_count = poll_suppress_count;
1432 c->interrupt_input_blocked = interrupt_input_blocked;
1433 c->byte_stack = byte_stack_list;
1434 handlerlist = c;
1435 return c;
1439 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1440 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1441 Lisp_Object data);
1443 void
1444 process_quit_flag (void)
1446 Lisp_Object flag = Vquit_flag;
1447 Vquit_flag = Qnil;
1448 if (EQ (flag, Qkill_emacs))
1449 Fkill_emacs (Qnil);
1450 if (EQ (Vthrow_on_input, flag))
1451 Fthrow (Vthrow_on_input, Qt);
1452 Fsignal (Qquit, Qnil);
1455 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1456 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1457 This function does not return.
1459 An error symbol is a symbol with an `error-conditions' property
1460 that is a list of condition names.
1461 A handler for any of those names will get to handle this signal.
1462 The symbol `error' should normally be one of them.
1464 DATA should be a list. Its elements are printed as part of the error message.
1465 See Info anchor `(elisp)Definition of signal' for some details on how this
1466 error message is constructed.
1467 If the signal is handled, DATA is made available to the handler.
1468 See also the function `condition-case'. */)
1469 (Lisp_Object error_symbol, Lisp_Object data)
1471 /* When memory is full, ERROR-SYMBOL is nil,
1472 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1473 That is a special case--don't do this in other situations. */
1474 Lisp_Object conditions;
1475 Lisp_Object string;
1476 Lisp_Object real_error_symbol
1477 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1478 register Lisp_Object clause = Qnil;
1479 struct handler *h;
1481 immediate_quit = 0;
1482 abort_on_gc = 0;
1483 if (gc_in_progress || waiting_for_input)
1484 emacs_abort ();
1486 #if 0 /* rms: I don't know why this was here,
1487 but it is surely wrong for an error that is handled. */
1488 #ifdef HAVE_WINDOW_SYSTEM
1489 if (display_hourglass_p)
1490 cancel_hourglass ();
1491 #endif
1492 #endif
1494 /* This hook is used by edebug. */
1495 if (! NILP (Vsignal_hook_function)
1496 && ! NILP (error_symbol))
1498 /* Edebug takes care of restoring these variables when it exits. */
1499 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1500 max_lisp_eval_depth = lisp_eval_depth + 20;
1502 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1503 max_specpdl_size = SPECPDL_INDEX () + 40;
1505 call2 (Vsignal_hook_function, error_symbol, data);
1508 conditions = Fget (real_error_symbol, Qerror_conditions);
1510 /* Remember from where signal was called. Skip over the frame for
1511 `signal' itself. If a frame for `error' follows, skip that,
1512 too. Don't do this when ERROR_SYMBOL is nil, because that
1513 is a memory-full error. */
1514 Vsignaling_function = Qnil;
1515 if (!NILP (error_symbol))
1517 union specbinding *pdl = backtrace_next (backtrace_top ());
1518 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1519 pdl = backtrace_next (pdl);
1520 if (backtrace_p (pdl))
1521 Vsignaling_function = backtrace_function (pdl);
1524 for (h = handlerlist; h; h = h->next)
1526 if (h->type != CONDITION_CASE)
1527 continue;
1528 clause = find_handler_clause (h->tag_or_ch, conditions);
1529 if (!NILP (clause))
1530 break;
1533 if (/* Don't run the debugger for a memory-full error.
1534 (There is no room in memory to do that!) */
1535 !NILP (error_symbol)
1536 && (!NILP (Vdebug_on_signal)
1537 /* If no handler is present now, try to run the debugger. */
1538 || NILP (clause)
1539 /* A `debug' symbol in the handler list disables the normal
1540 suppression of the debugger. */
1541 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1542 /* Special handler that means "print a message and run debugger
1543 if requested". */
1544 || EQ (h->tag_or_ch, Qerror)))
1546 bool debugger_called
1547 = maybe_call_debugger (conditions, error_symbol, data);
1548 /* We can't return values to code which signaled an error, but we
1549 can continue code which has signaled a quit. */
1550 if (debugger_called && EQ (real_error_symbol, Qquit))
1551 return Qnil;
1554 if (!NILP (clause))
1556 Lisp_Object unwind_data
1557 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1559 unwind_to_catch (h, unwind_data);
1561 else
1563 if (handlerlist != &handlerlist_sentinel)
1564 /* FIXME: This will come right back here if there's no `top-level'
1565 catcher. A better solution would be to abort here, and instead
1566 add a catch-all condition handler so we never come here. */
1567 Fthrow (Qtop_level, Qt);
1570 if (! NILP (error_symbol))
1571 data = Fcons (error_symbol, data);
1573 string = Ferror_message_string (data);
1574 fatal ("%s", SDATA (string));
1577 /* Internal version of Fsignal that never returns.
1578 Used for anything but Qquit (which can return from Fsignal). */
1580 void
1581 xsignal (Lisp_Object error_symbol, Lisp_Object data)
1583 Fsignal (error_symbol, data);
1584 emacs_abort ();
1587 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1589 void
1590 xsignal0 (Lisp_Object error_symbol)
1592 xsignal (error_symbol, Qnil);
1595 void
1596 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1598 xsignal (error_symbol, list1 (arg));
1601 void
1602 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1604 xsignal (error_symbol, list2 (arg1, arg2));
1607 void
1608 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1610 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1613 /* Signal `error' with message S, and additional arg ARG.
1614 If ARG is not a genuine list, make it a one-element list. */
1616 void
1617 signal_error (const char *s, Lisp_Object arg)
1619 Lisp_Object tortoise, hare;
1621 hare = tortoise = arg;
1622 while (CONSP (hare))
1624 hare = XCDR (hare);
1625 if (!CONSP (hare))
1626 break;
1628 hare = XCDR (hare);
1629 tortoise = XCDR (tortoise);
1631 if (EQ (hare, tortoise))
1632 break;
1635 if (!NILP (hare))
1636 arg = list1 (arg);
1638 xsignal (Qerror, Fcons (build_string (s), arg));
1642 /* Return true if LIST is a non-nil atom or
1643 a list containing one of CONDITIONS. */
1645 static bool
1646 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1648 if (NILP (list))
1649 return 0;
1650 if (! CONSP (list))
1651 return 1;
1653 while (CONSP (conditions))
1655 Lisp_Object this, tail;
1656 this = XCAR (conditions);
1657 for (tail = list; CONSP (tail); tail = XCDR (tail))
1658 if (EQ (XCAR (tail), this))
1659 return 1;
1660 conditions = XCDR (conditions);
1662 return 0;
1665 /* Return true if an error with condition-symbols CONDITIONS,
1666 and described by SIGNAL-DATA, should skip the debugger
1667 according to debugger-ignored-errors. */
1669 static bool
1670 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1672 Lisp_Object tail;
1673 bool first_string = 1;
1674 Lisp_Object error_message;
1676 error_message = Qnil;
1677 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1679 if (STRINGP (XCAR (tail)))
1681 if (first_string)
1683 error_message = Ferror_message_string (data);
1684 first_string = 0;
1687 if (fast_string_match (XCAR (tail), error_message) >= 0)
1688 return 1;
1690 else
1692 Lisp_Object contail;
1694 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1695 if (EQ (XCAR (tail), XCAR (contail)))
1696 return 1;
1700 return 0;
1703 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1704 SIG and DATA describe the signal. There are two ways to pass them:
1705 = SIG is the error symbol, and DATA is the rest of the data.
1706 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1707 This is for memory-full errors only. */
1708 static bool
1709 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1711 Lisp_Object combined_data;
1713 combined_data = Fcons (sig, data);
1715 if (
1716 /* Don't try to run the debugger with interrupts blocked.
1717 The editing loop would return anyway. */
1718 ! input_blocked_p ()
1719 && NILP (Vinhibit_debugger)
1720 /* Does user want to enter debugger for this kind of error? */
1721 && (EQ (sig, Qquit)
1722 ? debug_on_quit
1723 : wants_debugger (Vdebug_on_error, conditions))
1724 && ! skip_debugger (conditions, combined_data)
1725 /* RMS: What's this for? */
1726 && when_entered_debugger < num_nonmacro_input_events)
1728 call_debugger (list2 (Qerror, combined_data));
1729 return 1;
1732 return 0;
1735 static Lisp_Object
1736 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1738 register Lisp_Object h;
1740 /* t is used by handlers for all conditions, set up by C code. */
1741 if (EQ (handlers, Qt))
1742 return Qt;
1744 /* error is used similarly, but means print an error message
1745 and run the debugger if that is enabled. */
1746 if (EQ (handlers, Qerror))
1747 return Qt;
1749 for (h = handlers; CONSP (h); h = XCDR (h))
1751 Lisp_Object handler = XCAR (h);
1752 if (!NILP (Fmemq (handler, conditions)))
1753 return handlers;
1756 return Qnil;
1760 /* Dump an error message; called like vprintf. */
1761 void
1762 verror (const char *m, va_list ap)
1764 char buf[4000];
1765 ptrdiff_t size = sizeof buf;
1766 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1767 char *buffer = buf;
1768 ptrdiff_t used;
1769 Lisp_Object string;
1771 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1772 string = make_string (buffer, used);
1773 if (buffer != buf)
1774 xfree (buffer);
1776 xsignal1 (Qerror, string);
1780 /* Dump an error message; called like printf. */
1782 /* VARARGS 1 */
1783 void
1784 error (const char *m, ...)
1786 va_list ap;
1787 va_start (ap, m);
1788 verror (m, ap);
1791 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1792 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1793 This means it contains a description for how to read arguments to give it.
1794 The value is nil for an invalid function or a symbol with no function
1795 definition.
1797 Interactively callable functions include strings and vectors (treated
1798 as keyboard macros), lambda-expressions that contain a top-level call
1799 to `interactive', autoload definitions made by `autoload' with non-nil
1800 fourth argument, and some of the built-in functions of Lisp.
1802 Also, a symbol satisfies `commandp' if its function definition does so.
1804 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1805 then strings and vectors are not accepted. */)
1806 (Lisp_Object function, Lisp_Object for_call_interactively)
1808 register Lisp_Object fun;
1809 register Lisp_Object funcar;
1810 Lisp_Object if_prop = Qnil;
1812 fun = function;
1814 fun = indirect_function (fun); /* Check cycles. */
1815 if (NILP (fun))
1816 return Qnil;
1818 /* Check an `interactive-form' property if present, analogous to the
1819 function-documentation property. */
1820 fun = function;
1821 while (SYMBOLP (fun))
1823 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1824 if (!NILP (tmp))
1825 if_prop = Qt;
1826 fun = Fsymbol_function (fun);
1829 /* Emacs primitives are interactive if their DEFUN specifies an
1830 interactive spec. */
1831 if (SUBRP (fun))
1832 return XSUBR (fun)->intspec ? Qt : if_prop;
1834 /* Bytecode objects are interactive if they are long enough to
1835 have an element whose index is COMPILED_INTERACTIVE, which is
1836 where the interactive spec is stored. */
1837 else if (COMPILEDP (fun))
1838 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1839 ? Qt : if_prop);
1841 /* Strings and vectors are keyboard macros. */
1842 if (STRINGP (fun) || VECTORP (fun))
1843 return (NILP (for_call_interactively) ? Qt : Qnil);
1845 /* Lists may represent commands. */
1846 if (!CONSP (fun))
1847 return Qnil;
1848 funcar = XCAR (fun);
1849 if (EQ (funcar, Qclosure))
1850 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1851 ? Qt : if_prop);
1852 else if (EQ (funcar, Qlambda))
1853 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1854 else if (EQ (funcar, Qautoload))
1855 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1856 else
1857 return Qnil;
1860 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1861 doc: /* Define FUNCTION to autoload from FILE.
1862 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1863 Third arg DOCSTRING is documentation for the function.
1864 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1865 Fifth arg TYPE indicates the type of the object:
1866 nil or omitted says FUNCTION is a function,
1867 `keymap' says FUNCTION is really a keymap, and
1868 `macro' or t says FUNCTION is really a macro.
1869 Third through fifth args give info about the real definition.
1870 They default to nil.
1871 If FUNCTION is already defined other than as an autoload,
1872 this does nothing and returns nil. */)
1873 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1875 CHECK_SYMBOL (function);
1876 CHECK_STRING (file);
1878 /* If function is defined and not as an autoload, don't override. */
1879 if (!NILP (XSYMBOL (function)->function)
1880 && !AUTOLOADP (XSYMBOL (function)->function))
1881 return Qnil;
1883 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1884 /* `read1' in lread.c has found the docstring starting with "\
1885 and assumed the docstring will be provided by Snarf-documentation, so it
1886 passed us 0 instead. But that leads to accidental sharing in purecopy's
1887 hash-consing, so we use a (hopefully) unique integer instead. */
1888 docstring = make_number (XHASH (function));
1889 return Fdefalias (function,
1890 list5 (Qautoload, file, docstring, interactive, type),
1891 Qnil);
1894 void
1895 un_autoload (Lisp_Object oldqueue)
1897 Lisp_Object queue, first, second;
1899 /* Queue to unwind is current value of Vautoload_queue.
1900 oldqueue is the shadowed value to leave in Vautoload_queue. */
1901 queue = Vautoload_queue;
1902 Vautoload_queue = oldqueue;
1903 while (CONSP (queue))
1905 first = XCAR (queue);
1906 second = Fcdr (first);
1907 first = Fcar (first);
1908 if (EQ (first, make_number (0)))
1909 Vfeatures = second;
1910 else
1911 Ffset (first, second);
1912 queue = XCDR (queue);
1916 /* Load an autoloaded function.
1917 FUNNAME is the symbol which is the function's name.
1918 FUNDEF is the autoload definition (a list). */
1920 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1921 doc: /* Load FUNDEF which should be an autoload.
1922 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1923 in which case the function returns the new autoloaded function value.
1924 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1925 it defines a macro. */)
1926 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1928 ptrdiff_t count = SPECPDL_INDEX ();
1930 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1931 return fundef;
1933 if (EQ (macro_only, Qmacro))
1935 Lisp_Object kind = Fnth (make_number (4), fundef);
1936 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1937 return fundef;
1940 /* This is to make sure that loadup.el gives a clear picture
1941 of what files are preloaded and when. */
1942 if (! NILP (Vpurify_flag))
1943 error ("Attempt to autoload %s while preparing to dump",
1944 SDATA (SYMBOL_NAME (funname)));
1946 CHECK_SYMBOL (funname);
1948 /* Preserve the match data. */
1949 record_unwind_save_match_data ();
1951 /* If autoloading gets an error (which includes the error of failing
1952 to define the function being called), we use Vautoload_queue
1953 to undo function definitions and `provide' calls made by
1954 the function. We do this in the specific case of autoloading
1955 because autoloading is not an explicit request "load this file",
1956 but rather a request to "call this function".
1958 The value saved here is to be restored into Vautoload_queue. */
1959 record_unwind_protect (un_autoload, Vautoload_queue);
1960 Vautoload_queue = Qt;
1961 /* If `macro_only', assume this autoload to be a "best-effort",
1962 so don't signal an error if autoloading fails. */
1963 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
1965 /* Once loading finishes, don't undo it. */
1966 Vautoload_queue = Qt;
1967 unbind_to (count, Qnil);
1969 if (NILP (funname))
1970 return Qnil;
1971 else
1973 Lisp_Object fun = Findirect_function (funname, Qnil);
1975 if (!NILP (Fequal (fun, fundef)))
1976 error ("Autoloading failed to define function %s",
1977 SDATA (SYMBOL_NAME (funname)));
1978 else
1979 return fun;
1984 DEFUN ("eval", Feval, Seval, 1, 2, 0,
1985 doc: /* Evaluate FORM and return its value.
1986 If LEXICAL is t, evaluate using lexical scoping.
1987 LEXICAL can also be an actual lexical environment, in the form of an
1988 alist mapping symbols to their value. */)
1989 (Lisp_Object form, Lisp_Object lexical)
1991 ptrdiff_t count = SPECPDL_INDEX ();
1992 specbind (Qinternal_interpreter_environment,
1993 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
1994 return unbind_to (count, eval_sub (form));
1997 /* Grow the specpdl stack by one entry.
1998 The caller should have already initialized the entry.
1999 Signal an error on stack overflow.
2001 Make sure that there is always one unused entry past the top of the
2002 stack, so that the just-initialized entry is safely unwound if
2003 memory exhausted and an error is signaled here. Also, allocate a
2004 never-used entry just before the bottom of the stack; sometimes its
2005 address is taken. */
2007 static void
2008 grow_specpdl (void)
2010 specpdl_ptr++;
2012 if (specpdl_ptr == specpdl + specpdl_size)
2014 ptrdiff_t count = SPECPDL_INDEX ();
2015 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2016 union specbinding *pdlvec = specpdl - 1;
2017 ptrdiff_t pdlvecsize = specpdl_size + 1;
2018 if (max_size <= specpdl_size)
2020 if (max_specpdl_size < 400)
2021 max_size = max_specpdl_size = 400;
2022 if (max_size <= specpdl_size)
2023 signal_error ("Variable binding depth exceeds max-specpdl-size",
2024 Qnil);
2026 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2027 specpdl = pdlvec + 1;
2028 specpdl_size = pdlvecsize - 1;
2029 specpdl_ptr = specpdl + count;
2033 ptrdiff_t
2034 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2036 ptrdiff_t count = SPECPDL_INDEX ();
2038 eassert (nargs >= UNEVALLED);
2039 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2040 specpdl_ptr->bt.debug_on_exit = false;
2041 specpdl_ptr->bt.function = function;
2042 specpdl_ptr->bt.args = args;
2043 specpdl_ptr->bt.nargs = nargs;
2044 grow_specpdl ();
2046 return count;
2049 /* Eval a sub-expression of the current expression (i.e. in the same
2050 lexical scope). */
2051 Lisp_Object
2052 eval_sub (Lisp_Object form)
2054 Lisp_Object fun, val, original_fun, original_args;
2055 Lisp_Object funcar;
2056 ptrdiff_t count;
2058 /* Declare here, as this array may be accessed by call_debugger near
2059 the end of this function. See Bug#21245. */
2060 Lisp_Object argvals[8];
2062 if (SYMBOLP (form))
2064 /* Look up its binding in the lexical environment.
2065 We do not pay attention to the declared_special flag here, since we
2066 already did that when let-binding the variable. */
2067 Lisp_Object lex_binding
2068 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2069 ? Fassq (form, Vinternal_interpreter_environment)
2070 : Qnil;
2071 if (CONSP (lex_binding))
2072 return XCDR (lex_binding);
2073 else
2074 return Fsymbol_value (form);
2077 if (!CONSP (form))
2078 return form;
2080 QUIT;
2082 maybe_gc ();
2084 if (++lisp_eval_depth > max_lisp_eval_depth)
2086 if (max_lisp_eval_depth < 100)
2087 max_lisp_eval_depth = 100;
2088 if (lisp_eval_depth > max_lisp_eval_depth)
2089 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2092 original_fun = XCAR (form);
2093 original_args = XCDR (form);
2095 /* This also protects them from gc. */
2096 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2098 if (debug_on_next_call)
2099 do_debug_on_call (Qt, count);
2101 /* At this point, only original_fun and original_args
2102 have values that will be used below. */
2103 retry:
2105 /* Optimize for no indirection. */
2106 fun = original_fun;
2107 if (!SYMBOLP (fun))
2108 fun = Ffunction (Fcons (fun, Qnil));
2109 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2110 fun = indirect_function (fun);
2112 if (SUBRP (fun))
2114 Lisp_Object args_left = original_args;
2115 Lisp_Object numargs = Flength (args_left);
2117 check_cons_list ();
2119 if (XINT (numargs) < XSUBR (fun)->min_args
2120 || (XSUBR (fun)->max_args >= 0
2121 && XSUBR (fun)->max_args < XINT (numargs)))
2122 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2124 else if (XSUBR (fun)->max_args == UNEVALLED)
2125 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2126 else if (XSUBR (fun)->max_args == MANY)
2128 /* Pass a vector of evaluated arguments. */
2129 Lisp_Object *vals;
2130 ptrdiff_t argnum = 0;
2131 USE_SAFE_ALLOCA;
2133 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2135 while (!NILP (args_left))
2137 vals[argnum++] = eval_sub (Fcar (args_left));
2138 args_left = Fcdr (args_left);
2141 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2143 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2145 check_cons_list ();
2146 lisp_eval_depth--;
2147 /* Do the debug-on-exit now, while VALS still exists. */
2148 if (backtrace_debug_on_exit (specpdl + count))
2149 val = call_debugger (list2 (Qexit, val));
2150 SAFE_FREE ();
2151 specpdl_ptr--;
2152 return val;
2154 else
2156 int i, maxargs = XSUBR (fun)->max_args;
2158 for (i = 0; i < maxargs; i++)
2160 argvals[i] = eval_sub (Fcar (args_left));
2161 args_left = Fcdr (args_left);
2164 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2166 switch (i)
2168 case 0:
2169 val = (XSUBR (fun)->function.a0 ());
2170 break;
2171 case 1:
2172 val = (XSUBR (fun)->function.a1 (argvals[0]));
2173 break;
2174 case 2:
2175 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2176 break;
2177 case 3:
2178 val = (XSUBR (fun)->function.a3
2179 (argvals[0], argvals[1], argvals[2]));
2180 break;
2181 case 4:
2182 val = (XSUBR (fun)->function.a4
2183 (argvals[0], argvals[1], argvals[2], argvals[3]));
2184 break;
2185 case 5:
2186 val = (XSUBR (fun)->function.a5
2187 (argvals[0], argvals[1], argvals[2], argvals[3],
2188 argvals[4]));
2189 break;
2190 case 6:
2191 val = (XSUBR (fun)->function.a6
2192 (argvals[0], argvals[1], argvals[2], argvals[3],
2193 argvals[4], argvals[5]));
2194 break;
2195 case 7:
2196 val = (XSUBR (fun)->function.a7
2197 (argvals[0], argvals[1], argvals[2], argvals[3],
2198 argvals[4], argvals[5], argvals[6]));
2199 break;
2201 case 8:
2202 val = (XSUBR (fun)->function.a8
2203 (argvals[0], argvals[1], argvals[2], argvals[3],
2204 argvals[4], argvals[5], argvals[6], argvals[7]));
2205 break;
2207 default:
2208 /* Someone has created a subr that takes more arguments than
2209 is supported by this code. We need to either rewrite the
2210 subr to use a different argument protocol, or add more
2211 cases to this switch. */
2212 emacs_abort ();
2216 else if (COMPILEDP (fun))
2217 return apply_lambda (fun, original_args, count);
2218 else
2220 if (NILP (fun))
2221 xsignal1 (Qvoid_function, original_fun);
2222 if (!CONSP (fun))
2223 xsignal1 (Qinvalid_function, original_fun);
2224 funcar = XCAR (fun);
2225 if (!SYMBOLP (funcar))
2226 xsignal1 (Qinvalid_function, original_fun);
2227 if (EQ (funcar, Qautoload))
2229 Fautoload_do_load (fun, original_fun, Qnil);
2230 goto retry;
2232 if (EQ (funcar, Qmacro))
2234 ptrdiff_t count1 = SPECPDL_INDEX ();
2235 Lisp_Object exp;
2236 /* Bind lexical-binding during expansion of the macro, so the
2237 macro can know reliably if the code it outputs will be
2238 interpreted using lexical-binding or not. */
2239 specbind (Qlexical_binding,
2240 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2241 exp = apply1 (Fcdr (fun), original_args);
2242 unbind_to (count1, Qnil);
2243 val = eval_sub (exp);
2245 else if (EQ (funcar, Qlambda)
2246 || EQ (funcar, Qclosure))
2247 return apply_lambda (fun, original_args, count);
2248 else
2249 xsignal1 (Qinvalid_function, original_fun);
2251 check_cons_list ();
2253 lisp_eval_depth--;
2254 if (backtrace_debug_on_exit (specpdl + count))
2255 val = call_debugger (list2 (Qexit, val));
2256 specpdl_ptr--;
2258 return val;
2261 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2262 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2263 Then return the value FUNCTION returns.
2264 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2265 usage: (apply FUNCTION &rest ARGUMENTS) */)
2266 (ptrdiff_t nargs, Lisp_Object *args)
2268 ptrdiff_t i, numargs, funcall_nargs;
2269 register Lisp_Object *funcall_args = NULL;
2270 register Lisp_Object spread_arg = args[nargs - 1];
2271 Lisp_Object fun = args[0];
2272 Lisp_Object retval;
2273 USE_SAFE_ALLOCA;
2275 CHECK_LIST (spread_arg);
2277 numargs = XINT (Flength (spread_arg));
2279 if (numargs == 0)
2280 return Ffuncall (nargs - 1, args);
2281 else if (numargs == 1)
2283 args [nargs - 1] = XCAR (spread_arg);
2284 return Ffuncall (nargs, args);
2287 numargs += nargs - 2;
2289 /* Optimize for no indirection. */
2290 if (SYMBOLP (fun) && !NILP (fun)
2291 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2293 fun = indirect_function (fun);
2294 if (NILP (fun))
2295 /* Let funcall get the error. */
2296 fun = args[0];
2299 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2300 /* Don't hide an error by adding missing arguments. */
2301 && numargs >= XSUBR (fun)->min_args)
2303 /* Avoid making funcall cons up a yet another new vector of arguments
2304 by explicitly supplying nil's for optional values. */
2305 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2306 memclear (funcall_args + numargs + 1,
2307 (XSUBR (fun)->max_args - numargs) * word_size);
2308 funcall_nargs = 1 + XSUBR (fun)->max_args;
2310 else
2311 { /* We add 1 to numargs because funcall_args includes the
2312 function itself as well as its arguments. */
2313 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2314 funcall_nargs = 1 + numargs;
2317 memcpy (funcall_args, args, nargs * word_size);
2318 /* Spread the last arg we got. Its first element goes in
2319 the slot that it used to occupy, hence this value of I. */
2320 i = nargs - 1;
2321 while (!NILP (spread_arg))
2323 funcall_args [i++] = XCAR (spread_arg);
2324 spread_arg = XCDR (spread_arg);
2327 retval = Ffuncall (funcall_nargs, funcall_args);
2329 SAFE_FREE ();
2330 return retval;
2333 /* Run hook variables in various ways. */
2335 static Lisp_Object
2336 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2338 Ffuncall (nargs, args);
2339 return Qnil;
2342 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2343 doc: /* Run each hook in HOOKS.
2344 Each argument should be a symbol, a hook variable.
2345 These symbols are processed in the order specified.
2346 If a hook symbol has a non-nil value, that value may be a function
2347 or a list of functions to be called to run the hook.
2348 If the value is a function, it is called with no arguments.
2349 If it is a list, the elements are called, in order, with no arguments.
2351 Major modes should not use this function directly to run their mode
2352 hook; they should use `run-mode-hooks' instead.
2354 Do not use `make-local-variable' to make a hook variable buffer-local.
2355 Instead, use `add-hook' and specify t for the LOCAL argument.
2356 usage: (run-hooks &rest HOOKS) */)
2357 (ptrdiff_t nargs, Lisp_Object *args)
2359 ptrdiff_t i;
2361 for (i = 0; i < nargs; i++)
2362 run_hook (args[i]);
2364 return Qnil;
2367 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2368 Srun_hook_with_args, 1, MANY, 0,
2369 doc: /* Run HOOK with the specified arguments ARGS.
2370 HOOK should be a symbol, a hook variable. The value of HOOK
2371 may be nil, a function, or a list of functions. Call each
2372 function in order with arguments ARGS. The final return value
2373 is unspecified.
2375 Do not use `make-local-variable' to make a hook variable buffer-local.
2376 Instead, use `add-hook' and specify t for the LOCAL argument.
2377 usage: (run-hook-with-args HOOK &rest ARGS) */)
2378 (ptrdiff_t nargs, Lisp_Object *args)
2380 return run_hook_with_args (nargs, args, funcall_nil);
2383 /* NB this one still documents a specific non-nil return value.
2384 (As did run-hook-with-args and run-hook-with-args-until-failure
2385 until they were changed in 24.1.) */
2386 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2387 Srun_hook_with_args_until_success, 1, MANY, 0,
2388 doc: /* Run HOOK with the specified arguments ARGS.
2389 HOOK should be a symbol, a hook variable. The value of HOOK
2390 may be nil, a function, or a list of functions. Call each
2391 function in order with arguments ARGS, stopping at the first
2392 one that returns non-nil, and return that value. Otherwise (if
2393 all functions return nil, or if there are no functions to call),
2394 return nil.
2396 Do not use `make-local-variable' to make a hook variable buffer-local.
2397 Instead, use `add-hook' and specify t for the LOCAL argument.
2398 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2399 (ptrdiff_t nargs, Lisp_Object *args)
2401 return run_hook_with_args (nargs, args, Ffuncall);
2404 static Lisp_Object
2405 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2407 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2410 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2411 Srun_hook_with_args_until_failure, 1, MANY, 0,
2412 doc: /* Run HOOK with the specified arguments ARGS.
2413 HOOK should be a symbol, a hook variable. The value of HOOK
2414 may be nil, a function, or a list of functions. Call each
2415 function in order with arguments ARGS, stopping at the first
2416 one that returns nil, and return nil. Otherwise (if all functions
2417 return non-nil, or if there are no functions to call), return non-nil
2418 \(do not rely on the precise return value in this case).
2420 Do not use `make-local-variable' to make a hook variable buffer-local.
2421 Instead, use `add-hook' and specify t for the LOCAL argument.
2422 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2423 (ptrdiff_t nargs, Lisp_Object *args)
2425 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2428 static Lisp_Object
2429 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2431 Lisp_Object tmp = args[0], ret;
2432 args[0] = args[1];
2433 args[1] = tmp;
2434 ret = Ffuncall (nargs, args);
2435 args[1] = args[0];
2436 args[0] = tmp;
2437 return ret;
2440 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2441 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2442 I.e. instead of calling each function FUN directly with arguments ARGS,
2443 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2444 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2445 aborts and returns that value.
2446 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2447 (ptrdiff_t nargs, Lisp_Object *args)
2449 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2452 /* ARGS[0] should be a hook symbol.
2453 Call each of the functions in the hook value, passing each of them
2454 as arguments all the rest of ARGS (all NARGS - 1 elements).
2455 FUNCALL specifies how to call each function on the hook. */
2457 Lisp_Object
2458 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2459 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2461 Lisp_Object sym, val, ret = Qnil;
2463 /* If we are dying or still initializing,
2464 don't do anything--it would probably crash if we tried. */
2465 if (NILP (Vrun_hooks))
2466 return Qnil;
2468 sym = args[0];
2469 val = find_symbol_value (sym);
2471 if (EQ (val, Qunbound) || NILP (val))
2472 return ret;
2473 else if (!CONSP (val) || FUNCTIONP (val))
2475 args[0] = val;
2476 return funcall (nargs, args);
2478 else
2480 Lisp_Object global_vals = Qnil;
2482 for (;
2483 CONSP (val) && NILP (ret);
2484 val = XCDR (val))
2486 if (EQ (XCAR (val), Qt))
2488 /* t indicates this hook has a local binding;
2489 it means to run the global binding too. */
2490 global_vals = Fdefault_value (sym);
2491 if (NILP (global_vals)) continue;
2493 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2495 args[0] = global_vals;
2496 ret = funcall (nargs, args);
2498 else
2500 for (;
2501 CONSP (global_vals) && NILP (ret);
2502 global_vals = XCDR (global_vals))
2504 args[0] = XCAR (global_vals);
2505 /* In a global value, t should not occur. If it does, we
2506 must ignore it to avoid an endless loop. */
2507 if (!EQ (args[0], Qt))
2508 ret = funcall (nargs, args);
2512 else
2514 args[0] = XCAR (val);
2515 ret = funcall (nargs, args);
2519 return ret;
2523 /* Run the hook HOOK, giving each function no args. */
2525 void
2526 run_hook (Lisp_Object hook)
2528 Frun_hook_with_args (1, &hook);
2531 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2533 void
2534 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2536 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2539 /* Apply fn to arg. */
2540 Lisp_Object
2541 apply1 (Lisp_Object fn, Lisp_Object arg)
2543 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2546 /* Call function fn on no arguments. */
2547 Lisp_Object
2548 call0 (Lisp_Object fn)
2550 return Ffuncall (1, &fn);
2553 /* Call function fn with 1 argument arg1. */
2554 /* ARGSUSED */
2555 Lisp_Object
2556 call1 (Lisp_Object fn, Lisp_Object arg1)
2558 return CALLN (Ffuncall, fn, arg1);
2561 /* Call function fn with 2 arguments arg1, arg2. */
2562 /* ARGSUSED */
2563 Lisp_Object
2564 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2566 return CALLN (Ffuncall, fn, arg1, arg2);
2569 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2570 /* ARGSUSED */
2571 Lisp_Object
2572 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2574 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2577 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2578 /* ARGSUSED */
2579 Lisp_Object
2580 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2581 Lisp_Object arg4)
2583 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2586 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2587 /* ARGSUSED */
2588 Lisp_Object
2589 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2590 Lisp_Object arg4, Lisp_Object arg5)
2592 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2595 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2596 /* ARGSUSED */
2597 Lisp_Object
2598 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2599 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2601 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2604 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2605 /* ARGSUSED */
2606 Lisp_Object
2607 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2608 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2610 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2613 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2614 doc: /* Non-nil if OBJECT is a function. */)
2615 (Lisp_Object object)
2617 if (FUNCTIONP (object))
2618 return Qt;
2619 return Qnil;
2622 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2623 doc: /* Call first argument as a function, passing remaining arguments to it.
2624 Return the value that function returns.
2625 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2626 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2627 (ptrdiff_t nargs, Lisp_Object *args)
2629 Lisp_Object fun, original_fun;
2630 Lisp_Object funcar;
2631 ptrdiff_t numargs = nargs - 1;
2632 Lisp_Object lisp_numargs;
2633 Lisp_Object val;
2634 Lisp_Object *internal_args;
2635 ptrdiff_t count;
2637 QUIT;
2639 if (++lisp_eval_depth > max_lisp_eval_depth)
2641 if (max_lisp_eval_depth < 100)
2642 max_lisp_eval_depth = 100;
2643 if (lisp_eval_depth > max_lisp_eval_depth)
2644 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2647 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2649 maybe_gc ();
2651 if (debug_on_next_call)
2652 do_debug_on_call (Qlambda, count);
2654 check_cons_list ();
2656 original_fun = args[0];
2658 retry:
2660 /* Optimize for no indirection. */
2661 fun = original_fun;
2662 if (SYMBOLP (fun) && !NILP (fun)
2663 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2664 fun = indirect_function (fun);
2666 if (SUBRP (fun))
2668 if (numargs < XSUBR (fun)->min_args
2669 || (XSUBR (fun)->max_args >= 0 && XSUBR (fun)->max_args < numargs))
2671 XSETFASTINT (lisp_numargs, numargs);
2672 xsignal2 (Qwrong_number_of_arguments, original_fun, lisp_numargs);
2675 else if (XSUBR (fun)->max_args == UNEVALLED)
2676 xsignal1 (Qinvalid_function, original_fun);
2678 else if (XSUBR (fun)->max_args == MANY)
2679 val = (XSUBR (fun)->function.aMANY) (numargs, args + 1);
2680 else
2682 Lisp_Object internal_argbuf[8];
2683 if (XSUBR (fun)->max_args > numargs)
2685 eassert (XSUBR (fun)->max_args <= ARRAYELTS (internal_argbuf));
2686 internal_args = internal_argbuf;
2687 memcpy (internal_args, args + 1, numargs * word_size);
2688 memclear (internal_args + numargs,
2689 (XSUBR (fun)->max_args - numargs) * word_size);
2691 else
2692 internal_args = args + 1;
2693 switch (XSUBR (fun)->max_args)
2695 case 0:
2696 val = (XSUBR (fun)->function.a0 ());
2697 break;
2698 case 1:
2699 val = (XSUBR (fun)->function.a1 (internal_args[0]));
2700 break;
2701 case 2:
2702 val = (XSUBR (fun)->function.a2
2703 (internal_args[0], internal_args[1]));
2704 break;
2705 case 3:
2706 val = (XSUBR (fun)->function.a3
2707 (internal_args[0], internal_args[1], internal_args[2]));
2708 break;
2709 case 4:
2710 val = (XSUBR (fun)->function.a4
2711 (internal_args[0], internal_args[1], internal_args[2],
2712 internal_args[3]));
2713 break;
2714 case 5:
2715 val = (XSUBR (fun)->function.a5
2716 (internal_args[0], internal_args[1], internal_args[2],
2717 internal_args[3], internal_args[4]));
2718 break;
2719 case 6:
2720 val = (XSUBR (fun)->function.a6
2721 (internal_args[0], internal_args[1], internal_args[2],
2722 internal_args[3], internal_args[4], internal_args[5]));
2723 break;
2724 case 7:
2725 val = (XSUBR (fun)->function.a7
2726 (internal_args[0], internal_args[1], internal_args[2],
2727 internal_args[3], internal_args[4], internal_args[5],
2728 internal_args[6]));
2729 break;
2731 case 8:
2732 val = (XSUBR (fun)->function.a8
2733 (internal_args[0], internal_args[1], internal_args[2],
2734 internal_args[3], internal_args[4], internal_args[5],
2735 internal_args[6], internal_args[7]));
2736 break;
2738 default:
2740 /* If a subr takes more than 8 arguments without using MANY
2741 or UNEVALLED, we need to extend this function to support it.
2742 Until this is done, there is no way to call the function. */
2743 emacs_abort ();
2747 else if (COMPILEDP (fun))
2748 val = funcall_lambda (fun, numargs, args + 1);
2749 else
2751 if (NILP (fun))
2752 xsignal1 (Qvoid_function, original_fun);
2753 if (!CONSP (fun))
2754 xsignal1 (Qinvalid_function, original_fun);
2755 funcar = XCAR (fun);
2756 if (!SYMBOLP (funcar))
2757 xsignal1 (Qinvalid_function, original_fun);
2758 if (EQ (funcar, Qlambda)
2759 || EQ (funcar, Qclosure))
2760 val = funcall_lambda (fun, numargs, args + 1);
2761 else if (EQ (funcar, Qautoload))
2763 Fautoload_do_load (fun, original_fun, Qnil);
2764 check_cons_list ();
2765 goto retry;
2767 else
2768 xsignal1 (Qinvalid_function, original_fun);
2770 check_cons_list ();
2771 lisp_eval_depth--;
2772 if (backtrace_debug_on_exit (specpdl + count))
2773 val = call_debugger (list2 (Qexit, val));
2774 specpdl_ptr--;
2775 return val;
2778 static Lisp_Object
2779 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2781 Lisp_Object args_left;
2782 ptrdiff_t i;
2783 EMACS_INT numargs;
2784 Lisp_Object *arg_vector;
2785 Lisp_Object tem;
2786 USE_SAFE_ALLOCA;
2788 numargs = XFASTINT (Flength (args));
2789 SAFE_ALLOCA_LISP (arg_vector, numargs);
2790 args_left = args;
2792 for (i = 0; i < numargs; )
2794 tem = Fcar (args_left), args_left = Fcdr (args_left);
2795 tem = eval_sub (tem);
2796 arg_vector[i++] = tem;
2799 set_backtrace_args (specpdl + count, arg_vector, i);
2800 tem = funcall_lambda (fun, numargs, arg_vector);
2802 check_cons_list ();
2803 lisp_eval_depth--;
2804 /* Do the debug-on-exit now, while arg_vector still exists. */
2805 if (backtrace_debug_on_exit (specpdl + count))
2806 tem = call_debugger (list2 (Qexit, tem));
2807 SAFE_FREE ();
2808 specpdl_ptr--;
2809 return tem;
2812 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2813 and return the result of evaluation.
2814 FUN must be either a lambda-expression or a compiled-code object. */
2816 static Lisp_Object
2817 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2818 register Lisp_Object *arg_vector)
2820 Lisp_Object val, syms_left, next, lexenv;
2821 ptrdiff_t count = SPECPDL_INDEX ();
2822 ptrdiff_t i;
2823 bool optional, rest;
2825 if (CONSP (fun))
2827 if (EQ (XCAR (fun), Qclosure))
2829 Lisp_Object cdr = XCDR (fun); /* Drop `closure'. */
2830 if (! CONSP (cdr))
2831 xsignal1 (Qinvalid_function, fun);
2832 fun = cdr;
2833 lexenv = XCAR (fun);
2835 else
2836 lexenv = Qnil;
2837 syms_left = XCDR (fun);
2838 if (CONSP (syms_left))
2839 syms_left = XCAR (syms_left);
2840 else
2841 xsignal1 (Qinvalid_function, fun);
2843 else if (COMPILEDP (fun))
2845 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2846 if (size <= COMPILED_STACK_DEPTH)
2847 xsignal1 (Qinvalid_function, fun);
2848 syms_left = AREF (fun, COMPILED_ARGLIST);
2849 if (INTEGERP (syms_left))
2850 /* A byte-code object with a non-nil `push args' slot means we
2851 shouldn't bind any arguments, instead just call the byte-code
2852 interpreter directly; it will push arguments as necessary.
2854 Byte-code objects with either a non-existent, or a nil value for
2855 the `push args' slot (the default), have dynamically-bound
2856 arguments, and use the argument-binding code below instead (as do
2857 all interpreted functions, even lexically bound ones). */
2859 /* If we have not actually read the bytecode string
2860 and constants vector yet, fetch them from the file. */
2861 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2862 Ffetch_bytecode (fun);
2863 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2864 AREF (fun, COMPILED_CONSTANTS),
2865 AREF (fun, COMPILED_STACK_DEPTH),
2866 syms_left,
2867 nargs, arg_vector);
2869 lexenv = Qnil;
2871 else
2872 emacs_abort ();
2874 i = optional = rest = 0;
2875 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2877 QUIT;
2879 next = XCAR (syms_left);
2880 if (!SYMBOLP (next))
2881 xsignal1 (Qinvalid_function, fun);
2883 if (EQ (next, Qand_rest))
2884 rest = 1;
2885 else if (EQ (next, Qand_optional))
2886 optional = 1;
2887 else
2889 Lisp_Object arg;
2890 if (rest)
2892 arg = Flist (nargs - i, &arg_vector[i]);
2893 i = nargs;
2895 else if (i < nargs)
2896 arg = arg_vector[i++];
2897 else if (!optional)
2898 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2899 else
2900 arg = Qnil;
2902 /* Bind the argument. */
2903 if (!NILP (lexenv) && SYMBOLP (next))
2904 /* Lexically bind NEXT by adding it to the lexenv alist. */
2905 lexenv = Fcons (Fcons (next, arg), lexenv);
2906 else
2907 /* Dynamically bind NEXT. */
2908 specbind (next, arg);
2912 if (!NILP (syms_left))
2913 xsignal1 (Qinvalid_function, fun);
2914 else if (i < nargs)
2915 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2917 if (!EQ (lexenv, Vinternal_interpreter_environment))
2918 /* Instantiate a new lexical environment. */
2919 specbind (Qinternal_interpreter_environment, lexenv);
2921 if (CONSP (fun))
2922 val = Fprogn (XCDR (XCDR (fun)));
2923 else
2925 /* If we have not actually read the bytecode string
2926 and constants vector yet, fetch them from the file. */
2927 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2928 Ffetch_bytecode (fun);
2929 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2930 AREF (fun, COMPILED_CONSTANTS),
2931 AREF (fun, COMPILED_STACK_DEPTH),
2932 Qnil, 0, 0);
2935 return unbind_to (count, val);
2938 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
2939 1, 1, 0,
2940 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
2941 (Lisp_Object object)
2943 Lisp_Object tem;
2945 if (COMPILEDP (object))
2947 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
2948 if (size <= COMPILED_STACK_DEPTH)
2949 xsignal1 (Qinvalid_function, object);
2950 if (CONSP (AREF (object, COMPILED_BYTECODE)))
2952 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
2953 if (!CONSP (tem))
2955 tem = AREF (object, COMPILED_BYTECODE);
2956 if (CONSP (tem) && STRINGP (XCAR (tem)))
2957 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
2958 else
2959 error ("Invalid byte code");
2961 ASET (object, COMPILED_BYTECODE, XCAR (tem));
2962 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
2965 return object;
2968 /* Return true if SYMBOL currently has a let-binding
2969 which was made in the buffer that is now current. */
2971 bool
2972 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
2974 union specbinding *p;
2975 Lisp_Object buf = Fcurrent_buffer ();
2977 for (p = specpdl_ptr; p > specpdl; )
2978 if ((--p)->kind > SPECPDL_LET)
2980 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
2981 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
2982 if (symbol == let_bound_symbol
2983 && EQ (specpdl_where (p), buf))
2984 return 1;
2987 return 0;
2990 bool
2991 let_shadows_global_binding_p (Lisp_Object symbol)
2993 union specbinding *p;
2995 for (p = specpdl_ptr; p > specpdl; )
2996 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
2997 return 1;
2999 return 0;
3002 /* `specpdl_ptr' describes which variable is
3003 let-bound, so it can be properly undone when we unbind_to.
3004 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3005 - SYMBOL is the variable being bound. Note that it should not be
3006 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3007 to record V2 here).
3008 - WHERE tells us in which buffer the binding took place.
3009 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3010 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3011 i.e. bindings to the default value of a variable which can be
3012 buffer-local. */
3014 void
3015 specbind (Lisp_Object symbol, Lisp_Object value)
3017 struct Lisp_Symbol *sym;
3019 CHECK_SYMBOL (symbol);
3020 sym = XSYMBOL (symbol);
3022 start:
3023 switch (sym->redirect)
3025 case SYMBOL_VARALIAS:
3026 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3027 case SYMBOL_PLAINVAL:
3028 /* The most common case is that of a non-constant symbol with a
3029 trivial value. Make that as fast as we can. */
3030 specpdl_ptr->let.kind = SPECPDL_LET;
3031 specpdl_ptr->let.symbol = symbol;
3032 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3033 grow_specpdl ();
3034 if (!sym->constant)
3035 SET_SYMBOL_VAL (sym, value);
3036 else
3037 set_internal (symbol, value, Qnil, 1);
3038 break;
3039 case SYMBOL_LOCALIZED:
3040 if (SYMBOL_BLV (sym)->frame_local)
3041 error ("Frame-local vars cannot be let-bound");
3042 case SYMBOL_FORWARDED:
3044 Lisp_Object ovalue = find_symbol_value (symbol);
3045 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3046 specpdl_ptr->let.symbol = symbol;
3047 specpdl_ptr->let.old_value = ovalue;
3048 specpdl_ptr->let.where = Fcurrent_buffer ();
3050 eassert (sym->redirect != SYMBOL_LOCALIZED
3051 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3053 if (sym->redirect == SYMBOL_LOCALIZED)
3055 if (!blv_found (SYMBOL_BLV (sym)))
3056 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3058 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3060 /* If SYMBOL is a per-buffer variable which doesn't have a
3061 buffer-local value here, make the `let' change the global
3062 value by changing the value of SYMBOL in all buffers not
3063 having their own value. This is consistent with what
3064 happens with other buffer-local variables. */
3065 if (NILP (Flocal_variable_p (symbol, Qnil)))
3067 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3068 grow_specpdl ();
3069 Fset_default (symbol, value);
3070 return;
3073 else
3074 specpdl_ptr->let.kind = SPECPDL_LET;
3076 grow_specpdl ();
3077 set_internal (symbol, value, Qnil, 1);
3078 break;
3080 default: emacs_abort ();
3084 /* Push unwind-protect entries of various types. */
3086 void
3087 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3089 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3090 specpdl_ptr->unwind.func = function;
3091 specpdl_ptr->unwind.arg = arg;
3092 grow_specpdl ();
3095 void
3096 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3098 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3099 specpdl_ptr->unwind_ptr.func = function;
3100 specpdl_ptr->unwind_ptr.arg = arg;
3101 grow_specpdl ();
3104 void
3105 record_unwind_protect_int (void (*function) (int), int arg)
3107 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3108 specpdl_ptr->unwind_int.func = function;
3109 specpdl_ptr->unwind_int.arg = arg;
3110 grow_specpdl ();
3113 void
3114 record_unwind_protect_void (void (*function) (void))
3116 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3117 specpdl_ptr->unwind_void.func = function;
3118 grow_specpdl ();
3121 static void
3122 do_nothing (void)
3125 /* Push an unwind-protect entry that does nothing, so that
3126 set_unwind_protect_ptr can overwrite it later. */
3128 void
3129 record_unwind_protect_nothing (void)
3131 record_unwind_protect_void (do_nothing);
3134 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3135 It need not be at the top of the stack. */
3137 void
3138 clear_unwind_protect (ptrdiff_t count)
3140 union specbinding *p = specpdl + count;
3141 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3142 p->unwind_void.func = do_nothing;
3145 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3146 It need not be at the top of the stack. Discard the entry's
3147 previous value without invoking it. */
3149 void
3150 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3151 Lisp_Object arg)
3153 union specbinding *p = specpdl + count;
3154 p->unwind.kind = SPECPDL_UNWIND;
3155 p->unwind.func = func;
3156 p->unwind.arg = arg;
3159 void
3160 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3162 union specbinding *p = specpdl + count;
3163 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3164 p->unwind_ptr.func = func;
3165 p->unwind_ptr.arg = arg;
3168 /* Pop and execute entries from the unwind-protect stack until the
3169 depth COUNT is reached. Return VALUE. */
3171 Lisp_Object
3172 unbind_to (ptrdiff_t count, Lisp_Object value)
3174 Lisp_Object quitf = Vquit_flag;
3176 Vquit_flag = Qnil;
3178 while (specpdl_ptr != specpdl + count)
3180 /* Decrement specpdl_ptr before we do the work to unbind it, so
3181 that an error in unbinding won't try to unbind the same entry
3182 again. Take care to copy any parts of the binding needed
3183 before invoking any code that can make more bindings. */
3185 specpdl_ptr--;
3187 switch (specpdl_ptr->kind)
3189 case SPECPDL_UNWIND:
3190 specpdl_ptr->unwind.func (specpdl_ptr->unwind.arg);
3191 break;
3192 case SPECPDL_UNWIND_PTR:
3193 specpdl_ptr->unwind_ptr.func (specpdl_ptr->unwind_ptr.arg);
3194 break;
3195 case SPECPDL_UNWIND_INT:
3196 specpdl_ptr->unwind_int.func (specpdl_ptr->unwind_int.arg);
3197 break;
3198 case SPECPDL_UNWIND_VOID:
3199 specpdl_ptr->unwind_void.func ();
3200 break;
3201 case SPECPDL_BACKTRACE:
3202 break;
3203 case SPECPDL_LET:
3204 { /* If variable has a trivial value (no forwarding), we can
3205 just set it. No need to check for constant symbols here,
3206 since that was already done by specbind. */
3207 Lisp_Object sym = specpdl_symbol (specpdl_ptr);
3208 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3210 SET_SYMBOL_VAL (XSYMBOL (sym),
3211 specpdl_old_value (specpdl_ptr));
3212 break;
3214 else
3215 { /* FALLTHROUGH!!
3216 NOTE: we only ever come here if make_local_foo was used for
3217 the first time on this var within this let. */
3220 case SPECPDL_LET_DEFAULT:
3221 Fset_default (specpdl_symbol (specpdl_ptr),
3222 specpdl_old_value (specpdl_ptr));
3223 break;
3224 case SPECPDL_LET_LOCAL:
3226 Lisp_Object symbol = specpdl_symbol (specpdl_ptr);
3227 Lisp_Object where = specpdl_where (specpdl_ptr);
3228 Lisp_Object old_value = specpdl_old_value (specpdl_ptr);
3229 eassert (BUFFERP (where));
3231 /* If this was a local binding, reset the value in the appropriate
3232 buffer, but only if that buffer's binding still exists. */
3233 if (!NILP (Flocal_variable_p (symbol, where)))
3234 set_internal (symbol, old_value, where, 1);
3236 break;
3240 if (NILP (Vquit_flag) && !NILP (quitf))
3241 Vquit_flag = quitf;
3243 return value;
3246 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3247 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3248 A special variable is one that will be bound dynamically, even in a
3249 context where binding is lexical by default. */)
3250 (Lisp_Object symbol)
3252 CHECK_SYMBOL (symbol);
3253 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3257 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3258 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3259 The debugger is entered when that frame exits, if the flag is non-nil. */)
3260 (Lisp_Object level, Lisp_Object flag)
3262 union specbinding *pdl = backtrace_top ();
3263 register EMACS_INT i;
3265 CHECK_NUMBER (level);
3267 for (i = 0; backtrace_p (pdl) && i < XINT (level); i++)
3268 pdl = backtrace_next (pdl);
3270 if (backtrace_p (pdl))
3271 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3273 return flag;
3276 DEFUN ("backtrace", Fbacktrace, Sbacktrace, 0, 0, "",
3277 doc: /* Print a trace of Lisp function calls currently active.
3278 Output stream used is value of `standard-output'. */)
3279 (void)
3281 union specbinding *pdl = backtrace_top ();
3282 Lisp_Object tem;
3283 Lisp_Object old_print_level = Vprint_level;
3285 if (NILP (Vprint_level))
3286 XSETFASTINT (Vprint_level, 8);
3288 while (backtrace_p (pdl))
3290 write_string (backtrace_debug_on_exit (pdl) ? "* " : " ");
3291 if (backtrace_nargs (pdl) == UNEVALLED)
3293 Fprin1 (Fcons (backtrace_function (pdl), *backtrace_args (pdl)),
3294 Qnil);
3295 write_string ("\n");
3297 else
3299 tem = backtrace_function (pdl);
3300 Fprin1 (tem, Qnil); /* This can QUIT. */
3301 write_string ("(");
3303 ptrdiff_t i;
3304 for (i = 0; i < backtrace_nargs (pdl); i++)
3306 if (i) write_string (" ");
3307 Fprin1 (backtrace_args (pdl)[i], Qnil);
3310 write_string (")\n");
3312 pdl = backtrace_next (pdl);
3315 Vprint_level = old_print_level;
3316 return Qnil;
3319 static union specbinding *
3320 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3322 union specbinding *pdl = backtrace_top ();
3323 register EMACS_INT i;
3325 CHECK_NATNUM (nframes);
3327 if (!NILP (base))
3328 { /* Skip up to `base'. */
3329 base = Findirect_function (base, Qt);
3330 while (backtrace_p (pdl)
3331 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3332 pdl = backtrace_next (pdl);
3335 /* Find the frame requested. */
3336 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3337 pdl = backtrace_next (pdl);
3339 return pdl;
3342 DEFUN ("backtrace-frame", Fbacktrace_frame, Sbacktrace_frame, 1, 2, NULL,
3343 doc: /* Return the function and arguments NFRAMES up from current execution point.
3344 If that frame has not evaluated the arguments yet (or is a special form),
3345 the value is (nil FUNCTION ARG-FORMS...).
3346 If that frame has evaluated its arguments and called its function already,
3347 the value is (t FUNCTION ARG-VALUES...).
3348 A &rest arg is represented as the tail of the list ARG-VALUES.
3349 FUNCTION is whatever was supplied as car of evaluated list,
3350 or a lambda expression for macro calls.
3351 If NFRAMES is more than the number of frames, the value is nil.
3352 If BASE is non-nil, it should be a function and NFRAMES counts from its
3353 nearest activation frame. */)
3354 (Lisp_Object nframes, Lisp_Object base)
3356 union specbinding *pdl = get_backtrace_frame (nframes, base);
3358 if (!backtrace_p (pdl))
3359 return Qnil;
3360 if (backtrace_nargs (pdl) == UNEVALLED)
3361 return Fcons (Qnil,
3362 Fcons (backtrace_function (pdl), *backtrace_args (pdl)));
3363 else
3365 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3367 return Fcons (Qt, Fcons (backtrace_function (pdl), tem));
3371 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3372 the specpdl stack, and then rewind them. We store the pre-unwind values
3373 directly in the pre-existing specpdl elements (i.e. we swap the current
3374 value and the old value stored in the specpdl), kind of like the inplace
3375 pointer-reversal trick. As it turns out, the rewind does the same as the
3376 unwind, except it starts from the other end of the specpdl stack, so we use
3377 the same function for both unwind and rewind. */
3378 static void
3379 backtrace_eval_unrewind (int distance)
3381 union specbinding *tmp = specpdl_ptr;
3382 int step = -1;
3383 if (distance < 0)
3384 { /* It's a rewind rather than unwind. */
3385 tmp += distance - 1;
3386 step = 1;
3387 distance = -distance;
3390 for (; distance > 0; distance--)
3392 tmp += step;
3393 switch (tmp->kind)
3395 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3396 unwind_protect, but the problem is that we don't know how to
3397 rewind them afterwards. */
3398 case SPECPDL_UNWIND:
3400 Lisp_Object oldarg = tmp->unwind.arg;
3401 if (tmp->unwind.func == set_buffer_if_live)
3402 tmp->unwind.arg = Fcurrent_buffer ();
3403 else if (tmp->unwind.func == save_excursion_restore)
3404 tmp->unwind.arg = save_excursion_save ();
3405 else
3406 break;
3407 tmp->unwind.func (oldarg);
3408 break;
3411 case SPECPDL_UNWIND_PTR:
3412 case SPECPDL_UNWIND_INT:
3413 case SPECPDL_UNWIND_VOID:
3414 case SPECPDL_BACKTRACE:
3415 break;
3416 case SPECPDL_LET:
3417 { /* If variable has a trivial value (no forwarding), we can
3418 just set it. No need to check for constant symbols here,
3419 since that was already done by specbind. */
3420 Lisp_Object sym = specpdl_symbol (tmp);
3421 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3423 Lisp_Object old_value = specpdl_old_value (tmp);
3424 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3425 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3426 break;
3428 else
3429 { /* FALLTHROUGH!!
3430 NOTE: we only ever come here if make_local_foo was used for
3431 the first time on this var within this let. */
3434 case SPECPDL_LET_DEFAULT:
3436 Lisp_Object sym = specpdl_symbol (tmp);
3437 Lisp_Object old_value = specpdl_old_value (tmp);
3438 set_specpdl_old_value (tmp, Fdefault_value (sym));
3439 Fset_default (sym, old_value);
3441 break;
3442 case SPECPDL_LET_LOCAL:
3444 Lisp_Object symbol = specpdl_symbol (tmp);
3445 Lisp_Object where = specpdl_where (tmp);
3446 Lisp_Object old_value = specpdl_old_value (tmp);
3447 eassert (BUFFERP (where));
3449 /* If this was a local binding, reset the value in the appropriate
3450 buffer, but only if that buffer's binding still exists. */
3451 if (!NILP (Flocal_variable_p (symbol, where)))
3453 set_specpdl_old_value
3454 (tmp, Fbuffer_local_value (symbol, where));
3455 set_internal (symbol, old_value, where, 1);
3458 break;
3463 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3464 doc: /* Evaluate EXP in the context of some activation frame.
3465 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3466 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3468 union specbinding *pdl = get_backtrace_frame (nframes, base);
3469 ptrdiff_t count = SPECPDL_INDEX ();
3470 ptrdiff_t distance = specpdl_ptr - pdl;
3471 eassert (distance >= 0);
3473 if (!backtrace_p (pdl))
3474 error ("Activation frame not found!");
3476 backtrace_eval_unrewind (distance);
3477 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3479 /* Use eval_sub rather than Feval since the main motivation behind
3480 backtrace-eval is to be able to get/set the value of lexical variables
3481 from the debugger. */
3482 return unbind_to (count, eval_sub (exp));
3485 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3486 doc: /* Return names and values of local variables of a stack frame.
3487 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3488 (Lisp_Object nframes, Lisp_Object base)
3490 union specbinding *frame = get_backtrace_frame (nframes, base);
3491 union specbinding *prevframe
3492 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3493 ptrdiff_t distance = specpdl_ptr - frame;
3494 Lisp_Object result = Qnil;
3495 eassert (distance >= 0);
3497 if (!backtrace_p (prevframe))
3498 error ("Activation frame not found!");
3499 if (!backtrace_p (frame))
3500 error ("Activation frame not found!");
3502 /* The specpdl entries normally contain the symbol being bound along with its
3503 `old_value', so it can be restored. The new value to which it is bound is
3504 available in one of two places: either in the current value of the
3505 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3506 next specpdl entry for it.
3507 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3508 and "new value", so we abuse it here, to fetch the new value.
3509 It's ugly (we'd rather not modify global data) and a bit inefficient,
3510 but it does the job for now. */
3511 backtrace_eval_unrewind (distance);
3513 /* Grab values. */
3515 union specbinding *tmp = prevframe;
3516 for (; tmp > frame; tmp--)
3518 switch (tmp->kind)
3520 case SPECPDL_LET:
3521 case SPECPDL_LET_DEFAULT:
3522 case SPECPDL_LET_LOCAL:
3524 Lisp_Object sym = specpdl_symbol (tmp);
3525 Lisp_Object val = specpdl_old_value (tmp);
3526 if (EQ (sym, Qinternal_interpreter_environment))
3528 Lisp_Object env = val;
3529 for (; CONSP (env); env = XCDR (env))
3531 Lisp_Object binding = XCAR (env);
3532 if (CONSP (binding))
3533 result = Fcons (Fcons (XCAR (binding),
3534 XCDR (binding)),
3535 result);
3538 else
3539 result = Fcons (Fcons (sym, val), result);
3541 break;
3543 case SPECPDL_UNWIND:
3544 case SPECPDL_UNWIND_PTR:
3545 case SPECPDL_UNWIND_INT:
3546 case SPECPDL_UNWIND_VOID:
3547 case SPECPDL_BACKTRACE:
3548 break;
3550 default:
3551 emacs_abort ();
3556 /* Restore values from specpdl to original place. */
3557 backtrace_eval_unrewind (-distance);
3559 return result;
3563 void
3564 mark_specpdl (void)
3566 union specbinding *pdl;
3567 for (pdl = specpdl; pdl != specpdl_ptr; pdl++)
3569 switch (pdl->kind)
3571 case SPECPDL_UNWIND:
3572 mark_object (specpdl_arg (pdl));
3573 break;
3575 case SPECPDL_BACKTRACE:
3577 ptrdiff_t nargs = backtrace_nargs (pdl);
3578 mark_object (backtrace_function (pdl));
3579 if (nargs == UNEVALLED)
3580 nargs = 1;
3581 while (nargs--)
3582 mark_object (backtrace_args (pdl)[nargs]);
3584 break;
3586 case SPECPDL_LET_DEFAULT:
3587 case SPECPDL_LET_LOCAL:
3588 mark_object (specpdl_where (pdl));
3589 /* Fall through. */
3590 case SPECPDL_LET:
3591 mark_object (specpdl_symbol (pdl));
3592 mark_object (specpdl_old_value (pdl));
3593 break;
3595 case SPECPDL_UNWIND_PTR:
3596 case SPECPDL_UNWIND_INT:
3597 case SPECPDL_UNWIND_VOID:
3598 break;
3600 default:
3601 emacs_abort ();
3606 void
3607 get_backtrace (Lisp_Object array)
3609 union specbinding *pdl = backtrace_next (backtrace_top ());
3610 ptrdiff_t i = 0, asize = ASIZE (array);
3612 /* Copy the backtrace contents into working memory. */
3613 for (; i < asize; i++)
3615 if (backtrace_p (pdl))
3617 ASET (array, i, backtrace_function (pdl));
3618 pdl = backtrace_next (pdl);
3620 else
3621 ASET (array, i, Qnil);
3625 Lisp_Object backtrace_top_function (void)
3627 union specbinding *pdl = backtrace_top ();
3628 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3631 void
3632 syms_of_eval (void)
3634 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3635 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3636 If Lisp code tries to increase the total number past this amount,
3637 an error is signaled.
3638 You can safely use a value considerably larger than the default value,
3639 if that proves inconveniently small. However, if you increase it too far,
3640 Emacs could run out of memory trying to make the stack bigger.
3641 Note that this limit may be silently increased by the debugger
3642 if `debug-on-error' or `debug-on-quit' is set. */);
3644 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3645 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3647 This limit serves to catch infinite recursions for you before they cause
3648 actual stack overflow in C, which would be fatal for Emacs.
3649 You can safely make it considerably larger than its default value,
3650 if that proves inconveniently small. However, if you increase it too far,
3651 Emacs could overflow the real C stack, and crash. */);
3653 DEFVAR_LISP ("quit-flag", Vquit_flag,
3654 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3655 If the value is t, that means do an ordinary quit.
3656 If the value equals `throw-on-input', that means quit by throwing
3657 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3658 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3659 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3660 Vquit_flag = Qnil;
3662 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3663 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3664 Note that `quit-flag' will still be set by typing C-g,
3665 so a quit will be signaled as soon as `inhibit-quit' is nil.
3666 To prevent this happening, set `quit-flag' to nil
3667 before making `inhibit-quit' nil. */);
3668 Vinhibit_quit = Qnil;
3670 DEFSYM (Qsetq, "setq");
3671 DEFSYM (Qinhibit_quit, "inhibit-quit");
3672 DEFSYM (Qautoload, "autoload");
3673 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3674 DEFSYM (Qmacro, "macro");
3676 /* Note that the process handling also uses Qexit, but we don't want
3677 to staticpro it twice, so we just do it here. */
3678 DEFSYM (Qexit, "exit");
3680 DEFSYM (Qinteractive, "interactive");
3681 DEFSYM (Qcommandp, "commandp");
3682 DEFSYM (Qand_rest, "&rest");
3683 DEFSYM (Qand_optional, "&optional");
3684 DEFSYM (Qclosure, "closure");
3685 DEFSYM (QCdocumentation, ":documentation");
3686 DEFSYM (Qdebug, "debug");
3688 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3689 doc: /* Non-nil means never enter the debugger.
3690 Normally set while the debugger is already active, to avoid recursive
3691 invocations. */);
3692 Vinhibit_debugger = Qnil;
3694 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3695 doc: /* Non-nil means enter debugger if an error is signaled.
3696 Does not apply to errors handled by `condition-case' or those
3697 matched by `debug-ignored-errors'.
3698 If the value is a list, an error only means to enter the debugger
3699 if one of its condition symbols appears in the list.
3700 When you evaluate an expression interactively, this variable
3701 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3702 The command `toggle-debug-on-error' toggles this.
3703 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3704 Vdebug_on_error = Qnil;
3706 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3707 doc: /* List of errors for which the debugger should not be called.
3708 Each element may be a condition-name or a regexp that matches error messages.
3709 If any element applies to a given error, that error skips the debugger
3710 and just returns to top level.
3711 This overrides the variable `debug-on-error'.
3712 It does not apply to errors handled by `condition-case'. */);
3713 Vdebug_ignored_errors = Qnil;
3715 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3716 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3717 Does not apply if quit is handled by a `condition-case'. */);
3718 debug_on_quit = 0;
3720 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3721 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3723 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3724 doc: /* Non-nil means debugger may continue execution.
3725 This is nil when the debugger is called under circumstances where it
3726 might not be safe to continue. */);
3727 debugger_may_continue = 1;
3729 DEFVAR_LISP ("debugger", Vdebugger,
3730 doc: /* Function to call to invoke debugger.
3731 If due to frame exit, args are `exit' and the value being returned;
3732 this function's value will be returned instead of that.
3733 If due to error, args are `error' and a list of the args to `signal'.
3734 If due to `apply' or `funcall' entry, one arg, `lambda'.
3735 If due to `eval' entry, one arg, t. */);
3736 Vdebugger = Qnil;
3738 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
3739 doc: /* If non-nil, this is a function for `signal' to call.
3740 It receives the same arguments that `signal' was given.
3741 The Edebug package uses this to regain control. */);
3742 Vsignal_hook_function = Qnil;
3744 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
3745 doc: /* Non-nil means call the debugger regardless of condition handlers.
3746 Note that `debug-on-error', `debug-on-quit' and friends
3747 still determine whether to handle the particular condition. */);
3748 Vdebug_on_signal = Qnil;
3750 /* When lexical binding is being used,
3751 Vinternal_interpreter_environment is non-nil, and contains an alist
3752 of lexically-bound variable, or (t), indicating an empty
3753 environment. The lisp name of this variable would be
3754 `internal-interpreter-environment' if it weren't hidden.
3755 Every element of this list can be either a cons (VAR . VAL)
3756 specifying a lexical binding, or a single symbol VAR indicating
3757 that this variable should use dynamic scoping. */
3758 DEFSYM (Qinternal_interpreter_environment,
3759 "internal-interpreter-environment");
3760 DEFVAR_LISP ("internal-interpreter-environment",
3761 Vinternal_interpreter_environment,
3762 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
3763 When lexical binding is not being used, this variable is nil.
3764 A value of `(t)' indicates an empty environment, otherwise it is an
3765 alist of active lexical bindings. */);
3766 Vinternal_interpreter_environment = Qnil;
3767 /* Don't export this variable to Elisp, so no one can mess with it
3768 (Just imagine if someone makes it buffer-local). */
3769 Funintern (Qinternal_interpreter_environment, Qnil);
3771 Vrun_hooks = intern_c_string ("run-hooks");
3772 staticpro (&Vrun_hooks);
3774 staticpro (&Vautoload_queue);
3775 Vautoload_queue = Qnil;
3776 staticpro (&Vsignaling_function);
3777 Vsignaling_function = Qnil;
3779 inhibit_lisp_code = Qnil;
3781 defsubr (&Sor);
3782 defsubr (&Sand);
3783 defsubr (&Sif);
3784 defsubr (&Scond);
3785 defsubr (&Sprogn);
3786 defsubr (&Sprog1);
3787 defsubr (&Sprog2);
3788 defsubr (&Ssetq);
3789 defsubr (&Squote);
3790 defsubr (&Sfunction);
3791 defsubr (&Sdefault_toplevel_value);
3792 defsubr (&Sset_default_toplevel_value);
3793 defsubr (&Sdefvar);
3794 defsubr (&Sdefvaralias);
3795 defsubr (&Sdefconst);
3796 defsubr (&Smake_var_non_special);
3797 defsubr (&Slet);
3798 defsubr (&SletX);
3799 defsubr (&Swhile);
3800 defsubr (&Smacroexpand);
3801 defsubr (&Scatch);
3802 defsubr (&Sthrow);
3803 defsubr (&Sunwind_protect);
3804 defsubr (&Scondition_case);
3805 defsubr (&Ssignal);
3806 defsubr (&Scommandp);
3807 defsubr (&Sautoload);
3808 defsubr (&Sautoload_do_load);
3809 defsubr (&Seval);
3810 defsubr (&Sapply);
3811 defsubr (&Sfuncall);
3812 defsubr (&Srun_hooks);
3813 defsubr (&Srun_hook_with_args);
3814 defsubr (&Srun_hook_with_args_until_success);
3815 defsubr (&Srun_hook_with_args_until_failure);
3816 defsubr (&Srun_hook_wrapped);
3817 defsubr (&Sfetch_bytecode);
3818 defsubr (&Sbacktrace_debug);
3819 defsubr (&Sbacktrace);
3820 defsubr (&Sbacktrace_frame);
3821 defsubr (&Sbacktrace_eval);
3822 defsubr (&Sbacktrace__locals);
3823 defsubr (&Sspecial_variable_p);
3824 defsubr (&Sfunctionp);