Subject: Restore correct Gnus newsgroup name after sending message
[emacs.git] / src / eval.c
blob62d4af15e271045ad30352d4ef746007e3f69126
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 <stdlib.h>
26 #include "lisp.h"
27 #include "blockinput.h"
28 #include "commands.h"
29 #include "keyboard.h"
30 #include "dispextern.h"
31 #include "buffer.h"
33 /* Chain of condition and catch handlers currently in effect. */
35 /* struct handler *handlerlist; */
37 /* Non-nil means record all fset's and provide's, to be undone
38 if the file being autoloaded is not fully loaded.
39 They are recorded by being consed onto the front of Vautoload_queue:
40 (FUN . ODEF) for a defun, (0 . OFEATURES) for a provide. */
42 Lisp_Object Vautoload_queue;
44 /* This holds either the symbol `run-hooks' or nil.
45 It is nil at an early stage of startup, and when Emacs
46 is shutting down. */
47 Lisp_Object Vrun_hooks;
49 /* The commented-out variables below are macros defined in thread.h. */
51 /* Current number of specbindings allocated in specpdl, not counting
52 the dummy entry specpdl[-1]. */
54 /* ptrdiff_t specpdl_size; */
56 /* Pointer to beginning of specpdl. A dummy entry specpdl[-1] exists
57 only so that its address can be taken. */
59 /* union specbinding *specpdl; */
61 /* Pointer to first unused element in specpdl. */
63 /* union specbinding *specpdl_ptr; */
65 /* Depth in Lisp evaluations and function calls. */
67 /* static EMACS_INT lisp_eval_depth; */
69 /* The value of num_nonmacro_input_events as of the last time we
70 started to enter the debugger. If we decide to enter the debugger
71 again when this is still equal to num_nonmacro_input_events, then we
72 know that the debugger itself has an error, and we should just
73 signal the error instead of entering an infinite loop of debugger
74 invocations. */
76 static EMACS_INT when_entered_debugger;
78 /* The function from which the last `signal' was called. Set in
79 Fsignal. */
80 /* FIXME: We should probably get rid of this! */
81 Lisp_Object Vsignaling_function;
83 /* If non-nil, Lisp code must not be run since some part of Emacs is in
84 an inconsistent state. Currently unused. */
85 Lisp_Object inhibit_lisp_code;
87 /* These would ordinarily be static, but they need to be visible to GDB. */
88 bool backtrace_p (union specbinding *) EXTERNALLY_VISIBLE;
89 Lisp_Object *backtrace_args (union specbinding *) EXTERNALLY_VISIBLE;
90 Lisp_Object backtrace_function (union specbinding *) EXTERNALLY_VISIBLE;
91 union specbinding *backtrace_next (union specbinding *) EXTERNALLY_VISIBLE;
92 union specbinding *backtrace_top (void) EXTERNALLY_VISIBLE;
94 static Lisp_Object funcall_lambda (Lisp_Object, ptrdiff_t, Lisp_Object *);
95 static Lisp_Object apply_lambda (Lisp_Object, Lisp_Object, ptrdiff_t);
96 static Lisp_Object lambda_arity (Lisp_Object);
98 static Lisp_Object
99 specpdl_symbol (union specbinding *pdl)
101 eassert (pdl->kind >= SPECPDL_LET);
102 return pdl->let.symbol;
105 static enum specbind_tag
106 specpdl_kind (union specbinding *pdl)
108 eassert (pdl->kind >= SPECPDL_LET);
109 return pdl->let.kind;
112 static Lisp_Object
113 specpdl_old_value (union specbinding *pdl)
115 eassert (pdl->kind >= SPECPDL_LET);
116 return pdl->let.old_value;
119 static void
120 set_specpdl_old_value (union specbinding *pdl, Lisp_Object val)
122 eassert (pdl->kind >= SPECPDL_LET);
123 pdl->let.old_value = val;
126 static Lisp_Object
127 specpdl_where (union specbinding *pdl)
129 eassert (pdl->kind > SPECPDL_LET);
130 return pdl->let.where;
133 static Lisp_Object
134 specpdl_saved_value (union specbinding *pdl)
136 eassert (pdl->kind >= SPECPDL_LET);
137 return pdl->let.saved_value;
140 static Lisp_Object
141 specpdl_arg (union specbinding *pdl)
143 eassert (pdl->kind == SPECPDL_UNWIND);
144 return pdl->unwind.arg;
147 Lisp_Object
148 backtrace_function (union specbinding *pdl)
150 eassert (pdl->kind == SPECPDL_BACKTRACE);
151 return pdl->bt.function;
154 static ptrdiff_t
155 backtrace_nargs (union specbinding *pdl)
157 eassert (pdl->kind == SPECPDL_BACKTRACE);
158 return pdl->bt.nargs;
161 Lisp_Object *
162 backtrace_args (union specbinding *pdl)
164 eassert (pdl->kind == SPECPDL_BACKTRACE);
165 return pdl->bt.args;
168 static bool
169 backtrace_debug_on_exit (union specbinding *pdl)
171 eassert (pdl->kind == SPECPDL_BACKTRACE);
172 return pdl->bt.debug_on_exit;
175 /* Functions to modify slots of backtrace records. */
177 static void
178 set_backtrace_args (union specbinding *pdl, Lisp_Object *args, ptrdiff_t nargs)
180 eassert (pdl->kind == SPECPDL_BACKTRACE);
181 pdl->bt.args = args;
182 pdl->bt.nargs = nargs;
185 static void
186 set_backtrace_debug_on_exit (union specbinding *pdl, bool doe)
188 eassert (pdl->kind == SPECPDL_BACKTRACE);
189 pdl->bt.debug_on_exit = doe;
192 /* Helper functions to scan the backtrace. */
194 bool
195 backtrace_p (union specbinding *pdl)
196 { return pdl >= specpdl; }
198 union specbinding *
199 backtrace_top (void)
201 union specbinding *pdl = specpdl_ptr - 1;
202 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
203 pdl--;
204 return pdl;
207 union specbinding *
208 backtrace_next (union specbinding *pdl)
210 pdl--;
211 while (backtrace_p (pdl) && pdl->kind != SPECPDL_BACKTRACE)
212 pdl--;
213 return pdl;
216 /* Return a pointer to somewhere near the top of the C stack. */
217 void *
218 near_C_stack_top (void)
220 return backtrace_args (backtrace_top ());
223 void
224 init_eval_once (void)
226 enum { size = 50 };
227 union specbinding *pdlvec = xmalloc ((size + 1) * sizeof *specpdl);
228 specpdl_size = size;
229 specpdl = specpdl_ptr = pdlvec + 1;
230 /* Don't forget to update docs (lispref node "Local Variables"). */
231 max_specpdl_size = 1300; /* 1000 is not enough for CEDET's c-by.el. */
232 max_lisp_eval_depth = 800;
234 Vrun_hooks = Qnil;
237 /* static struct handler handlerlist_sentinel; */
239 void
240 init_eval (void)
242 specpdl_ptr = specpdl;
243 { /* Put a dummy catcher at top-level so that handlerlist is never NULL.
244 This is important since handlerlist->nextfree holds the freelist
245 which would otherwise leak every time we unwind back to top-level. */
246 handlerlist_sentinel = xzalloc (sizeof (struct handler));
247 handlerlist = handlerlist_sentinel->nextfree = handlerlist_sentinel;
248 struct handler *c = push_handler (Qunbound, CATCHER);
249 eassert (c == handlerlist_sentinel);
250 handlerlist_sentinel->nextfree = NULL;
251 handlerlist_sentinel->next = NULL;
253 Vquit_flag = Qnil;
254 debug_on_next_call = 0;
255 lisp_eval_depth = 0;
256 /* This is less than the initial value of num_nonmacro_input_events. */
257 when_entered_debugger = -1;
260 /* Unwind-protect function used by call_debugger. */
262 static void
263 restore_stack_limits (Lisp_Object data)
265 max_specpdl_size = XINT (XCAR (data));
266 max_lisp_eval_depth = XINT (XCDR (data));
269 static void grow_specpdl (void);
271 /* Call the Lisp debugger, giving it argument ARG. */
273 Lisp_Object
274 call_debugger (Lisp_Object arg)
276 bool debug_while_redisplaying;
277 ptrdiff_t count = SPECPDL_INDEX ();
278 Lisp_Object val;
279 EMACS_INT old_depth = max_lisp_eval_depth;
280 /* Do not allow max_specpdl_size less than actual depth (Bug#16603). */
281 EMACS_INT old_max = max (max_specpdl_size, count);
283 if (lisp_eval_depth + 40 > max_lisp_eval_depth)
284 max_lisp_eval_depth = lisp_eval_depth + 40;
286 /* While debugging Bug#16603, previous value of 100 was found
287 too small to avoid specpdl overflow in the debugger itself. */
288 if (max_specpdl_size - 200 < count)
289 max_specpdl_size = count + 200;
291 if (old_max == count)
293 /* We can enter the debugger due to specpdl overflow (Bug#16603). */
294 specpdl_ptr--;
295 grow_specpdl ();
298 /* Restore limits after leaving the debugger. */
299 record_unwind_protect (restore_stack_limits,
300 Fcons (make_number (old_max),
301 make_number (old_depth)));
303 #ifdef HAVE_WINDOW_SYSTEM
304 if (display_hourglass_p)
305 cancel_hourglass ();
306 #endif
308 debug_on_next_call = 0;
309 when_entered_debugger = num_nonmacro_input_events;
311 /* Resetting redisplaying_p to 0 makes sure that debug output is
312 displayed if the debugger is invoked during redisplay. */
313 debug_while_redisplaying = redisplaying_p;
314 redisplaying_p = 0;
315 specbind (intern ("debugger-may-continue"),
316 debug_while_redisplaying ? Qnil : Qt);
317 specbind (Qinhibit_redisplay, Qnil);
318 specbind (Qinhibit_debugger, Qt);
320 /* If we are debugging an error while `inhibit-changing-match-data'
321 is bound to non-nil (e.g., within a call to `string-match-p'),
322 then make sure debugger code can still use match data. */
323 specbind (Qinhibit_changing_match_data, Qnil);
325 #if 0 /* Binding this prevents execution of Lisp code during
326 redisplay, which necessarily leads to display problems. */
327 specbind (Qinhibit_eval_during_redisplay, Qt);
328 #endif
330 val = apply1 (Vdebugger, arg);
332 /* Interrupting redisplay and resuming it later is not safe under
333 all circumstances. So, when the debugger returns, abort the
334 interrupted redisplay by going back to the top-level. */
335 if (debug_while_redisplaying)
336 Ftop_level ();
338 return unbind_to (count, val);
341 static void
342 do_debug_on_call (Lisp_Object code, ptrdiff_t count)
344 debug_on_next_call = 0;
345 set_backtrace_debug_on_exit (specpdl + count, true);
346 call_debugger (list1 (code));
349 /* NOTE!!! Every function that can call EVAL must protect its args
350 and temporaries from garbage collection while it needs them.
351 The definition of `For' shows what you have to do. */
353 DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
354 doc: /* Eval args until one of them yields non-nil, then return that value.
355 The remaining args are not evalled at all.
356 If all args return nil, return nil.
357 usage: (or CONDITIONS...) */)
358 (Lisp_Object args)
360 Lisp_Object val = Qnil;
362 while (CONSP (args))
364 val = eval_sub (XCAR (args));
365 if (!NILP (val))
366 break;
367 args = XCDR (args);
370 return val;
373 DEFUN ("and", Fand, Sand, 0, UNEVALLED, 0,
374 doc: /* Eval args until one of them yields nil, then return nil.
375 The remaining args are not evalled at all.
376 If no arg yields nil, return the last arg's value.
377 usage: (and CONDITIONS...) */)
378 (Lisp_Object args)
380 Lisp_Object val = Qt;
382 while (CONSP (args))
384 val = eval_sub (XCAR (args));
385 if (NILP (val))
386 break;
387 args = XCDR (args);
390 return val;
393 DEFUN ("if", Fif, Sif, 2, UNEVALLED, 0,
394 doc: /* If COND yields non-nil, do THEN, else do ELSE...
395 Returns the value of THEN or the value of the last of the ELSE's.
396 THEN must be one expression, but ELSE... can be zero or more expressions.
397 If COND yields nil, and there are no ELSE's, the value is nil.
398 usage: (if COND THEN ELSE...) */)
399 (Lisp_Object args)
401 Lisp_Object cond;
403 cond = eval_sub (XCAR (args));
405 if (!NILP (cond))
406 return eval_sub (Fcar (XCDR (args)));
407 return Fprogn (XCDR (XCDR (args)));
410 DEFUN ("cond", Fcond, Scond, 0, UNEVALLED, 0,
411 doc: /* Try each clause until one succeeds.
412 Each clause looks like (CONDITION BODY...). CONDITION is evaluated
413 and, if the value is non-nil, this clause succeeds:
414 then the expressions in BODY are evaluated and the last one's
415 value is the value of the cond-form.
416 If a clause has one element, as in (CONDITION), then the cond-form
417 returns CONDITION's value, if that is non-nil.
418 If no clause succeeds, cond returns nil.
419 usage: (cond CLAUSES...) */)
420 (Lisp_Object args)
422 Lisp_Object val = args;
424 while (CONSP (args))
426 Lisp_Object clause = XCAR (args);
427 val = eval_sub (Fcar (clause));
428 if (!NILP (val))
430 if (!NILP (XCDR (clause)))
431 val = Fprogn (XCDR (clause));
432 break;
434 args = XCDR (args);
437 return val;
440 DEFUN ("progn", Fprogn, Sprogn, 0, UNEVALLED, 0,
441 doc: /* Eval BODY forms sequentially and return value of last one.
442 usage: (progn BODY...) */)
443 (Lisp_Object body)
445 Lisp_Object val = Qnil;
447 while (CONSP (body))
449 val = eval_sub (XCAR (body));
450 body = XCDR (body);
453 return val;
456 /* Evaluate BODY sequentially, discarding its value. */
458 void
459 prog_ignore (Lisp_Object body)
461 Fprogn (body);
464 DEFUN ("prog1", Fprog1, Sprog1, 1, UNEVALLED, 0,
465 doc: /* Eval FIRST and BODY sequentially; return value from FIRST.
466 The value of FIRST is saved during the evaluation of the remaining args,
467 whose values are discarded.
468 usage: (prog1 FIRST BODY...) */)
469 (Lisp_Object args)
471 Lisp_Object val = eval_sub (XCAR (args));
472 prog_ignore (XCDR (args));
473 return val;
476 DEFUN ("prog2", Fprog2, Sprog2, 2, UNEVALLED, 0,
477 doc: /* Eval FORM1, FORM2 and BODY sequentially; return value from FORM2.
478 The value of FORM2 is saved during the evaluation of the
479 remaining args, whose values are discarded.
480 usage: (prog2 FORM1 FORM2 BODY...) */)
481 (Lisp_Object args)
483 eval_sub (XCAR (args));
484 return Fprog1 (XCDR (args));
487 DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0,
488 doc: /* Set each SYM to the value of its VAL.
489 The symbols SYM are variables; they are literal (not evaluated).
490 The values VAL are expressions; they are evaluated.
491 Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'.
492 The second VAL is not computed until after the first SYM is set, and so on;
493 each VAL can use the new value of variables set earlier in the `setq'.
494 The return value of the `setq' form is the value of the last VAL.
495 usage: (setq [SYM VAL]...) */)
496 (Lisp_Object args)
498 Lisp_Object val, sym, lex_binding;
500 val = args;
501 if (CONSP (args))
503 Lisp_Object args_left = args;
504 Lisp_Object numargs = Flength (args);
506 if (XINT (numargs) & 1)
507 xsignal2 (Qwrong_number_of_arguments, Qsetq, numargs);
511 val = eval_sub (Fcar (XCDR (args_left)));
512 sym = XCAR (args_left);
514 /* Like for eval_sub, we do not check declared_special here since
515 it's been done when let-binding. */
516 if (!NILP (Vinternal_interpreter_environment) /* Mere optimization! */
517 && SYMBOLP (sym)
518 && !NILP (lex_binding
519 = Fassq (sym, Vinternal_interpreter_environment)))
520 XSETCDR (lex_binding, val); /* SYM is lexically bound. */
521 else
522 Fset (sym, val); /* SYM is dynamically bound. */
524 args_left = Fcdr (XCDR (args_left));
526 while (CONSP (args_left));
529 return val;
532 DEFUN ("quote", Fquote, Squote, 1, UNEVALLED, 0,
533 doc: /* Return the argument, without evaluating it. `(quote x)' yields `x'.
534 Warning: `quote' does not construct its return value, but just returns
535 the value that was pre-constructed by the Lisp reader (see info node
536 `(elisp)Printed Representation').
537 This means that \\='(a . b) is not identical to (cons \\='a \\='b): the former
538 does not cons. Quoting should be reserved for constants that will
539 never be modified by side-effects, unless you like self-modifying code.
540 See the common pitfall in info node `(elisp)Rearrangement' for an example
541 of unexpected results when a quoted object is modified.
542 usage: (quote ARG) */)
543 (Lisp_Object args)
545 if (CONSP (XCDR (args)))
546 xsignal2 (Qwrong_number_of_arguments, Qquote, Flength (args));
547 return XCAR (args);
550 DEFUN ("function", Ffunction, Sfunction, 1, UNEVALLED, 0,
551 doc: /* Like `quote', but preferred for objects which are functions.
552 In byte compilation, `function' causes its argument to be compiled.
553 `quote' cannot do that.
554 usage: (function ARG) */)
555 (Lisp_Object args)
557 Lisp_Object quoted = XCAR (args);
559 if (CONSP (XCDR (args)))
560 xsignal2 (Qwrong_number_of_arguments, Qfunction, Flength (args));
562 if (!NILP (Vinternal_interpreter_environment)
563 && CONSP (quoted)
564 && EQ (XCAR (quoted), Qlambda))
565 { /* This is a lambda expression within a lexical environment;
566 return an interpreted closure instead of a simple lambda. */
567 Lisp_Object cdr = XCDR (quoted);
568 Lisp_Object tmp = cdr;
569 if (CONSP (tmp)
570 && (tmp = XCDR (tmp), CONSP (tmp))
571 && (tmp = XCAR (tmp), CONSP (tmp))
572 && (EQ (QCdocumentation, XCAR (tmp))))
573 { /* Handle the special (:documentation <form>) to build the docstring
574 dynamically. */
575 Lisp_Object docstring = eval_sub (Fcar (XCDR (tmp)));
576 CHECK_STRING (docstring);
577 cdr = Fcons (XCAR (cdr), Fcons (docstring, XCDR (XCDR (cdr))));
579 return Fcons (Qclosure, Fcons (Vinternal_interpreter_environment,
580 cdr));
582 else
583 /* Simply quote the argument. */
584 return quoted;
588 DEFUN ("defvaralias", Fdefvaralias, Sdefvaralias, 2, 3, 0,
589 doc: /* Make NEW-ALIAS a variable alias for symbol BASE-VARIABLE.
590 Aliased variables always have the same value; setting one sets the other.
591 Third arg DOCSTRING, if non-nil, is documentation for NEW-ALIAS. If it is
592 omitted or nil, NEW-ALIAS gets the documentation string of BASE-VARIABLE,
593 or of the variable at the end of the chain of aliases, if BASE-VARIABLE is
594 itself an alias. If NEW-ALIAS is bound, and BASE-VARIABLE is not,
595 then the value of BASE-VARIABLE is set to that of NEW-ALIAS.
596 The return value is BASE-VARIABLE. */)
597 (Lisp_Object new_alias, Lisp_Object base_variable, Lisp_Object docstring)
599 struct Lisp_Symbol *sym;
601 CHECK_SYMBOL (new_alias);
602 CHECK_SYMBOL (base_variable);
604 if (SYMBOL_CONSTANT_P (new_alias))
605 /* Making it an alias effectively changes its value. */
606 error ("Cannot make a constant an alias");
608 sym = XSYMBOL (new_alias);
610 switch (sym->redirect)
612 case SYMBOL_FORWARDED:
613 error ("Cannot make an internal variable an alias");
614 case SYMBOL_LOCALIZED:
615 error ("Don't know how to make a localized variable an alias");
616 case SYMBOL_PLAINVAL:
617 case SYMBOL_VARALIAS:
618 break;
619 default:
620 emacs_abort ();
623 /* http://lists.gnu.org/archive/html/emacs-devel/2008-04/msg00834.html
624 If n_a is bound, but b_v is not, set the value of b_v to n_a,
625 so that old-code that affects n_a before the aliasing is setup
626 still works. */
627 if (NILP (Fboundp (base_variable)))
628 set_internal (base_variable, find_symbol_value (new_alias),
629 Qnil, SET_INTERNAL_BIND);
631 union specbinding *p;
633 for (p = specpdl_ptr; p > specpdl; )
634 if ((--p)->kind >= SPECPDL_LET
635 && (EQ (new_alias, specpdl_symbol (p))))
636 error ("Don't know how to make a let-bound variable an alias");
639 if (sym->trapped_write == SYMBOL_TRAPPED_WRITE)
640 notify_variable_watchers (new_alias, base_variable, Qdefvaralias, Qnil);
642 sym->declared_special = 1;
643 XSYMBOL (base_variable)->declared_special = 1;
644 sym->redirect = SYMBOL_VARALIAS;
645 SET_SYMBOL_ALIAS (sym, XSYMBOL (base_variable));
646 sym->trapped_write = XSYMBOL (base_variable)->trapped_write;
647 LOADHIST_ATTACH (new_alias);
648 /* Even if docstring is nil: remove old docstring. */
649 Fput (new_alias, Qvariable_documentation, docstring);
651 return base_variable;
654 static union specbinding *
655 default_toplevel_binding (Lisp_Object symbol)
657 union specbinding *binding = NULL;
658 union specbinding *pdl = specpdl_ptr;
659 while (pdl > specpdl)
661 switch ((--pdl)->kind)
663 case SPECPDL_LET_DEFAULT:
664 case SPECPDL_LET:
665 if (EQ (specpdl_symbol (pdl), symbol))
666 binding = pdl;
667 break;
669 case SPECPDL_UNWIND:
670 case SPECPDL_UNWIND_PTR:
671 case SPECPDL_UNWIND_INT:
672 case SPECPDL_UNWIND_VOID:
673 case SPECPDL_BACKTRACE:
674 case SPECPDL_LET_LOCAL:
675 break;
677 default:
678 emacs_abort ();
681 return binding;
684 DEFUN ("default-toplevel-value", Fdefault_toplevel_value, Sdefault_toplevel_value, 1, 1, 0,
685 doc: /* Return SYMBOL's toplevel default value.
686 "Toplevel" means outside of any let binding. */)
687 (Lisp_Object symbol)
689 union specbinding *binding = default_toplevel_binding (symbol);
690 Lisp_Object value
691 = binding ? specpdl_old_value (binding) : Fdefault_value (symbol);
692 if (!EQ (value, Qunbound))
693 return value;
694 xsignal1 (Qvoid_variable, symbol);
697 DEFUN ("set-default-toplevel-value", Fset_default_toplevel_value,
698 Sset_default_toplevel_value, 2, 2, 0,
699 doc: /* Set SYMBOL's toplevel default value to VALUE.
700 "Toplevel" means outside of any let binding. */)
701 (Lisp_Object symbol, Lisp_Object value)
703 union specbinding *binding = default_toplevel_binding (symbol);
704 if (binding)
705 set_specpdl_old_value (binding, value);
706 else
707 Fset_default (symbol, value);
708 return Qnil;
711 DEFUN ("defvar", Fdefvar, Sdefvar, 1, UNEVALLED, 0,
712 doc: /* Define SYMBOL as a variable, and return SYMBOL.
713 You are not required to define a variable in order to use it, but
714 defining it lets you supply an initial value and documentation, which
715 can be referred to by the Emacs help facilities and other programming
716 tools. The `defvar' form also declares the variable as \"special\",
717 so that it is always dynamically bound even if `lexical-binding' is t.
719 If SYMBOL's value is void and the optional argument INITVALUE is
720 provided, INITVALUE is evaluated and the result used to set SYMBOL's
721 value. If SYMBOL is buffer-local, its default value is what is set;
722 buffer-local values are not affected. If INITVALUE is missing,
723 SYMBOL's value is not set.
725 If SYMBOL has a local binding, then this form affects the local
726 binding. This is usually not what you want. Thus, if you need to
727 load a file defining variables, with this form or with `defconst' or
728 `defcustom', you should always load that file _outside_ any bindings
729 for these variables. (`defconst' and `defcustom' behave similarly in
730 this respect.)
732 The optional argument DOCSTRING is a documentation string for the
733 variable.
735 To define a user option, use `defcustom' instead of `defvar'.
736 usage: (defvar SYMBOL &optional INITVALUE DOCSTRING) */)
737 (Lisp_Object args)
739 Lisp_Object sym, tem, tail;
741 sym = XCAR (args);
742 tail = XCDR (args);
744 if (CONSP (tail))
746 if (CONSP (XCDR (tail)) && CONSP (XCDR (XCDR (tail))))
747 error ("Too many arguments");
749 tem = Fdefault_boundp (sym);
751 /* Do it before evaluating the initial value, for self-references. */
752 XSYMBOL (sym)->declared_special = 1;
754 if (NILP (tem))
755 Fset_default (sym, eval_sub (XCAR (tail)));
756 else
757 { /* Check if there is really a global binding rather than just a let
758 binding that shadows the global unboundness of the var. */
759 union specbinding *binding = default_toplevel_binding (sym);
760 if (binding && EQ (specpdl_old_value (binding), Qunbound))
762 set_specpdl_old_value (binding, eval_sub (XCAR (tail)));
765 tail = XCDR (tail);
766 tem = Fcar (tail);
767 if (!NILP (tem))
769 if (!NILP (Vpurify_flag))
770 tem = Fpurecopy (tem);
771 Fput (sym, Qvariable_documentation, tem);
773 LOADHIST_ATTACH (sym);
775 else if (!NILP (Vinternal_interpreter_environment)
776 && !XSYMBOL (sym)->declared_special)
777 /* A simple (defvar foo) with lexical scoping does "nothing" except
778 declare that var to be dynamically scoped *locally* (i.e. within
779 the current file or let-block). */
780 Vinternal_interpreter_environment
781 = Fcons (sym, Vinternal_interpreter_environment);
782 else
784 /* Simple (defvar <var>) should not count as a definition at all.
785 It could get in the way of other definitions, and unloading this
786 package could try to make the variable unbound. */
789 return sym;
792 DEFUN ("defconst", Fdefconst, Sdefconst, 2, UNEVALLED, 0,
793 doc: /* Define SYMBOL as a constant variable.
794 This declares that neither programs nor users should ever change the
795 value. This constancy is not actually enforced by Emacs Lisp, but
796 SYMBOL is marked as a special variable so that it is never lexically
797 bound.
799 The `defconst' form always sets the value of SYMBOL to the result of
800 evalling INITVALUE. If SYMBOL is buffer-local, its default value is
801 what is set; buffer-local values are not affected. If SYMBOL has a
802 local binding, then this form sets the local binding's value.
803 However, you should normally not make local bindings for variables
804 defined with this form.
806 The optional DOCSTRING specifies the variable's documentation string.
807 usage: (defconst SYMBOL INITVALUE [DOCSTRING]) */)
808 (Lisp_Object args)
810 Lisp_Object sym, tem;
812 sym = XCAR (args);
813 if (CONSP (Fcdr (XCDR (XCDR (args)))))
814 error ("Too many arguments");
816 tem = eval_sub (Fcar (XCDR (args)));
817 if (!NILP (Vpurify_flag))
818 tem = Fpurecopy (tem);
819 Fset_default (sym, tem);
820 XSYMBOL (sym)->declared_special = 1;
821 tem = Fcar (XCDR (XCDR (args)));
822 if (!NILP (tem))
824 if (!NILP (Vpurify_flag))
825 tem = Fpurecopy (tem);
826 Fput (sym, Qvariable_documentation, tem);
828 Fput (sym, Qrisky_local_variable, Qt);
829 LOADHIST_ATTACH (sym);
830 return sym;
833 /* Make SYMBOL lexically scoped. */
834 DEFUN ("internal-make-var-non-special", Fmake_var_non_special,
835 Smake_var_non_special, 1, 1, 0,
836 doc: /* Internal function. */)
837 (Lisp_Object symbol)
839 CHECK_SYMBOL (symbol);
840 XSYMBOL (symbol)->declared_special = 0;
841 return Qnil;
845 DEFUN ("let*", FletX, SletX, 1, UNEVALLED, 0,
846 doc: /* Bind variables according to VARLIST then eval BODY.
847 The value of the last form in BODY is returned.
848 Each element of VARLIST is a symbol (which is bound to nil)
849 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
850 Each VALUEFORM can refer to the symbols already bound by this VARLIST.
851 usage: (let* VARLIST BODY...) */)
852 (Lisp_Object args)
854 Lisp_Object varlist, var, val, elt, lexenv;
855 ptrdiff_t count = SPECPDL_INDEX ();
857 lexenv = Vinternal_interpreter_environment;
859 for (varlist = XCAR (args); CONSP (varlist); varlist = XCDR (varlist))
861 maybe_quit ();
863 elt = XCAR (varlist);
864 if (SYMBOLP (elt))
866 var = elt;
867 val = Qnil;
869 else if (! NILP (Fcdr (Fcdr (elt))))
870 signal_error ("`let' bindings can have only one value-form", elt);
871 else
873 var = Fcar (elt);
874 val = eval_sub (Fcar (Fcdr (elt)));
877 if (!NILP (lexenv) && SYMBOLP (var)
878 && !XSYMBOL (var)->declared_special
879 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
880 /* Lexically bind VAR by adding it to the interpreter's binding
881 alist. */
883 Lisp_Object newenv
884 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
885 if (EQ (Vinternal_interpreter_environment, lexenv))
886 /* Save the old lexical environment on the specpdl stack,
887 but only for the first lexical binding, since we'll never
888 need to revert to one of the intermediate ones. */
889 specbind (Qinternal_interpreter_environment, newenv);
890 else
891 Vinternal_interpreter_environment = newenv;
893 else
894 specbind (var, val);
896 CHECK_LIST_END (varlist, XCAR (args));
898 val = Fprogn (XCDR (args));
899 return unbind_to (count, val);
902 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
903 doc: /* Bind variables according to VARLIST then eval BODY.
904 The value of the last form in BODY is returned.
905 Each element of VARLIST is a symbol (which is bound to nil)
906 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
907 All the VALUEFORMs are evalled before any symbols are bound.
908 usage: (let VARLIST BODY...) */)
909 (Lisp_Object args)
911 Lisp_Object *temps, tem, lexenv;
912 Lisp_Object elt, varlist;
913 ptrdiff_t count = SPECPDL_INDEX ();
914 ptrdiff_t argnum;
915 USE_SAFE_ALLOCA;
917 varlist = XCAR (args);
918 CHECK_LIST (varlist);
920 /* Make space to hold the values to give the bound variables. */
921 elt = Flength (varlist);
922 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
924 /* Compute the values and store them in `temps'. */
926 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
928 maybe_quit ();
929 elt = XCAR (varlist);
930 if (SYMBOLP (elt))
931 temps [argnum++] = Qnil;
932 else if (! NILP (Fcdr (Fcdr (elt))))
933 signal_error ("`let' bindings can have only one value-form", elt);
934 else
935 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
938 lexenv = Vinternal_interpreter_environment;
940 varlist = XCAR (args);
941 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
943 Lisp_Object var;
945 elt = XCAR (varlist);
946 var = SYMBOLP (elt) ? elt : Fcar (elt);
947 tem = temps[argnum++];
949 if (!NILP (lexenv) && SYMBOLP (var)
950 && !XSYMBOL (var)->declared_special
951 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
952 /* Lexically bind VAR by adding it to the lexenv alist. */
953 lexenv = Fcons (Fcons (var, tem), lexenv);
954 else
955 /* Dynamically bind VAR. */
956 specbind (var, tem);
959 if (!EQ (lexenv, Vinternal_interpreter_environment))
960 /* Instantiate a new lexical environment. */
961 specbind (Qinternal_interpreter_environment, lexenv);
963 elt = Fprogn (XCDR (args));
964 SAFE_FREE ();
965 return unbind_to (count, elt);
968 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
969 doc: /* If TEST yields non-nil, eval BODY... and repeat.
970 The order of execution is thus TEST, BODY, TEST, BODY and so on
971 until TEST returns nil.
972 usage: (while TEST BODY...) */)
973 (Lisp_Object args)
975 Lisp_Object test, body;
977 test = XCAR (args);
978 body = XCDR (args);
979 while (!NILP (eval_sub (test)))
981 maybe_quit ();
982 prog_ignore (body);
985 return Qnil;
988 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
989 doc: /* Return result of expanding macros at top level of FORM.
990 If FORM is not a macro call, it is returned unchanged.
991 Otherwise, the macro is expanded and the expansion is considered
992 in place of FORM. When a non-macro-call results, it is returned.
994 The second optional arg ENVIRONMENT specifies an environment of macro
995 definitions to shadow the loaded ones for use in file byte-compilation. */)
996 (Lisp_Object form, Lisp_Object environment)
998 /* With cleanups from Hallvard Furuseth. */
999 register Lisp_Object expander, sym, def, tem;
1001 while (1)
1003 /* Come back here each time we expand a macro call,
1004 in case it expands into another macro call. */
1005 if (!CONSP (form))
1006 break;
1007 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1008 def = sym = XCAR (form);
1009 tem = Qnil;
1010 /* Trace symbols aliases to other symbols
1011 until we get a symbol that is not an alias. */
1012 while (SYMBOLP (def))
1014 maybe_quit ();
1015 sym = def;
1016 tem = Fassq (sym, environment);
1017 if (NILP (tem))
1019 def = XSYMBOL (sym)->function;
1020 if (!NILP (def))
1021 continue;
1023 break;
1025 /* Right now TEM is the result from SYM in ENVIRONMENT,
1026 and if TEM is nil then DEF is SYM's function definition. */
1027 if (NILP (tem))
1029 /* SYM is not mentioned in ENVIRONMENT.
1030 Look at its function definition. */
1031 def = Fautoload_do_load (def, sym, Qmacro);
1032 if (!CONSP (def))
1033 /* Not defined or definition not suitable. */
1034 break;
1035 if (!EQ (XCAR (def), Qmacro))
1036 break;
1037 else expander = XCDR (def);
1039 else
1041 expander = XCDR (tem);
1042 if (NILP (expander))
1043 break;
1046 Lisp_Object newform = apply1 (expander, XCDR (form));
1047 if (EQ (form, newform))
1048 break;
1049 else
1050 form = newform;
1053 return form;
1056 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1057 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1058 TAG is evalled to get the tag to use; it must not be nil.
1060 Then the BODY is executed.
1061 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1062 If no throw happens, `catch' returns the value of the last BODY form.
1063 If a throw happens, it specifies the value to return from `catch'.
1064 usage: (catch TAG BODY...) */)
1065 (Lisp_Object args)
1067 Lisp_Object tag = eval_sub (XCAR (args));
1068 return internal_catch (tag, Fprogn, XCDR (args));
1071 /* Assert that E is true, but do not evaluate E. Use this instead of
1072 eassert (E) when E contains variables that might be clobbered by a
1073 longjmp. */
1075 #define clobbered_eassert(E) verify (sizeof (E) != 0)
1077 /* Set up a catch, then call C function FUNC on argument ARG.
1078 FUNC should return a Lisp_Object.
1079 This is how catches are done from within C code. */
1081 Lisp_Object
1082 internal_catch (Lisp_Object tag,
1083 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1085 /* This structure is made part of the chain `catchlist'. */
1086 struct handler *c = push_handler (tag, CATCHER);
1088 /* Call FUNC. */
1089 if (! sys_setjmp (c->jmp))
1091 Lisp_Object val = func (arg);
1092 eassert (handlerlist == c);
1093 handlerlist = c->next;
1094 return val;
1096 else
1097 { /* Throw works by a longjmp that comes right here. */
1098 Lisp_Object val = handlerlist->val;
1099 clobbered_eassert (handlerlist == c);
1100 handlerlist = handlerlist->next;
1101 return val;
1105 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1106 jump to that CATCH, returning VALUE as the value of that catch.
1108 This is the guts of Fthrow and Fsignal; they differ only in the way
1109 they choose the catch tag to throw to. A catch tag for a
1110 condition-case form has a TAG of Qnil.
1112 Before each catch is discarded, unbind all special bindings and
1113 execute all unwind-protect clauses made above that catch. Unwind
1114 the handler stack as we go, so that the proper handlers are in
1115 effect for each unwind-protect clause we run. At the end, restore
1116 some static info saved in CATCH, and longjmp to the location
1117 specified there.
1119 This is used for correct unwinding in Fthrow and Fsignal. */
1121 static _Noreturn void
1122 unwind_to_catch (struct handler *catch, Lisp_Object value)
1124 bool last_time;
1126 eassert (catch->next);
1128 /* Save the value in the tag. */
1129 catch->val = value;
1131 /* Restore certain special C variables. */
1132 set_poll_suppress_count (catch->poll_suppress_count);
1133 unblock_input_to (catch->interrupt_input_blocked);
1134 immediate_quit = false;
1138 /* Unwind the specpdl stack, and then restore the proper set of
1139 handlers. */
1140 unbind_to (handlerlist->pdlcount, Qnil);
1141 last_time = handlerlist == catch;
1142 if (! last_time)
1143 handlerlist = handlerlist->next;
1145 while (! last_time);
1147 eassert (handlerlist == catch);
1149 lisp_eval_depth = catch->f_lisp_eval_depth;
1151 sys_longjmp (catch->jmp, 1);
1154 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1155 doc: /* Throw to the catch for TAG and return VALUE from it.
1156 Both TAG and VALUE are evalled. */
1157 attributes: noreturn)
1158 (register Lisp_Object tag, Lisp_Object value)
1160 struct handler *c;
1162 if (!NILP (tag))
1163 for (c = handlerlist; c; c = c->next)
1165 if (c->type == CATCHER_ALL)
1166 unwind_to_catch (c, Fcons (tag, value));
1167 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1168 unwind_to_catch (c, value);
1170 xsignal2 (Qno_catch, tag, value);
1174 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1175 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1176 If BODYFORM completes normally, its value is returned
1177 after executing the UNWINDFORMS.
1178 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1179 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1180 (Lisp_Object args)
1182 Lisp_Object val;
1183 ptrdiff_t count = SPECPDL_INDEX ();
1185 record_unwind_protect (prog_ignore, XCDR (args));
1186 val = eval_sub (XCAR (args));
1187 return unbind_to (count, val);
1190 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1191 doc: /* Regain control when an error is signaled.
1192 Executes BODYFORM and returns its value if no error happens.
1193 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1194 where the BODY is made of Lisp expressions.
1196 A handler is applicable to an error
1197 if CONDITION-NAME is one of the error's condition names.
1198 If an error happens, the first applicable handler is run.
1200 The car of a handler may be a list of condition names instead of a
1201 single condition name; then it handles all of them. If the special
1202 condition name `debug' is present in this list, it allows another
1203 condition in the list to run the debugger if `debug-on-error' and the
1204 other usual mechanisms says it should (otherwise, `condition-case'
1205 suppresses the debugger).
1207 When a handler handles an error, control returns to the `condition-case'
1208 and it executes the handler's BODY...
1209 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1210 \(If VAR is nil, the handler can't access that information.)
1211 Then the value of the last BODY form is returned from the `condition-case'
1212 expression.
1214 See also the function `signal' for more info.
1215 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1216 (Lisp_Object args)
1218 Lisp_Object var = XCAR (args);
1219 Lisp_Object bodyform = XCAR (XCDR (args));
1220 Lisp_Object handlers = XCDR (XCDR (args));
1222 return internal_lisp_condition_case (var, bodyform, handlers);
1225 /* Like Fcondition_case, but the args are separate
1226 rather than passed in a list. Used by Fbyte_code. */
1228 Lisp_Object
1229 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1230 Lisp_Object handlers)
1232 Lisp_Object val;
1233 struct handler *oldhandlerlist = handlerlist;
1234 int clausenb = 0;
1236 CHECK_SYMBOL (var);
1238 for (val = handlers; CONSP (val); val = XCDR (val))
1240 Lisp_Object tem = XCAR (val);
1241 clausenb++;
1242 if (! (NILP (tem)
1243 || (CONSP (tem)
1244 && (SYMBOLP (XCAR (tem))
1245 || CONSP (XCAR (tem))))))
1246 error ("Invalid condition handler: %s",
1247 SDATA (Fprin1_to_string (tem, Qt)));
1250 { /* The first clause is the one that should be checked first, so it should
1251 be added to handlerlist last. So we build in `clauses' a table that
1252 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1253 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1254 if (MAX_ALLOCA / word_size < clausenb)
1255 memory_full (SIZE_MAX);
1256 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1257 Lisp_Object *volatile clauses_volatile = clauses;
1258 int i = clausenb;
1259 for (val = handlers; CONSP (val); val = XCDR (val))
1260 clauses[--i] = XCAR (val);
1261 for (i = 0; i < clausenb; i++)
1263 Lisp_Object clause = clauses[i];
1264 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1265 if (!CONSP (condition))
1266 condition = Fcons (condition, Qnil);
1267 struct handler *c = push_handler (condition, CONDITION_CASE);
1268 if (sys_setjmp (c->jmp))
1270 ptrdiff_t count = SPECPDL_INDEX ();
1271 Lisp_Object val = handlerlist->val;
1272 Lisp_Object *chosen_clause = clauses_volatile;
1273 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1274 chosen_clause++;
1275 handlerlist = oldhandlerlist;
1276 if (!NILP (var))
1278 if (!NILP (Vinternal_interpreter_environment))
1279 specbind (Qinternal_interpreter_environment,
1280 Fcons (Fcons (var, val),
1281 Vinternal_interpreter_environment));
1282 else
1283 specbind (var, val);
1285 val = Fprogn (XCDR (*chosen_clause));
1286 /* Note that this just undoes the binding of var; whoever
1287 longjumped to us unwound the stack to c.pdlcount before
1288 throwing. */
1289 if (!NILP (var))
1290 unbind_to (count, Qnil);
1291 return val;
1296 val = eval_sub (bodyform);
1297 handlerlist = oldhandlerlist;
1298 return val;
1301 /* Call the function BFUN with no arguments, catching errors within it
1302 according to HANDLERS. If there is an error, call HFUN with
1303 one argument which is the data that describes the error:
1304 (SIGNALNAME . DATA)
1306 HANDLERS can be a list of conditions to catch.
1307 If HANDLERS is Qt, catch all errors.
1308 If HANDLERS is Qerror, catch all errors
1309 but allow the debugger to run if that is enabled. */
1311 Lisp_Object
1312 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1313 Lisp_Object (*hfun) (Lisp_Object))
1315 struct handler *c = push_handler (handlers, CONDITION_CASE);
1316 if (sys_setjmp (c->jmp))
1318 Lisp_Object val = handlerlist->val;
1319 clobbered_eassert (handlerlist == c);
1320 handlerlist = handlerlist->next;
1321 return hfun (val);
1323 else
1325 Lisp_Object val = bfun ();
1326 eassert (handlerlist == c);
1327 handlerlist = c->next;
1328 return val;
1332 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1334 Lisp_Object
1335 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1336 Lisp_Object handlers,
1337 Lisp_Object (*hfun) (Lisp_Object))
1339 struct handler *c = push_handler (handlers, CONDITION_CASE);
1340 if (sys_setjmp (c->jmp))
1342 Lisp_Object val = handlerlist->val;
1343 clobbered_eassert (handlerlist == c);
1344 handlerlist = handlerlist->next;
1345 return hfun (val);
1347 else
1349 Lisp_Object val = bfun (arg);
1350 eassert (handlerlist == c);
1351 handlerlist = c->next;
1352 return val;
1356 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1357 its arguments. */
1359 Lisp_Object
1360 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1361 Lisp_Object arg1,
1362 Lisp_Object arg2,
1363 Lisp_Object handlers,
1364 Lisp_Object (*hfun) (Lisp_Object))
1366 struct handler *c = push_handler (handlers, CONDITION_CASE);
1367 if (sys_setjmp (c->jmp))
1369 Lisp_Object val = handlerlist->val;
1370 clobbered_eassert (handlerlist == c);
1371 handlerlist = handlerlist->next;
1372 return hfun (val);
1374 else
1376 Lisp_Object val = bfun (arg1, arg2);
1377 eassert (handlerlist == c);
1378 handlerlist = c->next;
1379 return val;
1383 /* Like internal_condition_case but call BFUN with NARGS as first,
1384 and ARGS as second argument. */
1386 Lisp_Object
1387 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1388 ptrdiff_t nargs,
1389 Lisp_Object *args,
1390 Lisp_Object handlers,
1391 Lisp_Object (*hfun) (Lisp_Object err,
1392 ptrdiff_t nargs,
1393 Lisp_Object *args))
1395 struct handler *c = push_handler (handlers, CONDITION_CASE);
1396 if (sys_setjmp (c->jmp))
1398 Lisp_Object val = handlerlist->val;
1399 clobbered_eassert (handlerlist == c);
1400 handlerlist = handlerlist->next;
1401 return hfun (val, nargs, args);
1403 else
1405 Lisp_Object val = bfun (nargs, args);
1406 eassert (handlerlist == c);
1407 handlerlist = c->next;
1408 return val;
1412 struct handler *
1413 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1415 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1416 if (!c)
1417 memory_full (sizeof *c);
1418 return c;
1421 struct handler *
1422 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1424 struct handler *c = handlerlist->nextfree;
1425 if (!c)
1427 c = malloc (sizeof *c);
1428 if (!c)
1429 return c;
1430 if (profiler_memory_running)
1431 malloc_probe (sizeof *c);
1432 c->nextfree = NULL;
1433 handlerlist->nextfree = c;
1435 c->type = handlertype;
1436 c->tag_or_ch = tag_ch_val;
1437 c->val = Qnil;
1438 c->next = handlerlist;
1439 c->f_lisp_eval_depth = lisp_eval_depth;
1440 c->pdlcount = SPECPDL_INDEX ();
1441 c->poll_suppress_count = poll_suppress_count;
1442 c->interrupt_input_blocked = interrupt_input_blocked;
1443 handlerlist = c;
1444 return c;
1448 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1449 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1450 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1451 Lisp_Object data);
1453 static void
1454 process_quit_flag (void)
1456 Lisp_Object flag = Vquit_flag;
1457 Vquit_flag = Qnil;
1458 if (EQ (flag, Qkill_emacs))
1459 Fkill_emacs (Qnil);
1460 if (EQ (Vthrow_on_input, flag))
1461 Fthrow (Vthrow_on_input, Qt);
1462 quit ();
1465 void
1466 maybe_quit (void)
1468 if (!NILP (Vquit_flag) && NILP (Vinhibit_quit))
1469 process_quit_flag ();
1470 else if (pending_signals)
1471 process_pending_signals ();
1474 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1475 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1476 This function does not return.
1478 An error symbol is a symbol with an `error-conditions' property
1479 that is a list of condition names.
1480 A handler for any of those names will get to handle this signal.
1481 The symbol `error' should normally be one of them.
1483 DATA should be a list. Its elements are printed as part of the error message.
1484 See Info anchor `(elisp)Definition of signal' for some details on how this
1485 error message is constructed.
1486 If the signal is handled, DATA is made available to the handler.
1487 See also the function `condition-case'. */
1488 attributes: noreturn)
1489 (Lisp_Object error_symbol, Lisp_Object data)
1491 signal_or_quit (error_symbol, data, false);
1492 eassume (false);
1495 /* Quit, in response to a keyboard quit request. */
1496 Lisp_Object
1497 quit (void)
1499 return signal_or_quit (Qquit, Qnil, true);
1502 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1503 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1504 Qquit and DATA should be Qnil, and this function may return.
1505 Otherwise this function is like Fsignal and does not return. */
1507 static Lisp_Object
1508 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1510 /* When memory is full, ERROR-SYMBOL is nil,
1511 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1512 That is a special case--don't do this in other situations. */
1513 Lisp_Object conditions;
1514 Lisp_Object string;
1515 Lisp_Object real_error_symbol
1516 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1517 Lisp_Object clause = Qnil;
1518 struct handler *h;
1520 immediate_quit = false;
1521 if (gc_in_progress || waiting_for_input)
1522 emacs_abort ();
1524 #if 0 /* rms: I don't know why this was here,
1525 but it is surely wrong for an error that is handled. */
1526 #ifdef HAVE_WINDOW_SYSTEM
1527 if (display_hourglass_p)
1528 cancel_hourglass ();
1529 #endif
1530 #endif
1532 /* This hook is used by edebug. */
1533 if (! NILP (Vsignal_hook_function)
1534 && ! NILP (error_symbol))
1536 /* Edebug takes care of restoring these variables when it exits. */
1537 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1538 max_lisp_eval_depth = lisp_eval_depth + 20;
1540 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1541 max_specpdl_size = SPECPDL_INDEX () + 40;
1543 call2 (Vsignal_hook_function, error_symbol, data);
1546 conditions = Fget (real_error_symbol, Qerror_conditions);
1548 /* Remember from where signal was called. Skip over the frame for
1549 `signal' itself. If a frame for `error' follows, skip that,
1550 too. Don't do this when ERROR_SYMBOL is nil, because that
1551 is a memory-full error. */
1552 Vsignaling_function = Qnil;
1553 if (!NILP (error_symbol))
1555 union specbinding *pdl = backtrace_next (backtrace_top ());
1556 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1557 pdl = backtrace_next (pdl);
1558 if (backtrace_p (pdl))
1559 Vsignaling_function = backtrace_function (pdl);
1562 for (h = handlerlist; h; h = h->next)
1564 if (h->type != CONDITION_CASE)
1565 continue;
1566 clause = find_handler_clause (h->tag_or_ch, conditions);
1567 if (!NILP (clause))
1568 break;
1571 if (/* Don't run the debugger for a memory-full error.
1572 (There is no room in memory to do that!) */
1573 !NILP (error_symbol)
1574 && (!NILP (Vdebug_on_signal)
1575 /* If no handler is present now, try to run the debugger. */
1576 || NILP (clause)
1577 /* A `debug' symbol in the handler list disables the normal
1578 suppression of the debugger. */
1579 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1580 /* Special handler that means "print a message and run debugger
1581 if requested". */
1582 || EQ (h->tag_or_ch, Qerror)))
1584 bool debugger_called
1585 = maybe_call_debugger (conditions, error_symbol, data);
1586 /* We can't return values to code which signaled an error, but we
1587 can continue code which has signaled a quit. */
1588 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1589 return Qnil;
1592 if (!NILP (clause))
1594 Lisp_Object unwind_data
1595 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1597 unwind_to_catch (h, unwind_data);
1599 else
1601 if (handlerlist != handlerlist_sentinel)
1602 /* FIXME: This will come right back here if there's no `top-level'
1603 catcher. A better solution would be to abort here, and instead
1604 add a catch-all condition handler so we never come here. */
1605 Fthrow (Qtop_level, Qt);
1608 if (! NILP (error_symbol))
1609 data = Fcons (error_symbol, data);
1611 string = Ferror_message_string (data);
1612 fatal ("%s", SDATA (string));
1615 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1617 void
1618 xsignal0 (Lisp_Object error_symbol)
1620 xsignal (error_symbol, Qnil);
1623 void
1624 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1626 xsignal (error_symbol, list1 (arg));
1629 void
1630 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1632 xsignal (error_symbol, list2 (arg1, arg2));
1635 void
1636 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1638 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1641 /* Signal `error' with message S, and additional arg ARG.
1642 If ARG is not a genuine list, make it a one-element list. */
1644 void
1645 signal_error (const char *s, Lisp_Object arg)
1647 Lisp_Object tortoise, hare;
1649 hare = tortoise = arg;
1650 while (CONSP (hare))
1652 hare = XCDR (hare);
1653 if (!CONSP (hare))
1654 break;
1656 hare = XCDR (hare);
1657 tortoise = XCDR (tortoise);
1659 if (EQ (hare, tortoise))
1660 break;
1663 if (!NILP (hare))
1664 arg = list1 (arg);
1666 xsignal (Qerror, Fcons (build_string (s), arg));
1670 /* Return true if LIST is a non-nil atom or
1671 a list containing one of CONDITIONS. */
1673 static bool
1674 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1676 if (NILP (list))
1677 return 0;
1678 if (! CONSP (list))
1679 return 1;
1681 while (CONSP (conditions))
1683 Lisp_Object this, tail;
1684 this = XCAR (conditions);
1685 for (tail = list; CONSP (tail); tail = XCDR (tail))
1686 if (EQ (XCAR (tail), this))
1687 return 1;
1688 conditions = XCDR (conditions);
1690 return 0;
1693 /* Return true if an error with condition-symbols CONDITIONS,
1694 and described by SIGNAL-DATA, should skip the debugger
1695 according to debugger-ignored-errors. */
1697 static bool
1698 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1700 Lisp_Object tail;
1701 bool first_string = 1;
1702 Lisp_Object error_message;
1704 error_message = Qnil;
1705 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1707 if (STRINGP (XCAR (tail)))
1709 if (first_string)
1711 error_message = Ferror_message_string (data);
1712 first_string = 0;
1715 if (fast_string_match (XCAR (tail), error_message) >= 0)
1716 return 1;
1718 else
1720 Lisp_Object contail;
1722 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1723 if (EQ (XCAR (tail), XCAR (contail)))
1724 return 1;
1728 return 0;
1731 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1732 SIG and DATA describe the signal. There are two ways to pass them:
1733 = SIG is the error symbol, and DATA is the rest of the data.
1734 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1735 This is for memory-full errors only. */
1736 static bool
1737 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1739 Lisp_Object combined_data;
1741 combined_data = Fcons (sig, data);
1743 if (
1744 /* Don't try to run the debugger with interrupts blocked.
1745 The editing loop would return anyway. */
1746 ! input_blocked_p ()
1747 && NILP (Vinhibit_debugger)
1748 /* Does user want to enter debugger for this kind of error? */
1749 && (EQ (sig, Qquit)
1750 ? debug_on_quit
1751 : wants_debugger (Vdebug_on_error, conditions))
1752 && ! skip_debugger (conditions, combined_data)
1753 /* RMS: What's this for? */
1754 && when_entered_debugger < num_nonmacro_input_events)
1756 call_debugger (list2 (Qerror, combined_data));
1757 return 1;
1760 return 0;
1763 static Lisp_Object
1764 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1766 register Lisp_Object h;
1768 /* t is used by handlers for all conditions, set up by C code. */
1769 if (EQ (handlers, Qt))
1770 return Qt;
1772 /* error is used similarly, but means print an error message
1773 and run the debugger if that is enabled. */
1774 if (EQ (handlers, Qerror))
1775 return Qt;
1777 for (h = handlers; CONSP (h); h = XCDR (h))
1779 Lisp_Object handler = XCAR (h);
1780 if (!NILP (Fmemq (handler, conditions)))
1781 return handlers;
1784 return Qnil;
1788 /* Format and return a string; called like vprintf. */
1789 Lisp_Object
1790 vformat_string (const char *m, va_list ap)
1792 char buf[4000];
1793 ptrdiff_t size = sizeof buf;
1794 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1795 char *buffer = buf;
1796 ptrdiff_t used;
1797 Lisp_Object string;
1799 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1800 string = make_string (buffer, used);
1801 if (buffer != buf)
1802 xfree (buffer);
1804 return string;
1807 /* Dump an error message; called like vprintf. */
1808 void
1809 verror (const char *m, va_list ap)
1811 xsignal1 (Qerror, vformat_string (m, ap));
1815 /* Dump an error message; called like printf. */
1817 /* VARARGS 1 */
1818 void
1819 error (const char *m, ...)
1821 va_list ap;
1822 va_start (ap, m);
1823 verror (m, ap);
1826 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1827 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1828 This means it contains a description for how to read arguments to give it.
1829 The value is nil for an invalid function or a symbol with no function
1830 definition.
1832 Interactively callable functions include strings and vectors (treated
1833 as keyboard macros), lambda-expressions that contain a top-level call
1834 to `interactive', autoload definitions made by `autoload' with non-nil
1835 fourth argument, and some of the built-in functions of Lisp.
1837 Also, a symbol satisfies `commandp' if its function definition does so.
1839 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1840 then strings and vectors are not accepted. */)
1841 (Lisp_Object function, Lisp_Object for_call_interactively)
1843 register Lisp_Object fun;
1844 register Lisp_Object funcar;
1845 Lisp_Object if_prop = Qnil;
1847 fun = function;
1849 fun = indirect_function (fun); /* Check cycles. */
1850 if (NILP (fun))
1851 return Qnil;
1853 /* Check an `interactive-form' property if present, analogous to the
1854 function-documentation property. */
1855 fun = function;
1856 while (SYMBOLP (fun))
1858 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1859 if (!NILP (tmp))
1860 if_prop = Qt;
1861 fun = Fsymbol_function (fun);
1864 /* Emacs primitives are interactive if their DEFUN specifies an
1865 interactive spec. */
1866 if (SUBRP (fun))
1867 return XSUBR (fun)->intspec ? Qt : if_prop;
1869 /* Bytecode objects are interactive if they are long enough to
1870 have an element whose index is COMPILED_INTERACTIVE, which is
1871 where the interactive spec is stored. */
1872 else if (COMPILEDP (fun))
1873 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1874 ? Qt : if_prop);
1876 /* Strings and vectors are keyboard macros. */
1877 if (STRINGP (fun) || VECTORP (fun))
1878 return (NILP (for_call_interactively) ? Qt : Qnil);
1880 /* Lists may represent commands. */
1881 if (!CONSP (fun))
1882 return Qnil;
1883 funcar = XCAR (fun);
1884 if (EQ (funcar, Qclosure))
1885 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1886 ? Qt : if_prop);
1887 else if (EQ (funcar, Qlambda))
1888 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1889 else if (EQ (funcar, Qautoload))
1890 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1891 else
1892 return Qnil;
1895 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1896 doc: /* Define FUNCTION to autoload from FILE.
1897 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1898 Third arg DOCSTRING is documentation for the function.
1899 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1900 Fifth arg TYPE indicates the type of the object:
1901 nil or omitted says FUNCTION is a function,
1902 `keymap' says FUNCTION is really a keymap, and
1903 `macro' or t says FUNCTION is really a macro.
1904 Third through fifth args give info about the real definition.
1905 They default to nil.
1906 If FUNCTION is already defined other than as an autoload,
1907 this does nothing and returns nil. */)
1908 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1910 CHECK_SYMBOL (function);
1911 CHECK_STRING (file);
1913 /* If function is defined and not as an autoload, don't override. */
1914 if (!NILP (XSYMBOL (function)->function)
1915 && !AUTOLOADP (XSYMBOL (function)->function))
1916 return Qnil;
1918 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1919 /* `read1' in lread.c has found the docstring starting with "\
1920 and assumed the docstring will be provided by Snarf-documentation, so it
1921 passed us 0 instead. But that leads to accidental sharing in purecopy's
1922 hash-consing, so we use a (hopefully) unique integer instead. */
1923 docstring = make_number (XHASH (function));
1924 return Fdefalias (function,
1925 list5 (Qautoload, file, docstring, interactive, type),
1926 Qnil);
1929 void
1930 un_autoload (Lisp_Object oldqueue)
1932 Lisp_Object queue, first, second;
1934 /* Queue to unwind is current value of Vautoload_queue.
1935 oldqueue is the shadowed value to leave in Vautoload_queue. */
1936 queue = Vautoload_queue;
1937 Vautoload_queue = oldqueue;
1938 while (CONSP (queue))
1940 first = XCAR (queue);
1941 second = Fcdr (first);
1942 first = Fcar (first);
1943 if (EQ (first, make_number (0)))
1944 Vfeatures = second;
1945 else
1946 Ffset (first, second);
1947 queue = XCDR (queue);
1951 /* Load an autoloaded function.
1952 FUNNAME is the symbol which is the function's name.
1953 FUNDEF is the autoload definition (a list). */
1955 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1956 doc: /* Load FUNDEF which should be an autoload.
1957 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1958 in which case the function returns the new autoloaded function value.
1959 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1960 it defines a macro. */)
1961 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1963 ptrdiff_t count = SPECPDL_INDEX ();
1965 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1966 return fundef;
1968 /* In the special case that we are generating ldefs-boot-auto.el,
1969 then be noisy about the autoload. */
1970 if( generating_ldefs_boot )
1972 fprintf(stderr, "(autoload '");
1973 Fprin1(funname,Qexternal_debugging_output);
1974 fprintf(stderr, " ");
1975 Fprin1(Fcar (Fcdr (fundef)),Qexternal_debugging_output);
1976 fprintf(stderr, " nil nil ");
1978 Lisp_Object kind = Fnth (make_number (4), fundef);
1979 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1981 fprintf(stderr, "nil");
1983 else
1985 fprintf(stderr, "t");
1987 fprintf(stderr, ")\n");
1990 if (EQ (macro_only, Qmacro))
1992 Lisp_Object kind = Fnth (make_number (4), fundef);
1993 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1994 return fundef;
1997 /* This is to make sure that loadup.el gives a clear picture
1998 of what files are preloaded and when. */
1999 if (! NILP (Vpurify_flag))
2000 error ("Attempt to autoload %s while preparing to dump",
2001 SDATA (SYMBOL_NAME (funname)));
2003 CHECK_SYMBOL (funname);
2005 /* Preserve the match data. */
2006 record_unwind_save_match_data ();
2008 /* If autoloading gets an error (which includes the error of failing
2009 to define the function being called), we use Vautoload_queue
2010 to undo function definitions and `provide' calls made by
2011 the function. We do this in the specific case of autoloading
2012 because autoloading is not an explicit request "load this file",
2013 but rather a request to "call this function".
2015 The value saved here is to be restored into Vautoload_queue. */
2016 record_unwind_protect (un_autoload, Vautoload_queue);
2017 Vautoload_queue = Qt;
2018 /* If `macro_only', assume this autoload to be a "best-effort",
2019 so don't signal an error if autoloading fails. */
2020 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
2022 /* Once loading finishes, don't undo it. */
2023 Vautoload_queue = Qt;
2024 unbind_to (count, Qnil);
2026 if (NILP (funname))
2027 return Qnil;
2028 else
2030 Lisp_Object fun = Findirect_function (funname, Qnil);
2032 if (!NILP (Fequal (fun, fundef)))
2033 error ("Autoloading file %s failed to define function %s",
2034 SDATA (Fcar (Fcar (Vload_history))),
2035 SDATA (SYMBOL_NAME (funname)));
2036 else
2037 return fun;
2042 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2043 doc: /* Evaluate FORM and return its value.
2044 If LEXICAL is t, evaluate using lexical scoping.
2045 LEXICAL can also be an actual lexical environment, in the form of an
2046 alist mapping symbols to their value. */)
2047 (Lisp_Object form, Lisp_Object lexical)
2049 ptrdiff_t count = SPECPDL_INDEX ();
2050 specbind (Qinternal_interpreter_environment,
2051 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2052 return unbind_to (count, eval_sub (form));
2055 /* Grow the specpdl stack by one entry.
2056 The caller should have already initialized the entry.
2057 Signal an error on stack overflow.
2059 Make sure that there is always one unused entry past the top of the
2060 stack, so that the just-initialized entry is safely unwound if
2061 memory exhausted and an error is signaled here. Also, allocate a
2062 never-used entry just before the bottom of the stack; sometimes its
2063 address is taken. */
2065 static void
2066 grow_specpdl (void)
2068 specpdl_ptr++;
2070 if (specpdl_ptr == specpdl + specpdl_size)
2072 ptrdiff_t count = SPECPDL_INDEX ();
2073 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2074 union specbinding *pdlvec = specpdl - 1;
2075 ptrdiff_t pdlvecsize = specpdl_size + 1;
2076 if (max_size <= specpdl_size)
2078 if (max_specpdl_size < 400)
2079 max_size = max_specpdl_size = 400;
2080 if (max_size <= specpdl_size)
2081 signal_error ("Variable binding depth exceeds max-specpdl-size",
2082 Qnil);
2084 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2085 specpdl = pdlvec + 1;
2086 specpdl_size = pdlvecsize - 1;
2087 specpdl_ptr = specpdl + count;
2091 ptrdiff_t
2092 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2094 ptrdiff_t count = SPECPDL_INDEX ();
2096 eassert (nargs >= UNEVALLED);
2097 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2098 specpdl_ptr->bt.debug_on_exit = false;
2099 specpdl_ptr->bt.function = function;
2100 specpdl_ptr->bt.args = args;
2101 specpdl_ptr->bt.nargs = nargs;
2102 grow_specpdl ();
2104 return count;
2107 /* Eval a sub-expression of the current expression (i.e. in the same
2108 lexical scope). */
2109 Lisp_Object
2110 eval_sub (Lisp_Object form)
2112 Lisp_Object fun, val, original_fun, original_args;
2113 Lisp_Object funcar;
2114 ptrdiff_t count;
2116 /* Declare here, as this array may be accessed by call_debugger near
2117 the end of this function. See Bug#21245. */
2118 Lisp_Object argvals[8];
2120 if (SYMBOLP (form))
2122 /* Look up its binding in the lexical environment.
2123 We do not pay attention to the declared_special flag here, since we
2124 already did that when let-binding the variable. */
2125 Lisp_Object lex_binding
2126 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2127 ? Fassq (form, Vinternal_interpreter_environment)
2128 : Qnil;
2129 if (CONSP (lex_binding))
2130 return XCDR (lex_binding);
2131 else
2132 return Fsymbol_value (form);
2135 if (!CONSP (form))
2136 return form;
2138 maybe_quit ();
2140 maybe_gc ();
2142 if (++lisp_eval_depth > max_lisp_eval_depth)
2144 if (max_lisp_eval_depth < 100)
2145 max_lisp_eval_depth = 100;
2146 if (lisp_eval_depth > max_lisp_eval_depth)
2147 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2150 original_fun = XCAR (form);
2151 original_args = XCDR (form);
2153 /* This also protects them from gc. */
2154 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2156 if (debug_on_next_call)
2157 do_debug_on_call (Qt, count);
2159 /* At this point, only original_fun and original_args
2160 have values that will be used below. */
2161 retry:
2163 /* Optimize for no indirection. */
2164 fun = original_fun;
2165 if (!SYMBOLP (fun))
2166 fun = Ffunction (Fcons (fun, Qnil));
2167 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2168 fun = indirect_function (fun);
2170 if (SUBRP (fun))
2172 Lisp_Object args_left = original_args;
2173 Lisp_Object numargs = Flength (args_left);
2175 check_cons_list ();
2177 if (XINT (numargs) < XSUBR (fun)->min_args
2178 || (XSUBR (fun)->max_args >= 0
2179 && XSUBR (fun)->max_args < XINT (numargs)))
2180 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2182 else if (XSUBR (fun)->max_args == UNEVALLED)
2183 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2184 else if (XSUBR (fun)->max_args == MANY)
2186 /* Pass a vector of evaluated arguments. */
2187 Lisp_Object *vals;
2188 ptrdiff_t argnum = 0;
2189 USE_SAFE_ALLOCA;
2191 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2193 while (!NILP (args_left))
2195 vals[argnum++] = eval_sub (Fcar (args_left));
2196 args_left = Fcdr (args_left);
2199 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2201 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2203 check_cons_list ();
2204 lisp_eval_depth--;
2205 /* Do the debug-on-exit now, while VALS still exists. */
2206 if (backtrace_debug_on_exit (specpdl + count))
2207 val = call_debugger (list2 (Qexit, val));
2208 SAFE_FREE ();
2209 specpdl_ptr--;
2210 return val;
2212 else
2214 int i, maxargs = XSUBR (fun)->max_args;
2216 for (i = 0; i < maxargs; i++)
2218 argvals[i] = eval_sub (Fcar (args_left));
2219 args_left = Fcdr (args_left);
2222 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2224 switch (i)
2226 case 0:
2227 val = (XSUBR (fun)->function.a0 ());
2228 break;
2229 case 1:
2230 val = (XSUBR (fun)->function.a1 (argvals[0]));
2231 break;
2232 case 2:
2233 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2234 break;
2235 case 3:
2236 val = (XSUBR (fun)->function.a3
2237 (argvals[0], argvals[1], argvals[2]));
2238 break;
2239 case 4:
2240 val = (XSUBR (fun)->function.a4
2241 (argvals[0], argvals[1], argvals[2], argvals[3]));
2242 break;
2243 case 5:
2244 val = (XSUBR (fun)->function.a5
2245 (argvals[0], argvals[1], argvals[2], argvals[3],
2246 argvals[4]));
2247 break;
2248 case 6:
2249 val = (XSUBR (fun)->function.a6
2250 (argvals[0], argvals[1], argvals[2], argvals[3],
2251 argvals[4], argvals[5]));
2252 break;
2253 case 7:
2254 val = (XSUBR (fun)->function.a7
2255 (argvals[0], argvals[1], argvals[2], argvals[3],
2256 argvals[4], argvals[5], argvals[6]));
2257 break;
2259 case 8:
2260 val = (XSUBR (fun)->function.a8
2261 (argvals[0], argvals[1], argvals[2], argvals[3],
2262 argvals[4], argvals[5], argvals[6], argvals[7]));
2263 break;
2265 default:
2266 /* Someone has created a subr that takes more arguments than
2267 is supported by this code. We need to either rewrite the
2268 subr to use a different argument protocol, or add more
2269 cases to this switch. */
2270 emacs_abort ();
2274 else if (COMPILEDP (fun))
2275 return apply_lambda (fun, original_args, count);
2276 else
2278 if (NILP (fun))
2279 xsignal1 (Qvoid_function, original_fun);
2280 if (!CONSP (fun))
2281 xsignal1 (Qinvalid_function, original_fun);
2282 funcar = XCAR (fun);
2283 if (!SYMBOLP (funcar))
2284 xsignal1 (Qinvalid_function, original_fun);
2285 if (EQ (funcar, Qautoload))
2287 Fautoload_do_load (fun, original_fun, Qnil);
2288 goto retry;
2290 if (EQ (funcar, Qmacro))
2292 ptrdiff_t count1 = SPECPDL_INDEX ();
2293 Lisp_Object exp;
2294 /* Bind lexical-binding during expansion of the macro, so the
2295 macro can know reliably if the code it outputs will be
2296 interpreted using lexical-binding or not. */
2297 specbind (Qlexical_binding,
2298 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2299 exp = apply1 (Fcdr (fun), original_args);
2300 unbind_to (count1, Qnil);
2301 val = eval_sub (exp);
2303 else if (EQ (funcar, Qlambda)
2304 || EQ (funcar, Qclosure))
2305 return apply_lambda (fun, original_args, count);
2306 else
2307 xsignal1 (Qinvalid_function, original_fun);
2309 check_cons_list ();
2311 lisp_eval_depth--;
2312 if (backtrace_debug_on_exit (specpdl + count))
2313 val = call_debugger (list2 (Qexit, val));
2314 specpdl_ptr--;
2316 return val;
2319 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2320 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2321 Then return the value FUNCTION returns.
2322 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2323 usage: (apply FUNCTION &rest ARGUMENTS) */)
2324 (ptrdiff_t nargs, Lisp_Object *args)
2326 ptrdiff_t i, numargs, funcall_nargs;
2327 register Lisp_Object *funcall_args = NULL;
2328 register Lisp_Object spread_arg = args[nargs - 1];
2329 Lisp_Object fun = args[0];
2330 Lisp_Object retval;
2331 USE_SAFE_ALLOCA;
2333 CHECK_LIST (spread_arg);
2335 numargs = XINT (Flength (spread_arg));
2337 if (numargs == 0)
2338 return Ffuncall (nargs - 1, args);
2339 else if (numargs == 1)
2341 args [nargs - 1] = XCAR (spread_arg);
2342 return Ffuncall (nargs, args);
2345 numargs += nargs - 2;
2347 /* Optimize for no indirection. */
2348 if (SYMBOLP (fun) && !NILP (fun)
2349 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2351 fun = indirect_function (fun);
2352 if (NILP (fun))
2353 /* Let funcall get the error. */
2354 fun = args[0];
2357 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2358 /* Don't hide an error by adding missing arguments. */
2359 && numargs >= XSUBR (fun)->min_args)
2361 /* Avoid making funcall cons up a yet another new vector of arguments
2362 by explicitly supplying nil's for optional values. */
2363 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2364 memclear (funcall_args + numargs + 1,
2365 (XSUBR (fun)->max_args - numargs) * word_size);
2366 funcall_nargs = 1 + XSUBR (fun)->max_args;
2368 else
2369 { /* We add 1 to numargs because funcall_args includes the
2370 function itself as well as its arguments. */
2371 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2372 funcall_nargs = 1 + numargs;
2375 memcpy (funcall_args, args, nargs * word_size);
2376 /* Spread the last arg we got. Its first element goes in
2377 the slot that it used to occupy, hence this value of I. */
2378 i = nargs - 1;
2379 while (!NILP (spread_arg))
2381 funcall_args [i++] = XCAR (spread_arg);
2382 spread_arg = XCDR (spread_arg);
2385 retval = Ffuncall (funcall_nargs, funcall_args);
2387 SAFE_FREE ();
2388 return retval;
2391 /* Run hook variables in various ways. */
2393 static Lisp_Object
2394 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2396 Ffuncall (nargs, args);
2397 return Qnil;
2400 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2401 doc: /* Run each hook in HOOKS.
2402 Each argument should be a symbol, a hook variable.
2403 These symbols are processed in the order specified.
2404 If a hook symbol has a non-nil value, that value may be a function
2405 or a list of functions to be called to run the hook.
2406 If the value is a function, it is called with no arguments.
2407 If it is a list, the elements are called, in order, with no arguments.
2409 Major modes should not use this function directly to run their mode
2410 hook; they should use `run-mode-hooks' instead.
2412 Do not use `make-local-variable' to make a hook variable buffer-local.
2413 Instead, use `add-hook' and specify t for the LOCAL argument.
2414 usage: (run-hooks &rest HOOKS) */)
2415 (ptrdiff_t nargs, Lisp_Object *args)
2417 ptrdiff_t i;
2419 for (i = 0; i < nargs; i++)
2420 run_hook (args[i]);
2422 return Qnil;
2425 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2426 Srun_hook_with_args, 1, MANY, 0,
2427 doc: /* Run HOOK with the specified arguments ARGS.
2428 HOOK should be a symbol, a hook variable. The value of HOOK
2429 may be nil, a function, or a list of functions. Call each
2430 function in order with arguments ARGS. The final return value
2431 is unspecified.
2433 Do not use `make-local-variable' to make a hook variable buffer-local.
2434 Instead, use `add-hook' and specify t for the LOCAL argument.
2435 usage: (run-hook-with-args HOOK &rest ARGS) */)
2436 (ptrdiff_t nargs, Lisp_Object *args)
2438 return run_hook_with_args (nargs, args, funcall_nil);
2441 /* NB this one still documents a specific non-nil return value.
2442 (As did run-hook-with-args and run-hook-with-args-until-failure
2443 until they were changed in 24.1.) */
2444 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2445 Srun_hook_with_args_until_success, 1, MANY, 0,
2446 doc: /* Run HOOK with the specified arguments ARGS.
2447 HOOK should be a symbol, a hook variable. The value of HOOK
2448 may be nil, a function, or a list of functions. Call each
2449 function in order with arguments ARGS, stopping at the first
2450 one that returns non-nil, and return that value. Otherwise (if
2451 all functions return nil, or if there are no functions to call),
2452 return nil.
2454 Do not use `make-local-variable' to make a hook variable buffer-local.
2455 Instead, use `add-hook' and specify t for the LOCAL argument.
2456 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2457 (ptrdiff_t nargs, Lisp_Object *args)
2459 return run_hook_with_args (nargs, args, Ffuncall);
2462 static Lisp_Object
2463 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2465 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2468 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2469 Srun_hook_with_args_until_failure, 1, MANY, 0,
2470 doc: /* Run HOOK with the specified arguments ARGS.
2471 HOOK should be a symbol, a hook variable. The value of HOOK
2472 may be nil, a function, or a list of functions. Call each
2473 function in order with arguments ARGS, stopping at the first
2474 one that returns nil, and return nil. Otherwise (if all functions
2475 return non-nil, or if there are no functions to call), return non-nil
2476 \(do not rely on the precise return value in this case).
2478 Do not use `make-local-variable' to make a hook variable buffer-local.
2479 Instead, use `add-hook' and specify t for the LOCAL argument.
2480 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2481 (ptrdiff_t nargs, Lisp_Object *args)
2483 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2486 static Lisp_Object
2487 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2489 Lisp_Object tmp = args[0], ret;
2490 args[0] = args[1];
2491 args[1] = tmp;
2492 ret = Ffuncall (nargs, args);
2493 args[1] = args[0];
2494 args[0] = tmp;
2495 return ret;
2498 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2499 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2500 I.e. instead of calling each function FUN directly with arguments ARGS,
2501 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2502 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2503 aborts and returns that value.
2504 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2505 (ptrdiff_t nargs, Lisp_Object *args)
2507 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2510 /* ARGS[0] should be a hook symbol.
2511 Call each of the functions in the hook value, passing each of them
2512 as arguments all the rest of ARGS (all NARGS - 1 elements).
2513 FUNCALL specifies how to call each function on the hook. */
2515 Lisp_Object
2516 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2517 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2519 Lisp_Object sym, val, ret = Qnil;
2521 /* If we are dying or still initializing,
2522 don't do anything--it would probably crash if we tried. */
2523 if (NILP (Vrun_hooks))
2524 return Qnil;
2526 sym = args[0];
2527 val = find_symbol_value (sym);
2529 if (EQ (val, Qunbound) || NILP (val))
2530 return ret;
2531 else if (!CONSP (val) || FUNCTIONP (val))
2533 args[0] = val;
2534 return funcall (nargs, args);
2536 else
2538 Lisp_Object global_vals = Qnil;
2540 for (;
2541 CONSP (val) && NILP (ret);
2542 val = XCDR (val))
2544 if (EQ (XCAR (val), Qt))
2546 /* t indicates this hook has a local binding;
2547 it means to run the global binding too. */
2548 global_vals = Fdefault_value (sym);
2549 if (NILP (global_vals)) continue;
2551 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2553 args[0] = global_vals;
2554 ret = funcall (nargs, args);
2556 else
2558 for (;
2559 CONSP (global_vals) && NILP (ret);
2560 global_vals = XCDR (global_vals))
2562 args[0] = XCAR (global_vals);
2563 /* In a global value, t should not occur. If it does, we
2564 must ignore it to avoid an endless loop. */
2565 if (!EQ (args[0], Qt))
2566 ret = funcall (nargs, args);
2570 else
2572 args[0] = XCAR (val);
2573 ret = funcall (nargs, args);
2577 return ret;
2581 /* Run the hook HOOK, giving each function no args. */
2583 void
2584 run_hook (Lisp_Object hook)
2586 Frun_hook_with_args (1, &hook);
2589 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2591 void
2592 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2594 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2597 /* Apply fn to arg. */
2598 Lisp_Object
2599 apply1 (Lisp_Object fn, Lisp_Object arg)
2601 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2604 /* Call function fn on no arguments. */
2605 Lisp_Object
2606 call0 (Lisp_Object fn)
2608 return Ffuncall (1, &fn);
2611 /* Call function fn with 1 argument arg1. */
2612 /* ARGSUSED */
2613 Lisp_Object
2614 call1 (Lisp_Object fn, Lisp_Object arg1)
2616 return CALLN (Ffuncall, fn, arg1);
2619 /* Call function fn with 2 arguments arg1, arg2. */
2620 /* ARGSUSED */
2621 Lisp_Object
2622 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2624 return CALLN (Ffuncall, fn, arg1, arg2);
2627 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2628 /* ARGSUSED */
2629 Lisp_Object
2630 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2632 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2635 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2636 /* ARGSUSED */
2637 Lisp_Object
2638 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2639 Lisp_Object arg4)
2641 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2644 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2645 /* ARGSUSED */
2646 Lisp_Object
2647 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2648 Lisp_Object arg4, Lisp_Object arg5)
2650 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2653 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2654 /* ARGSUSED */
2655 Lisp_Object
2656 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2657 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2659 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2662 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2663 /* ARGSUSED */
2664 Lisp_Object
2665 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2666 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2668 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2671 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2672 doc: /* Non-nil if OBJECT is a function. */)
2673 (Lisp_Object object)
2675 if (FUNCTIONP (object))
2676 return Qt;
2677 return Qnil;
2680 bool
2681 FUNCTIONP (Lisp_Object object)
2683 if (SYMBOLP (object) && !NILP (Ffboundp (object)))
2685 object = Findirect_function (object, Qt);
2687 if (CONSP (object) && EQ (XCAR (object), Qautoload))
2689 /* Autoloaded symbols are functions, except if they load
2690 macros or keymaps. */
2691 for (int i = 0; i < 4 && CONSP (object); i++)
2692 object = XCDR (object);
2694 return ! (CONSP (object) && !NILP (XCAR (object)));
2698 if (SUBRP (object))
2699 return XSUBR (object)->max_args != UNEVALLED;
2700 else if (COMPILEDP (object))
2701 return true;
2702 else if (CONSP (object))
2704 Lisp_Object car = XCAR (object);
2705 return EQ (car, Qlambda) || EQ (car, Qclosure);
2707 else
2708 return false;
2711 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2712 doc: /* Call first argument as a function, passing remaining arguments to it.
2713 Return the value that function returns.
2714 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2715 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2716 (ptrdiff_t nargs, Lisp_Object *args)
2718 Lisp_Object fun, original_fun;
2719 Lisp_Object funcar;
2720 ptrdiff_t numargs = nargs - 1;
2721 Lisp_Object val;
2722 ptrdiff_t count;
2724 maybe_quit ();
2726 if (++lisp_eval_depth > max_lisp_eval_depth)
2728 if (max_lisp_eval_depth < 100)
2729 max_lisp_eval_depth = 100;
2730 if (lisp_eval_depth > max_lisp_eval_depth)
2731 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2734 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2736 maybe_gc ();
2738 if (debug_on_next_call)
2739 do_debug_on_call (Qlambda, count);
2741 check_cons_list ();
2743 original_fun = args[0];
2745 retry:
2747 /* Optimize for no indirection. */
2748 fun = original_fun;
2749 if (SYMBOLP (fun) && !NILP (fun)
2750 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2751 fun = indirect_function (fun);
2753 if (SUBRP (fun))
2754 val = funcall_subr (XSUBR (fun), numargs, args + 1);
2755 else if (COMPILEDP (fun))
2756 val = funcall_lambda (fun, numargs, args + 1);
2757 else
2759 if (NILP (fun))
2760 xsignal1 (Qvoid_function, original_fun);
2761 if (!CONSP (fun))
2762 xsignal1 (Qinvalid_function, original_fun);
2763 funcar = XCAR (fun);
2764 if (!SYMBOLP (funcar))
2765 xsignal1 (Qinvalid_function, original_fun);
2766 if (EQ (funcar, Qlambda)
2767 || EQ (funcar, Qclosure))
2768 val = funcall_lambda (fun, numargs, args + 1);
2769 else if (EQ (funcar, Qautoload))
2771 Fautoload_do_load (fun, original_fun, Qnil);
2772 check_cons_list ();
2773 goto retry;
2775 else
2776 xsignal1 (Qinvalid_function, original_fun);
2778 check_cons_list ();
2779 lisp_eval_depth--;
2780 if (backtrace_debug_on_exit (specpdl + count))
2781 val = call_debugger (list2 (Qexit, val));
2782 specpdl_ptr--;
2783 return val;
2787 /* Apply a C subroutine SUBR to the NUMARGS evaluated arguments in ARG_VECTOR
2788 and return the result of evaluation. */
2790 Lisp_Object
2791 funcall_subr (struct Lisp_Subr *subr, ptrdiff_t numargs, Lisp_Object *args)
2793 if (numargs < subr->min_args
2794 || (subr->max_args >= 0 && subr->max_args < numargs))
2796 Lisp_Object fun;
2797 XSETSUBR (fun, subr);
2798 xsignal2 (Qwrong_number_of_arguments, fun, make_number (numargs));
2801 else if (subr->max_args == UNEVALLED)
2803 Lisp_Object fun;
2804 XSETSUBR (fun, subr);
2805 xsignal1 (Qinvalid_function, fun);
2808 else if (subr->max_args == MANY)
2809 return (subr->function.aMANY) (numargs, args);
2810 else
2812 Lisp_Object internal_argbuf[8];
2813 Lisp_Object *internal_args;
2814 if (subr->max_args > numargs)
2816 eassert (subr->max_args <= ARRAYELTS (internal_argbuf));
2817 internal_args = internal_argbuf;
2818 memcpy (internal_args, args, numargs * word_size);
2819 memclear (internal_args + numargs,
2820 (subr->max_args - numargs) * word_size);
2822 else
2823 internal_args = args;
2824 switch (subr->max_args)
2826 case 0:
2827 return (subr->function.a0 ());
2828 case 1:
2829 return (subr->function.a1 (internal_args[0]));
2830 case 2:
2831 return (subr->function.a2
2832 (internal_args[0], internal_args[1]));
2833 case 3:
2834 return (subr->function.a3
2835 (internal_args[0], internal_args[1], internal_args[2]));
2836 case 4:
2837 return (subr->function.a4
2838 (internal_args[0], internal_args[1], internal_args[2],
2839 internal_args[3]));
2840 case 5:
2841 return (subr->function.a5
2842 (internal_args[0], internal_args[1], internal_args[2],
2843 internal_args[3], internal_args[4]));
2844 case 6:
2845 return (subr->function.a6
2846 (internal_args[0], internal_args[1], internal_args[2],
2847 internal_args[3], internal_args[4], internal_args[5]));
2848 case 7:
2849 return (subr->function.a7
2850 (internal_args[0], internal_args[1], internal_args[2],
2851 internal_args[3], internal_args[4], internal_args[5],
2852 internal_args[6]));
2853 case 8:
2854 return (subr->function.a8
2855 (internal_args[0], internal_args[1], internal_args[2],
2856 internal_args[3], internal_args[4], internal_args[5],
2857 internal_args[6], internal_args[7]));
2859 default:
2861 /* If a subr takes more than 8 arguments without using MANY
2862 or UNEVALLED, we need to extend this function to support it.
2863 Until this is done, there is no way to call the function. */
2864 emacs_abort ();
2869 static Lisp_Object
2870 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2872 Lisp_Object args_left;
2873 ptrdiff_t i;
2874 EMACS_INT numargs;
2875 Lisp_Object *arg_vector;
2876 Lisp_Object tem;
2877 USE_SAFE_ALLOCA;
2879 numargs = XFASTINT (Flength (args));
2880 SAFE_ALLOCA_LISP (arg_vector, numargs);
2881 args_left = args;
2883 for (i = 0; i < numargs; )
2885 tem = Fcar (args_left), args_left = Fcdr (args_left);
2886 tem = eval_sub (tem);
2887 arg_vector[i++] = tem;
2890 set_backtrace_args (specpdl + count, arg_vector, i);
2891 tem = funcall_lambda (fun, numargs, arg_vector);
2893 check_cons_list ();
2894 lisp_eval_depth--;
2895 /* Do the debug-on-exit now, while arg_vector still exists. */
2896 if (backtrace_debug_on_exit (specpdl + count))
2897 tem = call_debugger (list2 (Qexit, tem));
2898 SAFE_FREE ();
2899 specpdl_ptr--;
2900 return tem;
2903 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2904 and return the result of evaluation.
2905 FUN must be either a lambda-expression or a compiled-code object. */
2907 static Lisp_Object
2908 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2909 register Lisp_Object *arg_vector)
2911 Lisp_Object val, syms_left, next, lexenv;
2912 ptrdiff_t count = SPECPDL_INDEX ();
2913 ptrdiff_t i;
2914 bool optional, rest;
2916 if (CONSP (fun))
2918 if (EQ (XCAR (fun), Qclosure))
2920 Lisp_Object cdr = XCDR (fun); /* Drop `closure'. */
2921 if (! CONSP (cdr))
2922 xsignal1 (Qinvalid_function, fun);
2923 fun = cdr;
2924 lexenv = XCAR (fun);
2926 else
2927 lexenv = Qnil;
2928 syms_left = XCDR (fun);
2929 if (CONSP (syms_left))
2930 syms_left = XCAR (syms_left);
2931 else
2932 xsignal1 (Qinvalid_function, fun);
2934 else if (COMPILEDP (fun))
2936 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2937 if (size <= COMPILED_STACK_DEPTH)
2938 xsignal1 (Qinvalid_function, fun);
2939 syms_left = AREF (fun, COMPILED_ARGLIST);
2940 if (INTEGERP (syms_left))
2941 /* A byte-code object with an integer args template means we
2942 shouldn't bind any arguments, instead just call the byte-code
2943 interpreter directly; it will push arguments as necessary.
2945 Byte-code objects with a nil args template (the default)
2946 have dynamically-bound arguments, and use the
2947 argument-binding code below instead (as do all interpreted
2948 functions, even lexically bound ones). */
2950 /* If we have not actually read the bytecode string
2951 and constants vector yet, fetch them from the file. */
2952 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2953 Ffetch_bytecode (fun);
2954 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2955 AREF (fun, COMPILED_CONSTANTS),
2956 AREF (fun, COMPILED_STACK_DEPTH),
2957 syms_left,
2958 nargs, arg_vector);
2960 lexenv = Qnil;
2962 else
2963 emacs_abort ();
2965 i = optional = rest = 0;
2966 bool previous_optional_or_rest = false;
2967 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2969 maybe_quit ();
2971 next = XCAR (syms_left);
2972 if (!SYMBOLP (next))
2973 xsignal1 (Qinvalid_function, fun);
2975 if (EQ (next, Qand_rest))
2977 if (rest || previous_optional_or_rest)
2978 xsignal1 (Qinvalid_function, fun);
2979 rest = 1;
2980 previous_optional_or_rest = true;
2982 else if (EQ (next, Qand_optional))
2984 if (optional || rest || previous_optional_or_rest)
2985 xsignal1 (Qinvalid_function, fun);
2986 optional = 1;
2987 previous_optional_or_rest = true;
2989 else
2991 Lisp_Object arg;
2992 if (rest)
2994 arg = Flist (nargs - i, &arg_vector[i]);
2995 i = nargs;
2997 else if (i < nargs)
2998 arg = arg_vector[i++];
2999 else if (!optional)
3000 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
3001 else
3002 arg = Qnil;
3004 /* Bind the argument. */
3005 if (!NILP (lexenv) && SYMBOLP (next))
3006 /* Lexically bind NEXT by adding it to the lexenv alist. */
3007 lexenv = Fcons (Fcons (next, arg), lexenv);
3008 else
3009 /* Dynamically bind NEXT. */
3010 specbind (next, arg);
3011 previous_optional_or_rest = false;
3015 if (!NILP (syms_left) || previous_optional_or_rest)
3016 xsignal1 (Qinvalid_function, fun);
3017 else if (i < nargs)
3018 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
3020 if (!EQ (lexenv, Vinternal_interpreter_environment))
3021 /* Instantiate a new lexical environment. */
3022 specbind (Qinternal_interpreter_environment, lexenv);
3024 if (CONSP (fun))
3025 val = Fprogn (XCDR (XCDR (fun)));
3026 else
3028 /* If we have not actually read the bytecode string
3029 and constants vector yet, fetch them from the file. */
3030 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
3031 Ffetch_bytecode (fun);
3032 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
3033 AREF (fun, COMPILED_CONSTANTS),
3034 AREF (fun, COMPILED_STACK_DEPTH),
3035 Qnil, 0, 0);
3038 return unbind_to (count, val);
3041 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
3042 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
3043 FUNCTION must be a function of some kind.
3044 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
3045 of args. MAX is the maximum number, or the symbol `many', for a
3046 function with `&rest' args, or `unevalled' for a special form. */)
3047 (Lisp_Object function)
3049 Lisp_Object original;
3050 Lisp_Object funcar;
3051 Lisp_Object result;
3053 original = function;
3055 retry:
3057 /* Optimize for no indirection. */
3058 function = original;
3059 if (SYMBOLP (function) && !NILP (function))
3061 function = XSYMBOL (function)->function;
3062 if (SYMBOLP (function))
3063 function = indirect_function (function);
3066 if (CONSP (function) && EQ (XCAR (function), Qmacro))
3067 function = XCDR (function);
3069 if (SUBRP (function))
3070 result = Fsubr_arity (function);
3071 else if (COMPILEDP (function))
3072 result = lambda_arity (function);
3073 else
3075 if (NILP (function))
3076 xsignal1 (Qvoid_function, original);
3077 if (!CONSP (function))
3078 xsignal1 (Qinvalid_function, original);
3079 funcar = XCAR (function);
3080 if (!SYMBOLP (funcar))
3081 xsignal1 (Qinvalid_function, original);
3082 if (EQ (funcar, Qlambda)
3083 || EQ (funcar, Qclosure))
3084 result = lambda_arity (function);
3085 else if (EQ (funcar, Qautoload))
3087 Fautoload_do_load (function, original, Qnil);
3088 goto retry;
3090 else
3091 xsignal1 (Qinvalid_function, original);
3093 return result;
3096 /* FUN must be either a lambda-expression or a compiled-code object. */
3097 static Lisp_Object
3098 lambda_arity (Lisp_Object fun)
3100 Lisp_Object syms_left;
3102 if (CONSP (fun))
3104 if (EQ (XCAR (fun), Qclosure))
3106 fun = XCDR (fun); /* Drop `closure'. */
3107 CHECK_CONS (fun);
3109 syms_left = XCDR (fun);
3110 if (CONSP (syms_left))
3111 syms_left = XCAR (syms_left);
3112 else
3113 xsignal1 (Qinvalid_function, fun);
3115 else if (COMPILEDP (fun))
3117 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3118 if (size <= COMPILED_STACK_DEPTH)
3119 xsignal1 (Qinvalid_function, fun);
3120 syms_left = AREF (fun, COMPILED_ARGLIST);
3121 if (INTEGERP (syms_left))
3122 return get_byte_code_arity (syms_left);
3124 else
3125 emacs_abort ();
3127 EMACS_INT minargs = 0, maxargs = 0;
3128 bool optional = false;
3129 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3131 Lisp_Object next = XCAR (syms_left);
3132 if (!SYMBOLP (next))
3133 xsignal1 (Qinvalid_function, fun);
3135 if (EQ (next, Qand_rest))
3136 return Fcons (make_number (minargs), Qmany);
3137 else if (EQ (next, Qand_optional))
3138 optional = true;
3139 else
3141 if (!optional)
3142 minargs++;
3143 maxargs++;
3147 if (!NILP (syms_left))
3148 xsignal1 (Qinvalid_function, fun);
3150 return Fcons (make_number (minargs), make_number (maxargs));
3153 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3154 1, 1, 0,
3155 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3156 (Lisp_Object object)
3158 Lisp_Object tem;
3160 if (COMPILEDP (object))
3162 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3163 if (size <= COMPILED_STACK_DEPTH)
3164 xsignal1 (Qinvalid_function, object);
3165 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3167 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3168 if (!CONSP (tem))
3170 tem = AREF (object, COMPILED_BYTECODE);
3171 if (CONSP (tem) && STRINGP (XCAR (tem)))
3172 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3173 else
3174 error ("Invalid byte code");
3176 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3177 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3180 return object;
3183 /* Return true if SYMBOL currently has a let-binding
3184 which was made in the buffer that is now current. */
3186 bool
3187 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3189 union specbinding *p;
3190 Lisp_Object buf = Fcurrent_buffer ();
3192 for (p = specpdl_ptr; p > specpdl; )
3193 if ((--p)->kind > SPECPDL_LET)
3195 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3196 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3197 if (symbol == let_bound_symbol
3198 && EQ (specpdl_where (p), buf))
3199 return 1;
3202 return 0;
3205 bool
3206 let_shadows_global_binding_p (Lisp_Object symbol)
3208 union specbinding *p;
3210 for (p = specpdl_ptr; p > specpdl; )
3211 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3212 return 1;
3214 return 0;
3217 static void
3218 do_specbind (struct Lisp_Symbol *sym, union specbinding *bind,
3219 Lisp_Object value, enum Set_Internal_Bind bindflag)
3221 switch (sym->redirect)
3223 case SYMBOL_PLAINVAL:
3224 if (!sym->trapped_write)
3225 SET_SYMBOL_VAL (sym, value);
3226 else
3227 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3228 break;
3230 case SYMBOL_FORWARDED:
3231 if (BUFFER_OBJFWDP (SYMBOL_FWD (sym))
3232 && specpdl_kind (bind) == SPECPDL_LET_DEFAULT)
3234 set_default_internal (specpdl_symbol (bind), value, bindflag);
3235 return;
3237 /* FALLTHROUGH */
3238 case SYMBOL_LOCALIZED:
3239 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3240 break;
3242 default:
3243 emacs_abort ();
3247 /* `specpdl_ptr' describes which variable is
3248 let-bound, so it can be properly undone when we unbind_to.
3249 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3250 - SYMBOL is the variable being bound. Note that it should not be
3251 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3252 to record V2 here).
3253 - WHERE tells us in which buffer the binding took place.
3254 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3255 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3256 i.e. bindings to the default value of a variable which can be
3257 buffer-local. */
3259 void
3260 specbind (Lisp_Object symbol, Lisp_Object value)
3262 struct Lisp_Symbol *sym;
3264 CHECK_SYMBOL (symbol);
3265 sym = XSYMBOL (symbol);
3267 start:
3268 switch (sym->redirect)
3270 case SYMBOL_VARALIAS:
3271 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3272 case SYMBOL_PLAINVAL:
3273 /* The most common case is that of a non-constant symbol with a
3274 trivial value. Make that as fast as we can. */
3275 specpdl_ptr->let.kind = SPECPDL_LET;
3276 specpdl_ptr->let.symbol = symbol;
3277 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3278 specpdl_ptr->let.saved_value = Qnil;
3279 grow_specpdl ();
3280 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3281 break;
3282 case SYMBOL_LOCALIZED:
3283 case SYMBOL_FORWARDED:
3285 Lisp_Object ovalue = find_symbol_value (symbol);
3286 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3287 specpdl_ptr->let.symbol = symbol;
3288 specpdl_ptr->let.old_value = ovalue;
3289 specpdl_ptr->let.where = Fcurrent_buffer ();
3290 specpdl_ptr->let.saved_value = Qnil;
3292 eassert (sym->redirect != SYMBOL_LOCALIZED
3293 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3295 if (sym->redirect == SYMBOL_LOCALIZED)
3297 if (!blv_found (SYMBOL_BLV (sym)))
3298 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3300 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3302 /* If SYMBOL is a per-buffer variable which doesn't have a
3303 buffer-local value here, make the `let' change the global
3304 value by changing the value of SYMBOL in all buffers not
3305 having their own value. This is consistent with what
3306 happens with other buffer-local variables. */
3307 if (NILP (Flocal_variable_p (symbol, Qnil)))
3309 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3310 grow_specpdl ();
3311 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3312 return;
3315 else
3316 specpdl_ptr->let.kind = SPECPDL_LET;
3318 grow_specpdl ();
3319 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3320 break;
3322 default: emacs_abort ();
3326 /* Push unwind-protect entries of various types. */
3328 void
3329 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3331 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3332 specpdl_ptr->unwind.func = function;
3333 specpdl_ptr->unwind.arg = arg;
3334 grow_specpdl ();
3337 void
3338 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3340 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3341 specpdl_ptr->unwind_ptr.func = function;
3342 specpdl_ptr->unwind_ptr.arg = arg;
3343 grow_specpdl ();
3346 void
3347 record_unwind_protect_int (void (*function) (int), int arg)
3349 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3350 specpdl_ptr->unwind_int.func = function;
3351 specpdl_ptr->unwind_int.arg = arg;
3352 grow_specpdl ();
3355 void
3356 record_unwind_protect_void (void (*function) (void))
3358 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3359 specpdl_ptr->unwind_void.func = function;
3360 grow_specpdl ();
3363 void
3364 rebind_for_thread_switch (void)
3366 union specbinding *bind;
3368 for (bind = specpdl; bind != specpdl_ptr; ++bind)
3370 if (bind->kind >= SPECPDL_LET)
3372 Lisp_Object value = specpdl_saved_value (bind);
3373 Lisp_Object sym = specpdl_symbol (bind);
3374 bind->let.saved_value = Qnil;
3375 do_specbind (XSYMBOL (sym), bind, value,
3376 SET_INTERNAL_THREAD_SWITCH);
3381 static void
3382 do_one_unbind (union specbinding *this_binding, bool unwinding,
3383 enum Set_Internal_Bind bindflag)
3385 eassert (unwinding || this_binding->kind >= SPECPDL_LET);
3386 switch (this_binding->kind)
3388 case SPECPDL_UNWIND:
3389 this_binding->unwind.func (this_binding->unwind.arg);
3390 break;
3391 case SPECPDL_UNWIND_PTR:
3392 this_binding->unwind_ptr.func (this_binding->unwind_ptr.arg);
3393 break;
3394 case SPECPDL_UNWIND_INT:
3395 this_binding->unwind_int.func (this_binding->unwind_int.arg);
3396 break;
3397 case SPECPDL_UNWIND_VOID:
3398 this_binding->unwind_void.func ();
3399 break;
3400 case SPECPDL_BACKTRACE:
3401 break;
3402 case SPECPDL_LET:
3403 { /* If variable has a trivial value (no forwarding), and isn't
3404 trapped, we can just set it. */
3405 Lisp_Object sym = specpdl_symbol (this_binding);
3406 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3408 if (XSYMBOL (sym)->trapped_write == SYMBOL_UNTRAPPED_WRITE)
3409 SET_SYMBOL_VAL (XSYMBOL (sym), specpdl_old_value (this_binding));
3410 else
3411 set_internal (sym, specpdl_old_value (this_binding),
3412 Qnil, bindflag);
3413 break;
3415 else
3416 { /* FALLTHROUGH!!
3417 NOTE: we only ever come here if make_local_foo was used for
3418 the first time on this var within this let. */
3421 case SPECPDL_LET_DEFAULT:
3422 set_default_internal (specpdl_symbol (this_binding),
3423 specpdl_old_value (this_binding),
3424 bindflag);
3425 break;
3426 case SPECPDL_LET_LOCAL:
3428 Lisp_Object symbol = specpdl_symbol (this_binding);
3429 Lisp_Object where = specpdl_where (this_binding);
3430 Lisp_Object old_value = specpdl_old_value (this_binding);
3431 eassert (BUFFERP (where));
3433 /* If this was a local binding, reset the value in the appropriate
3434 buffer, but only if that buffer's binding still exists. */
3435 if (!NILP (Flocal_variable_p (symbol, where)))
3436 set_internal (symbol, old_value, where, bindflag);
3438 break;
3442 static void
3443 do_nothing (void)
3446 /* Push an unwind-protect entry that does nothing, so that
3447 set_unwind_protect_ptr can overwrite it later. */
3449 void
3450 record_unwind_protect_nothing (void)
3452 record_unwind_protect_void (do_nothing);
3455 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3456 It need not be at the top of the stack. */
3458 void
3459 clear_unwind_protect (ptrdiff_t count)
3461 union specbinding *p = specpdl + count;
3462 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3463 p->unwind_void.func = do_nothing;
3466 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3467 It need not be at the top of the stack. Discard the entry's
3468 previous value without invoking it. */
3470 void
3471 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3472 Lisp_Object arg)
3474 union specbinding *p = specpdl + count;
3475 p->unwind.kind = SPECPDL_UNWIND;
3476 p->unwind.func = func;
3477 p->unwind.arg = arg;
3480 void
3481 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3483 union specbinding *p = specpdl + count;
3484 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3485 p->unwind_ptr.func = func;
3486 p->unwind_ptr.arg = arg;
3489 /* Pop and execute entries from the unwind-protect stack until the
3490 depth COUNT is reached. Return VALUE. */
3492 Lisp_Object
3493 unbind_to (ptrdiff_t count, Lisp_Object value)
3495 Lisp_Object quitf = Vquit_flag;
3497 Vquit_flag = Qnil;
3499 while (specpdl_ptr != specpdl + count)
3501 /* Copy the binding, and decrement specpdl_ptr, before we do
3502 the work to unbind it. We decrement first
3503 so that an error in unbinding won't try to unbind
3504 the same entry again, and we copy the binding first
3505 in case more bindings are made during some of the code we run. */
3507 union specbinding this_binding;
3508 this_binding = *--specpdl_ptr;
3510 do_one_unbind (&this_binding, true, SET_INTERNAL_UNBIND);
3513 if (NILP (Vquit_flag) && !NILP (quitf))
3514 Vquit_flag = quitf;
3516 return value;
3519 void
3520 unbind_for_thread_switch (struct thread_state *thr)
3522 union specbinding *bind;
3524 for (bind = thr->m_specpdl_ptr; bind > thr->m_specpdl;)
3526 if ((--bind)->kind >= SPECPDL_LET)
3528 Lisp_Object sym = specpdl_symbol (bind);
3529 bind->let.saved_value = find_symbol_value (sym);
3530 do_one_unbind (bind, false, SET_INTERNAL_THREAD_SWITCH);
3535 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3536 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3537 A special variable is one that will be bound dynamically, even in a
3538 context where binding is lexical by default. */)
3539 (Lisp_Object symbol)
3541 CHECK_SYMBOL (symbol);
3542 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3546 static union specbinding *
3547 get_backtrace_starting_at (Lisp_Object base)
3549 union specbinding *pdl = backtrace_top ();
3551 if (!NILP (base))
3552 { /* Skip up to `base'. */
3553 base = Findirect_function (base, Qt);
3554 while (backtrace_p (pdl)
3555 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3556 pdl = backtrace_next (pdl);
3559 return pdl;
3562 static union specbinding *
3563 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3565 register EMACS_INT i;
3567 CHECK_NATNUM (nframes);
3568 union specbinding *pdl = get_backtrace_starting_at (base);
3570 /* Find the frame requested. */
3571 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3572 pdl = backtrace_next (pdl);
3574 return pdl;
3577 static Lisp_Object
3578 backtrace_frame_apply (Lisp_Object function, union specbinding *pdl)
3580 if (!backtrace_p (pdl))
3581 return Qnil;
3583 Lisp_Object flags = Qnil;
3584 if (backtrace_debug_on_exit (pdl))
3585 flags = Fcons (QCdebug_on_exit, Fcons (Qt, Qnil));
3587 if (backtrace_nargs (pdl) == UNEVALLED)
3588 return call4 (function, Qnil, backtrace_function (pdl), *backtrace_args (pdl), flags);
3589 else
3591 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3592 return call4 (function, Qt, backtrace_function (pdl), tem, flags);
3596 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3597 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3598 The debugger is entered when that frame exits, if the flag is non-nil. */)
3599 (Lisp_Object level, Lisp_Object flag)
3601 CHECK_NUMBER (level);
3602 union specbinding *pdl = get_backtrace_frame(level, Qnil);
3604 if (backtrace_p (pdl))
3605 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3607 return flag;
3610 DEFUN ("mapbacktrace", Fmapbacktrace, Smapbacktrace, 1, 2, 0,
3611 doc: /* Call FUNCTION for each frame in backtrace.
3612 If BASE is non-nil, it should be a function and iteration will start
3613 from its nearest activation frame.
3614 FUNCTION is called with 4 arguments: EVALD, FUNC, ARGS, and FLAGS. If
3615 a frame has not evaluated its arguments yet or is a special form,
3616 EVALD is nil and ARGS is a list of forms. If a frame has evaluated
3617 its arguments and called its function already, EVALD is t and ARGS is
3618 a list of values.
3619 FLAGS is a plist of properties of the current frame: currently, the
3620 only supported property is :debug-on-exit. `mapbacktrace' always
3621 returns nil. */)
3622 (Lisp_Object function, Lisp_Object base)
3624 union specbinding *pdl = get_backtrace_starting_at (base);
3626 while (backtrace_p (pdl))
3628 backtrace_frame_apply (function, pdl);
3629 pdl = backtrace_next (pdl);
3632 return Qnil;
3635 DEFUN ("backtrace-frame--internal", Fbacktrace_frame_internal,
3636 Sbacktrace_frame_internal, 3, 3, NULL,
3637 doc: /* Call FUNCTION on stack frame NFRAMES away from BASE.
3638 Return the result of FUNCTION, or nil if no matching frame could be found. */)
3639 (Lisp_Object function, Lisp_Object nframes, Lisp_Object base)
3641 return backtrace_frame_apply (function, get_backtrace_frame (nframes, base));
3644 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3645 the specpdl stack, and then rewind them. We store the pre-unwind values
3646 directly in the pre-existing specpdl elements (i.e. we swap the current
3647 value and the old value stored in the specpdl), kind of like the inplace
3648 pointer-reversal trick. As it turns out, the rewind does the same as the
3649 unwind, except it starts from the other end of the specpdl stack, so we use
3650 the same function for both unwind and rewind. */
3651 static void
3652 backtrace_eval_unrewind (int distance)
3654 union specbinding *tmp = specpdl_ptr;
3655 int step = -1;
3656 if (distance < 0)
3657 { /* It's a rewind rather than unwind. */
3658 tmp += distance - 1;
3659 step = 1;
3660 distance = -distance;
3663 for (; distance > 0; distance--)
3665 tmp += step;
3666 switch (tmp->kind)
3668 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3669 unwind_protect, but the problem is that we don't know how to
3670 rewind them afterwards. */
3671 case SPECPDL_UNWIND:
3673 Lisp_Object oldarg = tmp->unwind.arg;
3674 if (tmp->unwind.func == set_buffer_if_live)
3675 tmp->unwind.arg = Fcurrent_buffer ();
3676 else if (tmp->unwind.func == save_excursion_restore)
3677 tmp->unwind.arg = save_excursion_save ();
3678 else
3679 break;
3680 tmp->unwind.func (oldarg);
3681 break;
3684 case SPECPDL_UNWIND_PTR:
3685 case SPECPDL_UNWIND_INT:
3686 case SPECPDL_UNWIND_VOID:
3687 case SPECPDL_BACKTRACE:
3688 break;
3689 case SPECPDL_LET:
3690 { /* If variable has a trivial value (no forwarding), we can
3691 just set it. No need to check for constant symbols here,
3692 since that was already done by specbind. */
3693 Lisp_Object sym = specpdl_symbol (tmp);
3694 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3696 Lisp_Object old_value = specpdl_old_value (tmp);
3697 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3698 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3699 break;
3701 else
3702 { /* FALLTHROUGH!!
3703 NOTE: we only ever come here if make_local_foo was used for
3704 the first time on this var within this let. */
3707 case SPECPDL_LET_DEFAULT:
3709 Lisp_Object sym = specpdl_symbol (tmp);
3710 Lisp_Object old_value = specpdl_old_value (tmp);
3711 set_specpdl_old_value (tmp, Fdefault_value (sym));
3712 Fset_default (sym, old_value);
3714 break;
3715 case SPECPDL_LET_LOCAL:
3717 Lisp_Object symbol = specpdl_symbol (tmp);
3718 Lisp_Object where = specpdl_where (tmp);
3719 Lisp_Object old_value = specpdl_old_value (tmp);
3720 eassert (BUFFERP (where));
3722 /* If this was a local binding, reset the value in the appropriate
3723 buffer, but only if that buffer's binding still exists. */
3724 if (!NILP (Flocal_variable_p (symbol, where)))
3726 set_specpdl_old_value
3727 (tmp, Fbuffer_local_value (symbol, where));
3728 set_internal (symbol, old_value, where, SET_INTERNAL_UNBIND);
3731 break;
3736 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3737 doc: /* Evaluate EXP in the context of some activation frame.
3738 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3739 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3741 union specbinding *pdl = get_backtrace_frame (nframes, base);
3742 ptrdiff_t count = SPECPDL_INDEX ();
3743 ptrdiff_t distance = specpdl_ptr - pdl;
3744 eassert (distance >= 0);
3746 if (!backtrace_p (pdl))
3747 error ("Activation frame not found!");
3749 backtrace_eval_unrewind (distance);
3750 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3752 /* Use eval_sub rather than Feval since the main motivation behind
3753 backtrace-eval is to be able to get/set the value of lexical variables
3754 from the debugger. */
3755 return unbind_to (count, eval_sub (exp));
3758 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3759 doc: /* Return names and values of local variables of a stack frame.
3760 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3761 (Lisp_Object nframes, Lisp_Object base)
3763 union specbinding *frame = get_backtrace_frame (nframes, base);
3764 union specbinding *prevframe
3765 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3766 ptrdiff_t distance = specpdl_ptr - frame;
3767 Lisp_Object result = Qnil;
3768 eassert (distance >= 0);
3770 if (!backtrace_p (prevframe))
3771 error ("Activation frame not found!");
3772 if (!backtrace_p (frame))
3773 error ("Activation frame not found!");
3775 /* The specpdl entries normally contain the symbol being bound along with its
3776 `old_value', so it can be restored. The new value to which it is bound is
3777 available in one of two places: either in the current value of the
3778 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3779 next specpdl entry for it.
3780 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3781 and "new value", so we abuse it here, to fetch the new value.
3782 It's ugly (we'd rather not modify global data) and a bit inefficient,
3783 but it does the job for now. */
3784 backtrace_eval_unrewind (distance);
3786 /* Grab values. */
3788 union specbinding *tmp = prevframe;
3789 for (; tmp > frame; tmp--)
3791 switch (tmp->kind)
3793 case SPECPDL_LET:
3794 case SPECPDL_LET_DEFAULT:
3795 case SPECPDL_LET_LOCAL:
3797 Lisp_Object sym = specpdl_symbol (tmp);
3798 Lisp_Object val = specpdl_old_value (tmp);
3799 if (EQ (sym, Qinternal_interpreter_environment))
3801 Lisp_Object env = val;
3802 for (; CONSP (env); env = XCDR (env))
3804 Lisp_Object binding = XCAR (env);
3805 if (CONSP (binding))
3806 result = Fcons (Fcons (XCAR (binding),
3807 XCDR (binding)),
3808 result);
3811 else
3812 result = Fcons (Fcons (sym, val), result);
3814 break;
3816 case SPECPDL_UNWIND:
3817 case SPECPDL_UNWIND_PTR:
3818 case SPECPDL_UNWIND_INT:
3819 case SPECPDL_UNWIND_VOID:
3820 case SPECPDL_BACKTRACE:
3821 break;
3823 default:
3824 emacs_abort ();
3829 /* Restore values from specpdl to original place. */
3830 backtrace_eval_unrewind (-distance);
3832 return result;
3836 void
3837 mark_specpdl (union specbinding *first, union specbinding *ptr)
3839 union specbinding *pdl;
3840 for (pdl = first; pdl != ptr; pdl++)
3842 switch (pdl->kind)
3844 case SPECPDL_UNWIND:
3845 mark_object (specpdl_arg (pdl));
3846 break;
3848 case SPECPDL_BACKTRACE:
3850 ptrdiff_t nargs = backtrace_nargs (pdl);
3851 mark_object (backtrace_function (pdl));
3852 if (nargs == UNEVALLED)
3853 nargs = 1;
3854 while (nargs--)
3855 mark_object (backtrace_args (pdl)[nargs]);
3857 break;
3859 case SPECPDL_LET_DEFAULT:
3860 case SPECPDL_LET_LOCAL:
3861 mark_object (specpdl_where (pdl));
3862 /* Fall through. */
3863 case SPECPDL_LET:
3864 mark_object (specpdl_symbol (pdl));
3865 mark_object (specpdl_old_value (pdl));
3866 mark_object (specpdl_saved_value (pdl));
3867 break;
3869 case SPECPDL_UNWIND_PTR:
3870 case SPECPDL_UNWIND_INT:
3871 case SPECPDL_UNWIND_VOID:
3872 break;
3874 default:
3875 emacs_abort ();
3880 void
3881 get_backtrace (Lisp_Object array)
3883 union specbinding *pdl = backtrace_next (backtrace_top ());
3884 ptrdiff_t i = 0, asize = ASIZE (array);
3886 /* Copy the backtrace contents into working memory. */
3887 for (; i < asize; i++)
3889 if (backtrace_p (pdl))
3891 ASET (array, i, backtrace_function (pdl));
3892 pdl = backtrace_next (pdl);
3894 else
3895 ASET (array, i, Qnil);
3899 Lisp_Object backtrace_top_function (void)
3901 union specbinding *pdl = backtrace_top ();
3902 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3905 void
3906 syms_of_eval (void)
3908 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3909 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3910 If Lisp code tries to increase the total number past this amount,
3911 an error is signaled.
3912 You can safely use a value considerably larger than the default value,
3913 if that proves inconveniently small. However, if you increase it too far,
3914 Emacs could run out of memory trying to make the stack bigger.
3915 Note that this limit may be silently increased by the debugger
3916 if `debug-on-error' or `debug-on-quit' is set. */);
3918 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3919 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3921 This limit serves to catch infinite recursions for you before they cause
3922 actual stack overflow in C, which would be fatal for Emacs.
3923 You can safely make it considerably larger than its default value,
3924 if that proves inconveniently small. However, if you increase it too far,
3925 Emacs could overflow the real C stack, and crash. */);
3927 DEFVAR_LISP ("quit-flag", Vquit_flag,
3928 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3929 If the value is t, that means do an ordinary quit.
3930 If the value equals `throw-on-input', that means quit by throwing
3931 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3932 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3933 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3934 Vquit_flag = Qnil;
3936 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3937 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3938 Note that `quit-flag' will still be set by typing C-g,
3939 so a quit will be signaled as soon as `inhibit-quit' is nil.
3940 To prevent this happening, set `quit-flag' to nil
3941 before making `inhibit-quit' nil. */);
3942 Vinhibit_quit = Qnil;
3944 DEFSYM (Qsetq, "setq");
3945 DEFSYM (Qinhibit_quit, "inhibit-quit");
3946 DEFSYM (Qautoload, "autoload");
3947 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3948 DEFSYM (Qmacro, "macro");
3950 /* Note that the process handling also uses Qexit, but we don't want
3951 to staticpro it twice, so we just do it here. */
3952 DEFSYM (Qexit, "exit");
3954 DEFSYM (Qinteractive, "interactive");
3955 DEFSYM (Qcommandp, "commandp");
3956 DEFSYM (Qand_rest, "&rest");
3957 DEFSYM (Qand_optional, "&optional");
3958 DEFSYM (Qclosure, "closure");
3959 DEFSYM (QCdocumentation, ":documentation");
3960 DEFSYM (Qdebug, "debug");
3962 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3963 doc: /* Non-nil means never enter the debugger.
3964 Normally set while the debugger is already active, to avoid recursive
3965 invocations. */);
3966 Vinhibit_debugger = Qnil;
3968 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3969 doc: /* Non-nil means enter debugger if an error is signaled.
3970 Does not apply to errors handled by `condition-case' or those
3971 matched by `debug-ignored-errors'.
3972 If the value is a list, an error only means to enter the debugger
3973 if one of its condition symbols appears in the list.
3974 When you evaluate an expression interactively, this variable
3975 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3976 The command `toggle-debug-on-error' toggles this.
3977 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3978 Vdebug_on_error = Qnil;
3980 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3981 doc: /* List of errors for which the debugger should not be called.
3982 Each element may be a condition-name or a regexp that matches error messages.
3983 If any element applies to a given error, that error skips the debugger
3984 and just returns to top level.
3985 This overrides the variable `debug-on-error'.
3986 It does not apply to errors handled by `condition-case'. */);
3987 Vdebug_ignored_errors = Qnil;
3989 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3990 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3991 Does not apply if quit is handled by a `condition-case'. */);
3992 debug_on_quit = 0;
3994 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3995 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3997 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3998 doc: /* Non-nil means debugger may continue execution.
3999 This is nil when the debugger is called under circumstances where it
4000 might not be safe to continue. */);
4001 debugger_may_continue = 1;
4003 DEFVAR_BOOL ("debugger-stack-frame-as-list", debugger_stack_frame_as_list,
4004 doc: /* Non-nil means display call stack frames as lists. */);
4005 debugger_stack_frame_as_list = 0;
4007 DEFVAR_LISP ("debugger", Vdebugger,
4008 doc: /* Function to call to invoke debugger.
4009 If due to frame exit, args are `exit' and the value being returned;
4010 this function's value will be returned instead of that.
4011 If due to error, args are `error' and a list of the args to `signal'.
4012 If due to `apply' or `funcall' entry, one arg, `lambda'.
4013 If due to `eval' entry, one arg, t. */);
4014 Vdebugger = Qnil;
4016 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
4017 doc: /* If non-nil, this is a function for `signal' to call.
4018 It receives the same arguments that `signal' was given.
4019 The Edebug package uses this to regain control. */);
4020 Vsignal_hook_function = Qnil;
4022 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
4023 doc: /* Non-nil means call the debugger regardless of condition handlers.
4024 Note that `debug-on-error', `debug-on-quit' and friends
4025 still determine whether to handle the particular condition. */);
4026 Vdebug_on_signal = Qnil;
4028 /* When lexical binding is being used,
4029 Vinternal_interpreter_environment is non-nil, and contains an alist
4030 of lexically-bound variable, or (t), indicating an empty
4031 environment. The lisp name of this variable would be
4032 `internal-interpreter-environment' if it weren't hidden.
4033 Every element of this list can be either a cons (VAR . VAL)
4034 specifying a lexical binding, or a single symbol VAR indicating
4035 that this variable should use dynamic scoping. */
4036 DEFSYM (Qinternal_interpreter_environment,
4037 "internal-interpreter-environment");
4038 DEFVAR_LISP ("internal-interpreter-environment",
4039 Vinternal_interpreter_environment,
4040 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
4041 When lexical binding is not being used, this variable is nil.
4042 A value of `(t)' indicates an empty environment, otherwise it is an
4043 alist of active lexical bindings. */);
4044 Vinternal_interpreter_environment = Qnil;
4045 /* Don't export this variable to Elisp, so no one can mess with it
4046 (Just imagine if someone makes it buffer-local). */
4047 Funintern (Qinternal_interpreter_environment, Qnil);
4049 Vrun_hooks = intern_c_string ("run-hooks");
4050 staticpro (&Vrun_hooks);
4052 staticpro (&Vautoload_queue);
4053 Vautoload_queue = Qnil;
4054 staticpro (&Vsignaling_function);
4055 Vsignaling_function = Qnil;
4057 inhibit_lisp_code = Qnil;
4059 defsubr (&Sor);
4060 defsubr (&Sand);
4061 defsubr (&Sif);
4062 defsubr (&Scond);
4063 defsubr (&Sprogn);
4064 defsubr (&Sprog1);
4065 defsubr (&Sprog2);
4066 defsubr (&Ssetq);
4067 defsubr (&Squote);
4068 defsubr (&Sfunction);
4069 defsubr (&Sdefault_toplevel_value);
4070 defsubr (&Sset_default_toplevel_value);
4071 defsubr (&Sdefvar);
4072 defsubr (&Sdefvaralias);
4073 DEFSYM (Qdefvaralias, "defvaralias");
4074 defsubr (&Sdefconst);
4075 defsubr (&Smake_var_non_special);
4076 defsubr (&Slet);
4077 defsubr (&SletX);
4078 defsubr (&Swhile);
4079 defsubr (&Smacroexpand);
4080 defsubr (&Scatch);
4081 defsubr (&Sthrow);
4082 defsubr (&Sunwind_protect);
4083 defsubr (&Scondition_case);
4084 defsubr (&Ssignal);
4085 defsubr (&Scommandp);
4086 defsubr (&Sautoload);
4087 defsubr (&Sautoload_do_load);
4088 defsubr (&Seval);
4089 defsubr (&Sapply);
4090 defsubr (&Sfuncall);
4091 defsubr (&Sfunc_arity);
4092 defsubr (&Srun_hooks);
4093 defsubr (&Srun_hook_with_args);
4094 defsubr (&Srun_hook_with_args_until_success);
4095 defsubr (&Srun_hook_with_args_until_failure);
4096 defsubr (&Srun_hook_wrapped);
4097 defsubr (&Sfetch_bytecode);
4098 defsubr (&Sbacktrace_debug);
4099 DEFSYM (QCdebug_on_exit, ":debug-on-exit");
4100 defsubr (&Smapbacktrace);
4101 defsubr (&Sbacktrace_frame_internal);
4102 defsubr (&Sbacktrace_eval);
4103 defsubr (&Sbacktrace__locals);
4104 defsubr (&Sspecial_variable_p);
4105 defsubr (&Sfunctionp);