Clarify internal_catch etc.
[emacs.git] / src / eval.c
blobb1747387471dac6753b80f098b32a338815e2dab
1 /* Evaluator for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1987, 1993-1995, 1999-2016 Free Software Foundation,
4 Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h>
25 #include <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 varlist = XCAR (args);
860 while (CONSP (varlist))
862 QUIT;
864 elt = XCAR (varlist);
865 if (SYMBOLP (elt))
867 var = elt;
868 val = Qnil;
870 else if (! NILP (Fcdr (Fcdr (elt))))
871 signal_error ("`let' bindings can have only one value-form", elt);
872 else
874 var = Fcar (elt);
875 val = eval_sub (Fcar (Fcdr (elt)));
878 if (!NILP (lexenv) && SYMBOLP (var)
879 && !XSYMBOL (var)->declared_special
880 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
881 /* Lexically bind VAR by adding it to the interpreter's binding
882 alist. */
884 Lisp_Object newenv
885 = Fcons (Fcons (var, val), Vinternal_interpreter_environment);
886 if (EQ (Vinternal_interpreter_environment, lexenv))
887 /* Save the old lexical environment on the specpdl stack,
888 but only for the first lexical binding, since we'll never
889 need to revert to one of the intermediate ones. */
890 specbind (Qinternal_interpreter_environment, newenv);
891 else
892 Vinternal_interpreter_environment = newenv;
894 else
895 specbind (var, val);
897 varlist = XCDR (varlist);
900 val = Fprogn (XCDR (args));
901 return unbind_to (count, val);
904 DEFUN ("let", Flet, Slet, 1, UNEVALLED, 0,
905 doc: /* Bind variables according to VARLIST then eval BODY.
906 The value of the last form in BODY is returned.
907 Each element of VARLIST is a symbol (which is bound to nil)
908 or a list (SYMBOL VALUEFORM) (which binds SYMBOL to the value of VALUEFORM).
909 All the VALUEFORMs are evalled before any symbols are bound.
910 usage: (let VARLIST BODY...) */)
911 (Lisp_Object args)
913 Lisp_Object *temps, tem, lexenv;
914 Lisp_Object elt, varlist;
915 ptrdiff_t count = SPECPDL_INDEX ();
916 ptrdiff_t argnum;
917 USE_SAFE_ALLOCA;
919 varlist = XCAR (args);
921 /* Make space to hold the values to give the bound variables. */
922 elt = Flength (varlist);
923 SAFE_ALLOCA_LISP (temps, XFASTINT (elt));
925 /* Compute the values and store them in `temps'. */
927 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
929 QUIT;
930 elt = XCAR (varlist);
931 if (SYMBOLP (elt))
932 temps [argnum++] = Qnil;
933 else if (! NILP (Fcdr (Fcdr (elt))))
934 signal_error ("`let' bindings can have only one value-form", elt);
935 else
936 temps [argnum++] = eval_sub (Fcar (Fcdr (elt)));
939 lexenv = Vinternal_interpreter_environment;
941 varlist = XCAR (args);
942 for (argnum = 0; CONSP (varlist); varlist = XCDR (varlist))
944 Lisp_Object var;
946 elt = XCAR (varlist);
947 var = SYMBOLP (elt) ? elt : Fcar (elt);
948 tem = temps[argnum++];
950 if (!NILP (lexenv) && SYMBOLP (var)
951 && !XSYMBOL (var)->declared_special
952 && NILP (Fmemq (var, Vinternal_interpreter_environment)))
953 /* Lexically bind VAR by adding it to the lexenv alist. */
954 lexenv = Fcons (Fcons (var, tem), lexenv);
955 else
956 /* Dynamically bind VAR. */
957 specbind (var, tem);
960 if (!EQ (lexenv, Vinternal_interpreter_environment))
961 /* Instantiate a new lexical environment. */
962 specbind (Qinternal_interpreter_environment, lexenv);
964 elt = Fprogn (XCDR (args));
965 SAFE_FREE ();
966 return unbind_to (count, elt);
969 DEFUN ("while", Fwhile, Swhile, 1, UNEVALLED, 0,
970 doc: /* If TEST yields non-nil, eval BODY... and repeat.
971 The order of execution is thus TEST, BODY, TEST, BODY and so on
972 until TEST returns nil.
973 usage: (while TEST BODY...) */)
974 (Lisp_Object args)
976 Lisp_Object test, body;
978 test = XCAR (args);
979 body = XCDR (args);
980 while (!NILP (eval_sub (test)))
982 QUIT;
983 prog_ignore (body);
986 return Qnil;
989 DEFUN ("macroexpand", Fmacroexpand, Smacroexpand, 1, 2, 0,
990 doc: /* Return result of expanding macros at top level of FORM.
991 If FORM is not a macro call, it is returned unchanged.
992 Otherwise, the macro is expanded and the expansion is considered
993 in place of FORM. When a non-macro-call results, it is returned.
995 The second optional arg ENVIRONMENT specifies an environment of macro
996 definitions to shadow the loaded ones for use in file byte-compilation. */)
997 (Lisp_Object form, Lisp_Object environment)
999 /* With cleanups from Hallvard Furuseth. */
1000 register Lisp_Object expander, sym, def, tem;
1002 while (1)
1004 /* Come back here each time we expand a macro call,
1005 in case it expands into another macro call. */
1006 if (!CONSP (form))
1007 break;
1008 /* Set SYM, give DEF and TEM right values in case SYM is not a symbol. */
1009 def = sym = XCAR (form);
1010 tem = Qnil;
1011 /* Trace symbols aliases to other symbols
1012 until we get a symbol that is not an alias. */
1013 while (SYMBOLP (def))
1015 QUIT;
1016 sym = def;
1017 tem = Fassq (sym, environment);
1018 if (NILP (tem))
1020 def = XSYMBOL (sym)->function;
1021 if (!NILP (def))
1022 continue;
1024 break;
1026 /* Right now TEM is the result from SYM in ENVIRONMENT,
1027 and if TEM is nil then DEF is SYM's function definition. */
1028 if (NILP (tem))
1030 /* SYM is not mentioned in ENVIRONMENT.
1031 Look at its function definition. */
1032 def = Fautoload_do_load (def, sym, Qmacro);
1033 if (!CONSP (def))
1034 /* Not defined or definition not suitable. */
1035 break;
1036 if (!EQ (XCAR (def), Qmacro))
1037 break;
1038 else expander = XCDR (def);
1040 else
1042 expander = XCDR (tem);
1043 if (NILP (expander))
1044 break;
1047 Lisp_Object newform = apply1 (expander, XCDR (form));
1048 if (EQ (form, newform))
1049 break;
1050 else
1051 form = newform;
1054 return form;
1057 DEFUN ("catch", Fcatch, Scatch, 1, UNEVALLED, 0,
1058 doc: /* Eval BODY allowing nonlocal exits using `throw'.
1059 TAG is evalled to get the tag to use; it must not be nil.
1061 Then the BODY is executed.
1062 Within BODY, a call to `throw' with the same TAG exits BODY and this `catch'.
1063 If no throw happens, `catch' returns the value of the last BODY form.
1064 If a throw happens, it specifies the value to return from `catch'.
1065 usage: (catch TAG BODY...) */)
1066 (Lisp_Object args)
1068 Lisp_Object tag = eval_sub (XCAR (args));
1069 return internal_catch (tag, Fprogn, XCDR (args));
1072 /* Assert that E is true, but do not evaluate E. Use this instead of
1073 eassert (E) when E contains variables that might be clobbered by a
1074 longjmp. */
1076 #define clobbered_eassert(E) verify (sizeof (E) != 0)
1078 /* Set up a catch, then call C function FUNC on argument ARG.
1079 FUNC should return a Lisp_Object.
1080 This is how catches are done from within C code. */
1082 Lisp_Object
1083 internal_catch (Lisp_Object tag,
1084 Lisp_Object (*func) (Lisp_Object), Lisp_Object arg)
1086 /* This structure is made part of the chain `catchlist'. */
1087 struct handler *c = push_handler (tag, CATCHER);
1089 /* Call FUNC. */
1090 if (! sys_setjmp (c->jmp))
1092 Lisp_Object val = func (arg);
1093 eassert (handlerlist == c);
1094 handlerlist = c->next;
1095 return val;
1097 else
1098 { /* Throw works by a longjmp that comes right here. */
1099 Lisp_Object val = handlerlist->val;
1100 clobbered_eassert (handlerlist == c);
1101 handlerlist = handlerlist->next;
1102 return val;
1106 /* Unwind the specbind, catch, and handler stacks back to CATCH, and
1107 jump to that CATCH, returning VALUE as the value of that catch.
1109 This is the guts of Fthrow and Fsignal; they differ only in the way
1110 they choose the catch tag to throw to. A catch tag for a
1111 condition-case form has a TAG of Qnil.
1113 Before each catch is discarded, unbind all special bindings and
1114 execute all unwind-protect clauses made above that catch. Unwind
1115 the handler stack as we go, so that the proper handlers are in
1116 effect for each unwind-protect clause we run. At the end, restore
1117 some static info saved in CATCH, and longjmp to the location
1118 specified there.
1120 This is used for correct unwinding in Fthrow and Fsignal. */
1122 static _Noreturn void
1123 unwind_to_catch (struct handler *catch, Lisp_Object value)
1125 bool last_time;
1127 eassert (catch->next);
1129 /* Save the value in the tag. */
1130 catch->val = value;
1132 /* Restore certain special C variables. */
1133 set_poll_suppress_count (catch->poll_suppress_count);
1134 unblock_input_to (catch->interrupt_input_blocked);
1135 immediate_quit = 0;
1139 /* Unwind the specpdl stack, and then restore the proper set of
1140 handlers. */
1141 unbind_to (handlerlist->pdlcount, Qnil);
1142 last_time = handlerlist == catch;
1143 if (! last_time)
1144 handlerlist = handlerlist->next;
1146 while (! last_time);
1148 eassert (handlerlist == catch);
1150 lisp_eval_depth = catch->f_lisp_eval_depth;
1152 sys_longjmp (catch->jmp, 1);
1155 DEFUN ("throw", Fthrow, Sthrow, 2, 2, 0,
1156 doc: /* Throw to the catch for TAG and return VALUE from it.
1157 Both TAG and VALUE are evalled. */
1158 attributes: noreturn)
1159 (register Lisp_Object tag, Lisp_Object value)
1161 struct handler *c;
1163 if (!NILP (tag))
1164 for (c = handlerlist; c; c = c->next)
1166 if (c->type == CATCHER_ALL)
1167 unwind_to_catch (c, Fcons (tag, value));
1168 if (c->type == CATCHER && EQ (c->tag_or_ch, tag))
1169 unwind_to_catch (c, value);
1171 xsignal2 (Qno_catch, tag, value);
1175 DEFUN ("unwind-protect", Funwind_protect, Sunwind_protect, 1, UNEVALLED, 0,
1176 doc: /* Do BODYFORM, protecting with UNWINDFORMS.
1177 If BODYFORM completes normally, its value is returned
1178 after executing the UNWINDFORMS.
1179 If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway.
1180 usage: (unwind-protect BODYFORM UNWINDFORMS...) */)
1181 (Lisp_Object args)
1183 Lisp_Object val;
1184 ptrdiff_t count = SPECPDL_INDEX ();
1186 record_unwind_protect (prog_ignore, XCDR (args));
1187 val = eval_sub (XCAR (args));
1188 return unbind_to (count, val);
1191 DEFUN ("condition-case", Fcondition_case, Scondition_case, 2, UNEVALLED, 0,
1192 doc: /* Regain control when an error is signaled.
1193 Executes BODYFORM and returns its value if no error happens.
1194 Each element of HANDLERS looks like (CONDITION-NAME BODY...)
1195 where the BODY is made of Lisp expressions.
1197 A handler is applicable to an error
1198 if CONDITION-NAME is one of the error's condition names.
1199 If an error happens, the first applicable handler is run.
1201 The car of a handler may be a list of condition names instead of a
1202 single condition name; then it handles all of them. If the special
1203 condition name `debug' is present in this list, it allows another
1204 condition in the list to run the debugger if `debug-on-error' and the
1205 other usual mechanisms says it should (otherwise, `condition-case'
1206 suppresses the debugger).
1208 When a handler handles an error, control returns to the `condition-case'
1209 and it executes the handler's BODY...
1210 with VAR bound to (ERROR-SYMBOL . SIGNAL-DATA) from the error.
1211 \(If VAR is nil, the handler can't access that information.)
1212 Then the value of the last BODY form is returned from the `condition-case'
1213 expression.
1215 See also the function `signal' for more info.
1216 usage: (condition-case VAR BODYFORM &rest HANDLERS) */)
1217 (Lisp_Object args)
1219 Lisp_Object var = XCAR (args);
1220 Lisp_Object bodyform = XCAR (XCDR (args));
1221 Lisp_Object handlers = XCDR (XCDR (args));
1223 return internal_lisp_condition_case (var, bodyform, handlers);
1226 /* Like Fcondition_case, but the args are separate
1227 rather than passed in a list. Used by Fbyte_code. */
1229 Lisp_Object
1230 internal_lisp_condition_case (volatile Lisp_Object var, Lisp_Object bodyform,
1231 Lisp_Object handlers)
1233 Lisp_Object val;
1234 struct handler *oldhandlerlist = handlerlist;
1235 int clausenb = 0;
1237 CHECK_SYMBOL (var);
1239 for (val = handlers; CONSP (val); val = XCDR (val))
1241 Lisp_Object tem = XCAR (val);
1242 clausenb++;
1243 if (! (NILP (tem)
1244 || (CONSP (tem)
1245 && (SYMBOLP (XCAR (tem))
1246 || CONSP (XCAR (tem))))))
1247 error ("Invalid condition handler: %s",
1248 SDATA (Fprin1_to_string (tem, Qt)));
1251 { /* The first clause is the one that should be checked first, so it should
1252 be added to handlerlist last. So we build in `clauses' a table that
1253 contains `handlers' but in reverse order. SAFE_ALLOCA won't work
1254 here due to the setjmp, so impose a MAX_ALLOCA limit. */
1255 if (MAX_ALLOCA / word_size < clausenb)
1256 memory_full (SIZE_MAX);
1257 Lisp_Object *clauses = alloca (clausenb * sizeof *clauses);
1258 Lisp_Object *volatile clauses_volatile = clauses;
1259 int i = clausenb;
1260 for (val = handlers; CONSP (val); val = XCDR (val))
1261 clauses[--i] = XCAR (val);
1262 for (i = 0; i < clausenb; i++)
1264 Lisp_Object clause = clauses[i];
1265 Lisp_Object condition = CONSP (clause) ? XCAR (clause) : Qnil;
1266 if (!CONSP (condition))
1267 condition = Fcons (condition, Qnil);
1268 struct handler *c = push_handler (condition, CONDITION_CASE);
1269 if (sys_setjmp (c->jmp))
1271 ptrdiff_t count = SPECPDL_INDEX ();
1272 Lisp_Object val = handlerlist->val;
1273 Lisp_Object *chosen_clause = clauses_volatile;
1274 for (c = handlerlist->next; c != oldhandlerlist; c = c->next)
1275 chosen_clause++;
1276 handlerlist = oldhandlerlist;
1277 if (!NILP (var))
1279 if (!NILP (Vinternal_interpreter_environment))
1280 specbind (Qinternal_interpreter_environment,
1281 Fcons (Fcons (var, val),
1282 Vinternal_interpreter_environment));
1283 else
1284 specbind (var, val);
1286 val = Fprogn (XCDR (*chosen_clause));
1287 /* Note that this just undoes the binding of var; whoever
1288 longjumped to us unwound the stack to c.pdlcount before
1289 throwing. */
1290 if (!NILP (var))
1291 unbind_to (count, Qnil);
1292 return val;
1297 val = eval_sub (bodyform);
1298 handlerlist = oldhandlerlist;
1299 return val;
1302 /* Call the function BFUN with no arguments, catching errors within it
1303 according to HANDLERS. If there is an error, call HFUN with
1304 one argument which is the data that describes the error:
1305 (SIGNALNAME . DATA)
1307 HANDLERS can be a list of conditions to catch.
1308 If HANDLERS is Qt, catch all errors.
1309 If HANDLERS is Qerror, catch all errors
1310 but allow the debugger to run if that is enabled. */
1312 Lisp_Object
1313 internal_condition_case (Lisp_Object (*bfun) (void), Lisp_Object handlers,
1314 Lisp_Object (*hfun) (Lisp_Object))
1316 struct handler *c = push_handler (handlers, CONDITION_CASE);
1317 if (sys_setjmp (c->jmp))
1319 Lisp_Object val = handlerlist->val;
1320 clobbered_eassert (handlerlist == c);
1321 handlerlist = handlerlist->next;
1322 return hfun (val);
1324 else
1326 Lisp_Object val = bfun ();
1327 eassert (handlerlist == c);
1328 handlerlist = c->next;
1329 return val;
1333 /* Like internal_condition_case but call BFUN with ARG as its argument. */
1335 Lisp_Object
1336 internal_condition_case_1 (Lisp_Object (*bfun) (Lisp_Object), Lisp_Object arg,
1337 Lisp_Object handlers,
1338 Lisp_Object (*hfun) (Lisp_Object))
1340 struct handler *c = push_handler (handlers, CONDITION_CASE);
1341 if (sys_setjmp (c->jmp))
1343 Lisp_Object val = handlerlist->val;
1344 clobbered_eassert (handlerlist == c);
1345 handlerlist = handlerlist->next;
1346 return hfun (val);
1348 else
1350 Lisp_Object val = bfun (arg);
1351 eassert (handlerlist == c);
1352 handlerlist = c->next;
1353 return val;
1357 /* Like internal_condition_case_1 but call BFUN with ARG1 and ARG2 as
1358 its arguments. */
1360 Lisp_Object
1361 internal_condition_case_2 (Lisp_Object (*bfun) (Lisp_Object, Lisp_Object),
1362 Lisp_Object arg1,
1363 Lisp_Object arg2,
1364 Lisp_Object handlers,
1365 Lisp_Object (*hfun) (Lisp_Object))
1367 struct handler *c = push_handler (handlers, CONDITION_CASE);
1368 if (sys_setjmp (c->jmp))
1370 Lisp_Object val = handlerlist->val;
1371 clobbered_eassert (handlerlist == c);
1372 handlerlist = handlerlist->next;
1373 return hfun (val);
1375 else
1377 Lisp_Object val = bfun (arg1, arg2);
1378 eassert (handlerlist == c);
1379 handlerlist = c->next;
1380 return val;
1384 /* Like internal_condition_case but call BFUN with NARGS as first,
1385 and ARGS as second argument. */
1387 Lisp_Object
1388 internal_condition_case_n (Lisp_Object (*bfun) (ptrdiff_t, Lisp_Object *),
1389 ptrdiff_t nargs,
1390 Lisp_Object *args,
1391 Lisp_Object handlers,
1392 Lisp_Object (*hfun) (Lisp_Object err,
1393 ptrdiff_t nargs,
1394 Lisp_Object *args))
1396 struct handler *c = push_handler (handlers, CONDITION_CASE);
1397 if (sys_setjmp (c->jmp))
1399 Lisp_Object val = handlerlist->val;
1400 clobbered_eassert (handlerlist == c);
1401 handlerlist = handlerlist->next;
1402 return hfun (val, nargs, args);
1404 else
1406 Lisp_Object val = bfun (nargs, args);
1407 eassert (handlerlist == c);
1408 handlerlist = c->next;
1409 return val;
1413 struct handler *
1414 push_handler (Lisp_Object tag_ch_val, enum handlertype handlertype)
1416 struct handler *c = push_handler_nosignal (tag_ch_val, handlertype);
1417 if (!c)
1418 memory_full (sizeof *c);
1419 return c;
1422 struct handler *
1423 push_handler_nosignal (Lisp_Object tag_ch_val, enum handlertype handlertype)
1425 struct handler *c = handlerlist->nextfree;
1426 if (!c)
1428 c = malloc (sizeof *c);
1429 if (!c)
1430 return c;
1431 if (profiler_memory_running)
1432 malloc_probe (sizeof *c);
1433 c->nextfree = NULL;
1434 handlerlist->nextfree = c;
1436 c->type = handlertype;
1437 c->tag_or_ch = tag_ch_val;
1438 c->val = Qnil;
1439 c->next = handlerlist;
1440 c->f_lisp_eval_depth = lisp_eval_depth;
1441 c->pdlcount = SPECPDL_INDEX ();
1442 c->poll_suppress_count = poll_suppress_count;
1443 c->interrupt_input_blocked = interrupt_input_blocked;
1444 handlerlist = c;
1445 return c;
1449 static Lisp_Object signal_or_quit (Lisp_Object, Lisp_Object, bool);
1450 static Lisp_Object find_handler_clause (Lisp_Object, Lisp_Object);
1451 static bool maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig,
1452 Lisp_Object data);
1454 void
1455 process_quit_flag (void)
1457 Lisp_Object flag = Vquit_flag;
1458 Vquit_flag = Qnil;
1459 if (EQ (flag, Qkill_emacs))
1460 Fkill_emacs (Qnil);
1461 if (EQ (Vthrow_on_input, flag))
1462 Fthrow (Vthrow_on_input, Qt);
1463 quit ();
1466 DEFUN ("signal", Fsignal, Ssignal, 2, 2, 0,
1467 doc: /* Signal an error. Args are ERROR-SYMBOL and associated DATA.
1468 This function does not return.
1470 An error symbol is a symbol with an `error-conditions' property
1471 that is a list of condition names.
1472 A handler for any of those names will get to handle this signal.
1473 The symbol `error' should normally be one of them.
1475 DATA should be a list. Its elements are printed as part of the error message.
1476 See Info anchor `(elisp)Definition of signal' for some details on how this
1477 error message is constructed.
1478 If the signal is handled, DATA is made available to the handler.
1479 See also the function `condition-case'. */
1480 attributes: noreturn)
1481 (Lisp_Object error_symbol, Lisp_Object data)
1483 signal_or_quit (error_symbol, data, false);
1484 eassume (false);
1487 /* Quit, in response to a keyboard quit request. */
1488 Lisp_Object
1489 quit (void)
1491 return signal_or_quit (Qquit, Qnil, true);
1494 /* Signal an error, or quit. ERROR_SYMBOL and DATA are as with Fsignal.
1495 If KEYBOARD_QUIT, this is a quit; ERROR_SYMBOL should be
1496 Qquit and DATA should be Qnil, and this function may return.
1497 Otherwise this function is like Fsignal and does not return. */
1499 static Lisp_Object
1500 signal_or_quit (Lisp_Object error_symbol, Lisp_Object data, bool keyboard_quit)
1502 /* When memory is full, ERROR-SYMBOL is nil,
1503 and DATA is (REAL-ERROR-SYMBOL . REAL-DATA).
1504 That is a special case--don't do this in other situations. */
1505 Lisp_Object conditions;
1506 Lisp_Object string;
1507 Lisp_Object real_error_symbol
1508 = (NILP (error_symbol) ? Fcar (data) : error_symbol);
1509 register Lisp_Object clause = Qnil;
1510 struct handler *h;
1512 immediate_quit = 0;
1513 if (gc_in_progress || waiting_for_input)
1514 emacs_abort ();
1516 #if 0 /* rms: I don't know why this was here,
1517 but it is surely wrong for an error that is handled. */
1518 #ifdef HAVE_WINDOW_SYSTEM
1519 if (display_hourglass_p)
1520 cancel_hourglass ();
1521 #endif
1522 #endif
1524 /* This hook is used by edebug. */
1525 if (! NILP (Vsignal_hook_function)
1526 && ! NILP (error_symbol))
1528 /* Edebug takes care of restoring these variables when it exits. */
1529 if (lisp_eval_depth + 20 > max_lisp_eval_depth)
1530 max_lisp_eval_depth = lisp_eval_depth + 20;
1532 if (SPECPDL_INDEX () + 40 > max_specpdl_size)
1533 max_specpdl_size = SPECPDL_INDEX () + 40;
1535 call2 (Vsignal_hook_function, error_symbol, data);
1538 conditions = Fget (real_error_symbol, Qerror_conditions);
1540 /* Remember from where signal was called. Skip over the frame for
1541 `signal' itself. If a frame for `error' follows, skip that,
1542 too. Don't do this when ERROR_SYMBOL is nil, because that
1543 is a memory-full error. */
1544 Vsignaling_function = Qnil;
1545 if (!NILP (error_symbol))
1547 union specbinding *pdl = backtrace_next (backtrace_top ());
1548 if (backtrace_p (pdl) && EQ (backtrace_function (pdl), Qerror))
1549 pdl = backtrace_next (pdl);
1550 if (backtrace_p (pdl))
1551 Vsignaling_function = backtrace_function (pdl);
1554 for (h = handlerlist; h; h = h->next)
1556 if (h->type != CONDITION_CASE)
1557 continue;
1558 clause = find_handler_clause (h->tag_or_ch, conditions);
1559 if (!NILP (clause))
1560 break;
1563 if (/* Don't run the debugger for a memory-full error.
1564 (There is no room in memory to do that!) */
1565 !NILP (error_symbol)
1566 && (!NILP (Vdebug_on_signal)
1567 /* If no handler is present now, try to run the debugger. */
1568 || NILP (clause)
1569 /* A `debug' symbol in the handler list disables the normal
1570 suppression of the debugger. */
1571 || (CONSP (clause) && !NILP (Fmemq (Qdebug, clause)))
1572 /* Special handler that means "print a message and run debugger
1573 if requested". */
1574 || EQ (h->tag_or_ch, Qerror)))
1576 bool debugger_called
1577 = maybe_call_debugger (conditions, error_symbol, data);
1578 /* We can't return values to code which signaled an error, but we
1579 can continue code which has signaled a quit. */
1580 if (keyboard_quit && debugger_called && EQ (real_error_symbol, Qquit))
1581 return Qnil;
1584 if (!NILP (clause))
1586 Lisp_Object unwind_data
1587 = (NILP (error_symbol) ? data : Fcons (error_symbol, data));
1589 unwind_to_catch (h, unwind_data);
1591 else
1593 if (handlerlist != handlerlist_sentinel)
1594 /* FIXME: This will come right back here if there's no `top-level'
1595 catcher. A better solution would be to abort here, and instead
1596 add a catch-all condition handler so we never come here. */
1597 Fthrow (Qtop_level, Qt);
1600 if (! NILP (error_symbol))
1601 data = Fcons (error_symbol, data);
1603 string = Ferror_message_string (data);
1604 fatal ("%s", SDATA (string));
1607 /* Like xsignal, but takes 0, 1, 2, or 3 args instead of a list. */
1609 void
1610 xsignal0 (Lisp_Object error_symbol)
1612 xsignal (error_symbol, Qnil);
1615 void
1616 xsignal1 (Lisp_Object error_symbol, Lisp_Object arg)
1618 xsignal (error_symbol, list1 (arg));
1621 void
1622 xsignal2 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2)
1624 xsignal (error_symbol, list2 (arg1, arg2));
1627 void
1628 xsignal3 (Lisp_Object error_symbol, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
1630 xsignal (error_symbol, list3 (arg1, arg2, arg3));
1633 /* Signal `error' with message S, and additional arg ARG.
1634 If ARG is not a genuine list, make it a one-element list. */
1636 void
1637 signal_error (const char *s, Lisp_Object arg)
1639 Lisp_Object tortoise, hare;
1641 hare = tortoise = arg;
1642 while (CONSP (hare))
1644 hare = XCDR (hare);
1645 if (!CONSP (hare))
1646 break;
1648 hare = XCDR (hare);
1649 tortoise = XCDR (tortoise);
1651 if (EQ (hare, tortoise))
1652 break;
1655 if (!NILP (hare))
1656 arg = list1 (arg);
1658 xsignal (Qerror, Fcons (build_string (s), arg));
1662 /* Return true if LIST is a non-nil atom or
1663 a list containing one of CONDITIONS. */
1665 static bool
1666 wants_debugger (Lisp_Object list, Lisp_Object conditions)
1668 if (NILP (list))
1669 return 0;
1670 if (! CONSP (list))
1671 return 1;
1673 while (CONSP (conditions))
1675 Lisp_Object this, tail;
1676 this = XCAR (conditions);
1677 for (tail = list; CONSP (tail); tail = XCDR (tail))
1678 if (EQ (XCAR (tail), this))
1679 return 1;
1680 conditions = XCDR (conditions);
1682 return 0;
1685 /* Return true if an error with condition-symbols CONDITIONS,
1686 and described by SIGNAL-DATA, should skip the debugger
1687 according to debugger-ignored-errors. */
1689 static bool
1690 skip_debugger (Lisp_Object conditions, Lisp_Object data)
1692 Lisp_Object tail;
1693 bool first_string = 1;
1694 Lisp_Object error_message;
1696 error_message = Qnil;
1697 for (tail = Vdebug_ignored_errors; CONSP (tail); tail = XCDR (tail))
1699 if (STRINGP (XCAR (tail)))
1701 if (first_string)
1703 error_message = Ferror_message_string (data);
1704 first_string = 0;
1707 if (fast_string_match (XCAR (tail), error_message) >= 0)
1708 return 1;
1710 else
1712 Lisp_Object contail;
1714 for (contail = conditions; CONSP (contail); contail = XCDR (contail))
1715 if (EQ (XCAR (tail), XCAR (contail)))
1716 return 1;
1720 return 0;
1723 /* Call the debugger if calling it is currently enabled for CONDITIONS.
1724 SIG and DATA describe the signal. There are two ways to pass them:
1725 = SIG is the error symbol, and DATA is the rest of the data.
1726 = SIG is nil, and DATA is (SYMBOL . REST-OF-DATA).
1727 This is for memory-full errors only. */
1728 static bool
1729 maybe_call_debugger (Lisp_Object conditions, Lisp_Object sig, Lisp_Object data)
1731 Lisp_Object combined_data;
1733 combined_data = Fcons (sig, data);
1735 if (
1736 /* Don't try to run the debugger with interrupts blocked.
1737 The editing loop would return anyway. */
1738 ! input_blocked_p ()
1739 && NILP (Vinhibit_debugger)
1740 /* Does user want to enter debugger for this kind of error? */
1741 && (EQ (sig, Qquit)
1742 ? debug_on_quit
1743 : wants_debugger (Vdebug_on_error, conditions))
1744 && ! skip_debugger (conditions, combined_data)
1745 /* RMS: What's this for? */
1746 && when_entered_debugger < num_nonmacro_input_events)
1748 call_debugger (list2 (Qerror, combined_data));
1749 return 1;
1752 return 0;
1755 static Lisp_Object
1756 find_handler_clause (Lisp_Object handlers, Lisp_Object conditions)
1758 register Lisp_Object h;
1760 /* t is used by handlers for all conditions, set up by C code. */
1761 if (EQ (handlers, Qt))
1762 return Qt;
1764 /* error is used similarly, but means print an error message
1765 and run the debugger if that is enabled. */
1766 if (EQ (handlers, Qerror))
1767 return Qt;
1769 for (h = handlers; CONSP (h); h = XCDR (h))
1771 Lisp_Object handler = XCAR (h);
1772 if (!NILP (Fmemq (handler, conditions)))
1773 return handlers;
1776 return Qnil;
1780 /* Format and return a string; called like vprintf. */
1781 Lisp_Object
1782 vformat_string (const char *m, va_list ap)
1784 char buf[4000];
1785 ptrdiff_t size = sizeof buf;
1786 ptrdiff_t size_max = STRING_BYTES_BOUND + 1;
1787 char *buffer = buf;
1788 ptrdiff_t used;
1789 Lisp_Object string;
1791 used = evxprintf (&buffer, &size, buf, size_max, m, ap);
1792 string = make_string (buffer, used);
1793 if (buffer != buf)
1794 xfree (buffer);
1796 return string;
1799 /* Dump an error message; called like vprintf. */
1800 void
1801 verror (const char *m, va_list ap)
1803 xsignal1 (Qerror, vformat_string (m, ap));
1807 /* Dump an error message; called like printf. */
1809 /* VARARGS 1 */
1810 void
1811 error (const char *m, ...)
1813 va_list ap;
1814 va_start (ap, m);
1815 verror (m, ap);
1818 DEFUN ("commandp", Fcommandp, Scommandp, 1, 2, 0,
1819 doc: /* Non-nil if FUNCTION makes provisions for interactive calling.
1820 This means it contains a description for how to read arguments to give it.
1821 The value is nil for an invalid function or a symbol with no function
1822 definition.
1824 Interactively callable functions include strings and vectors (treated
1825 as keyboard macros), lambda-expressions that contain a top-level call
1826 to `interactive', autoload definitions made by `autoload' with non-nil
1827 fourth argument, and some of the built-in functions of Lisp.
1829 Also, a symbol satisfies `commandp' if its function definition does so.
1831 If the optional argument FOR-CALL-INTERACTIVELY is non-nil,
1832 then strings and vectors are not accepted. */)
1833 (Lisp_Object function, Lisp_Object for_call_interactively)
1835 register Lisp_Object fun;
1836 register Lisp_Object funcar;
1837 Lisp_Object if_prop = Qnil;
1839 fun = function;
1841 fun = indirect_function (fun); /* Check cycles. */
1842 if (NILP (fun))
1843 return Qnil;
1845 /* Check an `interactive-form' property if present, analogous to the
1846 function-documentation property. */
1847 fun = function;
1848 while (SYMBOLP (fun))
1850 Lisp_Object tmp = Fget (fun, Qinteractive_form);
1851 if (!NILP (tmp))
1852 if_prop = Qt;
1853 fun = Fsymbol_function (fun);
1856 /* Emacs primitives are interactive if their DEFUN specifies an
1857 interactive spec. */
1858 if (SUBRP (fun))
1859 return XSUBR (fun)->intspec ? Qt : if_prop;
1861 /* Bytecode objects are interactive if they are long enough to
1862 have an element whose index is COMPILED_INTERACTIVE, which is
1863 where the interactive spec is stored. */
1864 else if (COMPILEDP (fun))
1865 return ((ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK) > COMPILED_INTERACTIVE
1866 ? Qt : if_prop);
1868 /* Strings and vectors are keyboard macros. */
1869 if (STRINGP (fun) || VECTORP (fun))
1870 return (NILP (for_call_interactively) ? Qt : Qnil);
1872 /* Lists may represent commands. */
1873 if (!CONSP (fun))
1874 return Qnil;
1875 funcar = XCAR (fun);
1876 if (EQ (funcar, Qclosure))
1877 return (!NILP (Fassq (Qinteractive, Fcdr (Fcdr (XCDR (fun)))))
1878 ? Qt : if_prop);
1879 else if (EQ (funcar, Qlambda))
1880 return !NILP (Fassq (Qinteractive, Fcdr (XCDR (fun)))) ? Qt : if_prop;
1881 else if (EQ (funcar, Qautoload))
1882 return !NILP (Fcar (Fcdr (Fcdr (XCDR (fun))))) ? Qt : if_prop;
1883 else
1884 return Qnil;
1887 DEFUN ("autoload", Fautoload, Sautoload, 2, 5, 0,
1888 doc: /* Define FUNCTION to autoload from FILE.
1889 FUNCTION is a symbol; FILE is a file name string to pass to `load'.
1890 Third arg DOCSTRING is documentation for the function.
1891 Fourth arg INTERACTIVE if non-nil says function can be called interactively.
1892 Fifth arg TYPE indicates the type of the object:
1893 nil or omitted says FUNCTION is a function,
1894 `keymap' says FUNCTION is really a keymap, and
1895 `macro' or t says FUNCTION is really a macro.
1896 Third through fifth args give info about the real definition.
1897 They default to nil.
1898 If FUNCTION is already defined other than as an autoload,
1899 this does nothing and returns nil. */)
1900 (Lisp_Object function, Lisp_Object file, Lisp_Object docstring, Lisp_Object interactive, Lisp_Object type)
1902 CHECK_SYMBOL (function);
1903 CHECK_STRING (file);
1905 /* If function is defined and not as an autoload, don't override. */
1906 if (!NILP (XSYMBOL (function)->function)
1907 && !AUTOLOADP (XSYMBOL (function)->function))
1908 return Qnil;
1910 if (!NILP (Vpurify_flag) && EQ (docstring, make_number (0)))
1911 /* `read1' in lread.c has found the docstring starting with "\
1912 and assumed the docstring will be provided by Snarf-documentation, so it
1913 passed us 0 instead. But that leads to accidental sharing in purecopy's
1914 hash-consing, so we use a (hopefully) unique integer instead. */
1915 docstring = make_number (XHASH (function));
1916 return Fdefalias (function,
1917 list5 (Qautoload, file, docstring, interactive, type),
1918 Qnil);
1921 void
1922 un_autoload (Lisp_Object oldqueue)
1924 Lisp_Object queue, first, second;
1926 /* Queue to unwind is current value of Vautoload_queue.
1927 oldqueue is the shadowed value to leave in Vautoload_queue. */
1928 queue = Vautoload_queue;
1929 Vautoload_queue = oldqueue;
1930 while (CONSP (queue))
1932 first = XCAR (queue);
1933 second = Fcdr (first);
1934 first = Fcar (first);
1935 if (EQ (first, make_number (0)))
1936 Vfeatures = second;
1937 else
1938 Ffset (first, second);
1939 queue = XCDR (queue);
1943 /* Load an autoloaded function.
1944 FUNNAME is the symbol which is the function's name.
1945 FUNDEF is the autoload definition (a list). */
1947 DEFUN ("autoload-do-load", Fautoload_do_load, Sautoload_do_load, 1, 3, 0,
1948 doc: /* Load FUNDEF which should be an autoload.
1949 If non-nil, FUNNAME should be the symbol whose function value is FUNDEF,
1950 in which case the function returns the new autoloaded function value.
1951 If equal to `macro', MACRO-ONLY specifies that FUNDEF should only be loaded if
1952 it defines a macro. */)
1953 (Lisp_Object fundef, Lisp_Object funname, Lisp_Object macro_only)
1955 ptrdiff_t count = SPECPDL_INDEX ();
1957 if (!CONSP (fundef) || !EQ (Qautoload, XCAR (fundef)))
1958 return fundef;
1960 /* In the special case that we are generating ldefs-boot-auto.el,
1961 then be noisy about the autoload. */
1962 if( generating_ldefs_boot )
1964 fprintf(stderr, "(autoload '");
1965 Fprin1(funname,Qexternal_debugging_output);
1966 fprintf(stderr, " ");
1967 Fprin1(Fcar (Fcdr (fundef)),Qexternal_debugging_output);
1968 fprintf(stderr, " nil nil ");
1970 Lisp_Object kind = Fnth (make_number (4), fundef);
1971 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1973 fprintf(stderr, "nil");
1975 else
1977 fprintf(stderr, "t");
1979 fprintf(stderr, ")\n");
1982 if (EQ (macro_only, Qmacro))
1984 Lisp_Object kind = Fnth (make_number (4), fundef);
1985 if (! (EQ (kind, Qt) || EQ (kind, Qmacro)))
1986 return fundef;
1989 /* This is to make sure that loadup.el gives a clear picture
1990 of what files are preloaded and when. */
1991 if (! NILP (Vpurify_flag))
1992 error ("Attempt to autoload %s while preparing to dump",
1993 SDATA (SYMBOL_NAME (funname)));
1995 CHECK_SYMBOL (funname);
1997 /* Preserve the match data. */
1998 record_unwind_save_match_data ();
2000 /* If autoloading gets an error (which includes the error of failing
2001 to define the function being called), we use Vautoload_queue
2002 to undo function definitions and `provide' calls made by
2003 the function. We do this in the specific case of autoloading
2004 because autoloading is not an explicit request "load this file",
2005 but rather a request to "call this function".
2007 The value saved here is to be restored into Vautoload_queue. */
2008 record_unwind_protect (un_autoload, Vautoload_queue);
2009 Vautoload_queue = Qt;
2010 /* If `macro_only', assume this autoload to be a "best-effort",
2011 so don't signal an error if autoloading fails. */
2012 Fload (Fcar (Fcdr (fundef)), macro_only, Qt, Qnil, Qt);
2014 /* Once loading finishes, don't undo it. */
2015 Vautoload_queue = Qt;
2016 unbind_to (count, Qnil);
2018 if (NILP (funname))
2019 return Qnil;
2020 else
2022 Lisp_Object fun = Findirect_function (funname, Qnil);
2024 if (!NILP (Fequal (fun, fundef)))
2025 error ("Autoloading file %s failed to define function %s",
2026 SDATA (Fcar (Fcar (Vload_history))),
2027 SDATA (SYMBOL_NAME (funname)));
2028 else
2029 return fun;
2034 DEFUN ("eval", Feval, Seval, 1, 2, 0,
2035 doc: /* Evaluate FORM and return its value.
2036 If LEXICAL is t, evaluate using lexical scoping.
2037 LEXICAL can also be an actual lexical environment, in the form of an
2038 alist mapping symbols to their value. */)
2039 (Lisp_Object form, Lisp_Object lexical)
2041 ptrdiff_t count = SPECPDL_INDEX ();
2042 specbind (Qinternal_interpreter_environment,
2043 CONSP (lexical) || NILP (lexical) ? lexical : list1 (Qt));
2044 return unbind_to (count, eval_sub (form));
2047 /* Grow the specpdl stack by one entry.
2048 The caller should have already initialized the entry.
2049 Signal an error on stack overflow.
2051 Make sure that there is always one unused entry past the top of the
2052 stack, so that the just-initialized entry is safely unwound if
2053 memory exhausted and an error is signaled here. Also, allocate a
2054 never-used entry just before the bottom of the stack; sometimes its
2055 address is taken. */
2057 static void
2058 grow_specpdl (void)
2060 specpdl_ptr++;
2062 if (specpdl_ptr == specpdl + specpdl_size)
2064 ptrdiff_t count = SPECPDL_INDEX ();
2065 ptrdiff_t max_size = min (max_specpdl_size, PTRDIFF_MAX - 1000);
2066 union specbinding *pdlvec = specpdl - 1;
2067 ptrdiff_t pdlvecsize = specpdl_size + 1;
2068 if (max_size <= specpdl_size)
2070 if (max_specpdl_size < 400)
2071 max_size = max_specpdl_size = 400;
2072 if (max_size <= specpdl_size)
2073 signal_error ("Variable binding depth exceeds max-specpdl-size",
2074 Qnil);
2076 pdlvec = xpalloc (pdlvec, &pdlvecsize, 1, max_size + 1, sizeof *specpdl);
2077 specpdl = pdlvec + 1;
2078 specpdl_size = pdlvecsize - 1;
2079 specpdl_ptr = specpdl + count;
2083 ptrdiff_t
2084 record_in_backtrace (Lisp_Object function, Lisp_Object *args, ptrdiff_t nargs)
2086 ptrdiff_t count = SPECPDL_INDEX ();
2088 eassert (nargs >= UNEVALLED);
2089 specpdl_ptr->bt.kind = SPECPDL_BACKTRACE;
2090 specpdl_ptr->bt.debug_on_exit = false;
2091 specpdl_ptr->bt.function = function;
2092 specpdl_ptr->bt.args = args;
2093 specpdl_ptr->bt.nargs = nargs;
2094 grow_specpdl ();
2096 return count;
2099 /* Eval a sub-expression of the current expression (i.e. in the same
2100 lexical scope). */
2101 Lisp_Object
2102 eval_sub (Lisp_Object form)
2104 Lisp_Object fun, val, original_fun, original_args;
2105 Lisp_Object funcar;
2106 ptrdiff_t count;
2108 /* Declare here, as this array may be accessed by call_debugger near
2109 the end of this function. See Bug#21245. */
2110 Lisp_Object argvals[8];
2112 if (SYMBOLP (form))
2114 /* Look up its binding in the lexical environment.
2115 We do not pay attention to the declared_special flag here, since we
2116 already did that when let-binding the variable. */
2117 Lisp_Object lex_binding
2118 = !NILP (Vinternal_interpreter_environment) /* Mere optimization! */
2119 ? Fassq (form, Vinternal_interpreter_environment)
2120 : Qnil;
2121 if (CONSP (lex_binding))
2122 return XCDR (lex_binding);
2123 else
2124 return Fsymbol_value (form);
2127 if (!CONSP (form))
2128 return form;
2130 QUIT;
2132 maybe_gc ();
2134 if (++lisp_eval_depth > max_lisp_eval_depth)
2136 if (max_lisp_eval_depth < 100)
2137 max_lisp_eval_depth = 100;
2138 if (lisp_eval_depth > max_lisp_eval_depth)
2139 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2142 original_fun = XCAR (form);
2143 original_args = XCDR (form);
2145 /* This also protects them from gc. */
2146 count = record_in_backtrace (original_fun, &original_args, UNEVALLED);
2148 if (debug_on_next_call)
2149 do_debug_on_call (Qt, count);
2151 /* At this point, only original_fun and original_args
2152 have values that will be used below. */
2153 retry:
2155 /* Optimize for no indirection. */
2156 fun = original_fun;
2157 if (!SYMBOLP (fun))
2158 fun = Ffunction (Fcons (fun, Qnil));
2159 else if (!NILP (fun) && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2160 fun = indirect_function (fun);
2162 if (SUBRP (fun))
2164 Lisp_Object args_left = original_args;
2165 Lisp_Object numargs = Flength (args_left);
2167 check_cons_list ();
2169 if (XINT (numargs) < XSUBR (fun)->min_args
2170 || (XSUBR (fun)->max_args >= 0
2171 && XSUBR (fun)->max_args < XINT (numargs)))
2172 xsignal2 (Qwrong_number_of_arguments, original_fun, numargs);
2174 else if (XSUBR (fun)->max_args == UNEVALLED)
2175 val = (XSUBR (fun)->function.aUNEVALLED) (args_left);
2176 else if (XSUBR (fun)->max_args == MANY)
2178 /* Pass a vector of evaluated arguments. */
2179 Lisp_Object *vals;
2180 ptrdiff_t argnum = 0;
2181 USE_SAFE_ALLOCA;
2183 SAFE_ALLOCA_LISP (vals, XINT (numargs));
2185 while (!NILP (args_left))
2187 vals[argnum++] = eval_sub (Fcar (args_left));
2188 args_left = Fcdr (args_left);
2191 set_backtrace_args (specpdl + count, vals, XINT (numargs));
2193 val = (XSUBR (fun)->function.aMANY) (XINT (numargs), vals);
2195 check_cons_list ();
2196 lisp_eval_depth--;
2197 /* Do the debug-on-exit now, while VALS still exists. */
2198 if (backtrace_debug_on_exit (specpdl + count))
2199 val = call_debugger (list2 (Qexit, val));
2200 SAFE_FREE ();
2201 specpdl_ptr--;
2202 return val;
2204 else
2206 int i, maxargs = XSUBR (fun)->max_args;
2208 for (i = 0; i < maxargs; i++)
2210 argvals[i] = eval_sub (Fcar (args_left));
2211 args_left = Fcdr (args_left);
2214 set_backtrace_args (specpdl + count, argvals, XINT (numargs));
2216 switch (i)
2218 case 0:
2219 val = (XSUBR (fun)->function.a0 ());
2220 break;
2221 case 1:
2222 val = (XSUBR (fun)->function.a1 (argvals[0]));
2223 break;
2224 case 2:
2225 val = (XSUBR (fun)->function.a2 (argvals[0], argvals[1]));
2226 break;
2227 case 3:
2228 val = (XSUBR (fun)->function.a3
2229 (argvals[0], argvals[1], argvals[2]));
2230 break;
2231 case 4:
2232 val = (XSUBR (fun)->function.a4
2233 (argvals[0], argvals[1], argvals[2], argvals[3]));
2234 break;
2235 case 5:
2236 val = (XSUBR (fun)->function.a5
2237 (argvals[0], argvals[1], argvals[2], argvals[3],
2238 argvals[4]));
2239 break;
2240 case 6:
2241 val = (XSUBR (fun)->function.a6
2242 (argvals[0], argvals[1], argvals[2], argvals[3],
2243 argvals[4], argvals[5]));
2244 break;
2245 case 7:
2246 val = (XSUBR (fun)->function.a7
2247 (argvals[0], argvals[1], argvals[2], argvals[3],
2248 argvals[4], argvals[5], argvals[6]));
2249 break;
2251 case 8:
2252 val = (XSUBR (fun)->function.a8
2253 (argvals[0], argvals[1], argvals[2], argvals[3],
2254 argvals[4], argvals[5], argvals[6], argvals[7]));
2255 break;
2257 default:
2258 /* Someone has created a subr that takes more arguments than
2259 is supported by this code. We need to either rewrite the
2260 subr to use a different argument protocol, or add more
2261 cases to this switch. */
2262 emacs_abort ();
2266 else if (COMPILEDP (fun))
2267 return apply_lambda (fun, original_args, count);
2268 else
2270 if (NILP (fun))
2271 xsignal1 (Qvoid_function, original_fun);
2272 if (!CONSP (fun))
2273 xsignal1 (Qinvalid_function, original_fun);
2274 funcar = XCAR (fun);
2275 if (!SYMBOLP (funcar))
2276 xsignal1 (Qinvalid_function, original_fun);
2277 if (EQ (funcar, Qautoload))
2279 Fautoload_do_load (fun, original_fun, Qnil);
2280 goto retry;
2282 if (EQ (funcar, Qmacro))
2284 ptrdiff_t count1 = SPECPDL_INDEX ();
2285 Lisp_Object exp;
2286 /* Bind lexical-binding during expansion of the macro, so the
2287 macro can know reliably if the code it outputs will be
2288 interpreted using lexical-binding or not. */
2289 specbind (Qlexical_binding,
2290 NILP (Vinternal_interpreter_environment) ? Qnil : Qt);
2291 exp = apply1 (Fcdr (fun), original_args);
2292 unbind_to (count1, Qnil);
2293 val = eval_sub (exp);
2295 else if (EQ (funcar, Qlambda)
2296 || EQ (funcar, Qclosure))
2297 return apply_lambda (fun, original_args, count);
2298 else
2299 xsignal1 (Qinvalid_function, original_fun);
2301 check_cons_list ();
2303 lisp_eval_depth--;
2304 if (backtrace_debug_on_exit (specpdl + count))
2305 val = call_debugger (list2 (Qexit, val));
2306 specpdl_ptr--;
2308 return val;
2311 DEFUN ("apply", Fapply, Sapply, 1, MANY, 0,
2312 doc: /* Call FUNCTION with our remaining args, using our last arg as list of args.
2313 Then return the value FUNCTION returns.
2314 Thus, (apply \\='+ 1 2 \\='(3 4)) returns 10.
2315 usage: (apply FUNCTION &rest ARGUMENTS) */)
2316 (ptrdiff_t nargs, Lisp_Object *args)
2318 ptrdiff_t i, numargs, funcall_nargs;
2319 register Lisp_Object *funcall_args = NULL;
2320 register Lisp_Object spread_arg = args[nargs - 1];
2321 Lisp_Object fun = args[0];
2322 Lisp_Object retval;
2323 USE_SAFE_ALLOCA;
2325 CHECK_LIST (spread_arg);
2327 numargs = XINT (Flength (spread_arg));
2329 if (numargs == 0)
2330 return Ffuncall (nargs - 1, args);
2331 else if (numargs == 1)
2333 args [nargs - 1] = XCAR (spread_arg);
2334 return Ffuncall (nargs, args);
2337 numargs += nargs - 2;
2339 /* Optimize for no indirection. */
2340 if (SYMBOLP (fun) && !NILP (fun)
2341 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2343 fun = indirect_function (fun);
2344 if (NILP (fun))
2345 /* Let funcall get the error. */
2346 fun = args[0];
2349 if (SUBRP (fun) && XSUBR (fun)->max_args > numargs
2350 /* Don't hide an error by adding missing arguments. */
2351 && numargs >= XSUBR (fun)->min_args)
2353 /* Avoid making funcall cons up a yet another new vector of arguments
2354 by explicitly supplying nil's for optional values. */
2355 SAFE_ALLOCA_LISP (funcall_args, 1 + XSUBR (fun)->max_args);
2356 memclear (funcall_args + numargs + 1,
2357 (XSUBR (fun)->max_args - numargs) * word_size);
2358 funcall_nargs = 1 + XSUBR (fun)->max_args;
2360 else
2361 { /* We add 1 to numargs because funcall_args includes the
2362 function itself as well as its arguments. */
2363 SAFE_ALLOCA_LISP (funcall_args, 1 + numargs);
2364 funcall_nargs = 1 + numargs;
2367 memcpy (funcall_args, args, nargs * word_size);
2368 /* Spread the last arg we got. Its first element goes in
2369 the slot that it used to occupy, hence this value of I. */
2370 i = nargs - 1;
2371 while (!NILP (spread_arg))
2373 funcall_args [i++] = XCAR (spread_arg);
2374 spread_arg = XCDR (spread_arg);
2377 retval = Ffuncall (funcall_nargs, funcall_args);
2379 SAFE_FREE ();
2380 return retval;
2383 /* Run hook variables in various ways. */
2385 static Lisp_Object
2386 funcall_nil (ptrdiff_t nargs, Lisp_Object *args)
2388 Ffuncall (nargs, args);
2389 return Qnil;
2392 DEFUN ("run-hooks", Frun_hooks, Srun_hooks, 0, MANY, 0,
2393 doc: /* Run each hook in HOOKS.
2394 Each argument should be a symbol, a hook variable.
2395 These symbols are processed in the order specified.
2396 If a hook symbol has a non-nil value, that value may be a function
2397 or a list of functions to be called to run the hook.
2398 If the value is a function, it is called with no arguments.
2399 If it is a list, the elements are called, in order, with no arguments.
2401 Major modes should not use this function directly to run their mode
2402 hook; they should use `run-mode-hooks' instead.
2404 Do not use `make-local-variable' to make a hook variable buffer-local.
2405 Instead, use `add-hook' and specify t for the LOCAL argument.
2406 usage: (run-hooks &rest HOOKS) */)
2407 (ptrdiff_t nargs, Lisp_Object *args)
2409 ptrdiff_t i;
2411 for (i = 0; i < nargs; i++)
2412 run_hook (args[i]);
2414 return Qnil;
2417 DEFUN ("run-hook-with-args", Frun_hook_with_args,
2418 Srun_hook_with_args, 1, MANY, 0,
2419 doc: /* Run HOOK with the specified arguments ARGS.
2420 HOOK should be a symbol, a hook variable. The value of HOOK
2421 may be nil, a function, or a list of functions. Call each
2422 function in order with arguments ARGS. The final return value
2423 is unspecified.
2425 Do not use `make-local-variable' to make a hook variable buffer-local.
2426 Instead, use `add-hook' and specify t for the LOCAL argument.
2427 usage: (run-hook-with-args HOOK &rest ARGS) */)
2428 (ptrdiff_t nargs, Lisp_Object *args)
2430 return run_hook_with_args (nargs, args, funcall_nil);
2433 /* NB this one still documents a specific non-nil return value.
2434 (As did run-hook-with-args and run-hook-with-args-until-failure
2435 until they were changed in 24.1.) */
2436 DEFUN ("run-hook-with-args-until-success", Frun_hook_with_args_until_success,
2437 Srun_hook_with_args_until_success, 1, MANY, 0,
2438 doc: /* Run HOOK with the specified arguments ARGS.
2439 HOOK should be a symbol, a hook variable. The value of HOOK
2440 may be nil, a function, or a list of functions. Call each
2441 function in order with arguments ARGS, stopping at the first
2442 one that returns non-nil, and return that value. Otherwise (if
2443 all functions return nil, or if there are no functions to call),
2444 return nil.
2446 Do not use `make-local-variable' to make a hook variable buffer-local.
2447 Instead, use `add-hook' and specify t for the LOCAL argument.
2448 usage: (run-hook-with-args-until-success HOOK &rest ARGS) */)
2449 (ptrdiff_t nargs, Lisp_Object *args)
2451 return run_hook_with_args (nargs, args, Ffuncall);
2454 static Lisp_Object
2455 funcall_not (ptrdiff_t nargs, Lisp_Object *args)
2457 return NILP (Ffuncall (nargs, args)) ? Qt : Qnil;
2460 DEFUN ("run-hook-with-args-until-failure", Frun_hook_with_args_until_failure,
2461 Srun_hook_with_args_until_failure, 1, MANY, 0,
2462 doc: /* Run HOOK with the specified arguments ARGS.
2463 HOOK should be a symbol, a hook variable. The value of HOOK
2464 may be nil, a function, or a list of functions. Call each
2465 function in order with arguments ARGS, stopping at the first
2466 one that returns nil, and return nil. Otherwise (if all functions
2467 return non-nil, or if there are no functions to call), return non-nil
2468 \(do not rely on the precise return value in this case).
2470 Do not use `make-local-variable' to make a hook variable buffer-local.
2471 Instead, use `add-hook' and specify t for the LOCAL argument.
2472 usage: (run-hook-with-args-until-failure HOOK &rest ARGS) */)
2473 (ptrdiff_t nargs, Lisp_Object *args)
2475 return NILP (run_hook_with_args (nargs, args, funcall_not)) ? Qt : Qnil;
2478 static Lisp_Object
2479 run_hook_wrapped_funcall (ptrdiff_t nargs, Lisp_Object *args)
2481 Lisp_Object tmp = args[0], ret;
2482 args[0] = args[1];
2483 args[1] = tmp;
2484 ret = Ffuncall (nargs, args);
2485 args[1] = args[0];
2486 args[0] = tmp;
2487 return ret;
2490 DEFUN ("run-hook-wrapped", Frun_hook_wrapped, Srun_hook_wrapped, 2, MANY, 0,
2491 doc: /* Run HOOK, passing each function through WRAP-FUNCTION.
2492 I.e. instead of calling each function FUN directly with arguments ARGS,
2493 it calls WRAP-FUNCTION with arguments FUN and ARGS.
2494 As soon as a call to WRAP-FUNCTION returns non-nil, `run-hook-wrapped'
2495 aborts and returns that value.
2496 usage: (run-hook-wrapped HOOK WRAP-FUNCTION &rest ARGS) */)
2497 (ptrdiff_t nargs, Lisp_Object *args)
2499 return run_hook_with_args (nargs, args, run_hook_wrapped_funcall);
2502 /* ARGS[0] should be a hook symbol.
2503 Call each of the functions in the hook value, passing each of them
2504 as arguments all the rest of ARGS (all NARGS - 1 elements).
2505 FUNCALL specifies how to call each function on the hook. */
2507 Lisp_Object
2508 run_hook_with_args (ptrdiff_t nargs, Lisp_Object *args,
2509 Lisp_Object (*funcall) (ptrdiff_t nargs, Lisp_Object *args))
2511 Lisp_Object sym, val, ret = Qnil;
2513 /* If we are dying or still initializing,
2514 don't do anything--it would probably crash if we tried. */
2515 if (NILP (Vrun_hooks))
2516 return Qnil;
2518 sym = args[0];
2519 val = find_symbol_value (sym);
2521 if (EQ (val, Qunbound) || NILP (val))
2522 return ret;
2523 else if (!CONSP (val) || FUNCTIONP (val))
2525 args[0] = val;
2526 return funcall (nargs, args);
2528 else
2530 Lisp_Object global_vals = Qnil;
2532 for (;
2533 CONSP (val) && NILP (ret);
2534 val = XCDR (val))
2536 if (EQ (XCAR (val), Qt))
2538 /* t indicates this hook has a local binding;
2539 it means to run the global binding too. */
2540 global_vals = Fdefault_value (sym);
2541 if (NILP (global_vals)) continue;
2543 if (!CONSP (global_vals) || EQ (XCAR (global_vals), Qlambda))
2545 args[0] = global_vals;
2546 ret = funcall (nargs, args);
2548 else
2550 for (;
2551 CONSP (global_vals) && NILP (ret);
2552 global_vals = XCDR (global_vals))
2554 args[0] = XCAR (global_vals);
2555 /* In a global value, t should not occur. If it does, we
2556 must ignore it to avoid an endless loop. */
2557 if (!EQ (args[0], Qt))
2558 ret = funcall (nargs, args);
2562 else
2564 args[0] = XCAR (val);
2565 ret = funcall (nargs, args);
2569 return ret;
2573 /* Run the hook HOOK, giving each function no args. */
2575 void
2576 run_hook (Lisp_Object hook)
2578 Frun_hook_with_args (1, &hook);
2581 /* Run the hook HOOK, giving each function the two args ARG1 and ARG2. */
2583 void
2584 run_hook_with_args_2 (Lisp_Object hook, Lisp_Object arg1, Lisp_Object arg2)
2586 CALLN (Frun_hook_with_args, hook, arg1, arg2);
2589 /* Apply fn to arg. */
2590 Lisp_Object
2591 apply1 (Lisp_Object fn, Lisp_Object arg)
2593 return NILP (arg) ? Ffuncall (1, &fn) : CALLN (Fapply, fn, arg);
2596 /* Call function fn on no arguments. */
2597 Lisp_Object
2598 call0 (Lisp_Object fn)
2600 return Ffuncall (1, &fn);
2603 /* Call function fn with 1 argument arg1. */
2604 /* ARGSUSED */
2605 Lisp_Object
2606 call1 (Lisp_Object fn, Lisp_Object arg1)
2608 return CALLN (Ffuncall, fn, arg1);
2611 /* Call function fn with 2 arguments arg1, arg2. */
2612 /* ARGSUSED */
2613 Lisp_Object
2614 call2 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2)
2616 return CALLN (Ffuncall, fn, arg1, arg2);
2619 /* Call function fn with 3 arguments arg1, arg2, arg3. */
2620 /* ARGSUSED */
2621 Lisp_Object
2622 call3 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2624 return CALLN (Ffuncall, fn, arg1, arg2, arg3);
2627 /* Call function fn with 4 arguments arg1, arg2, arg3, arg4. */
2628 /* ARGSUSED */
2629 Lisp_Object
2630 call4 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2631 Lisp_Object arg4)
2633 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4);
2636 /* Call function fn with 5 arguments arg1, arg2, arg3, arg4, arg5. */
2637 /* ARGSUSED */
2638 Lisp_Object
2639 call5 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2640 Lisp_Object arg4, Lisp_Object arg5)
2642 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5);
2645 /* Call function fn with 6 arguments arg1, arg2, arg3, arg4, arg5, arg6. */
2646 /* ARGSUSED */
2647 Lisp_Object
2648 call6 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2649 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6)
2651 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6);
2654 /* Call function fn with 7 arguments arg1, arg2, arg3, arg4, arg5, arg6, arg7. */
2655 /* ARGSUSED */
2656 Lisp_Object
2657 call7 (Lisp_Object fn, Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3,
2658 Lisp_Object arg4, Lisp_Object arg5, Lisp_Object arg6, Lisp_Object arg7)
2660 return CALLN (Ffuncall, fn, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
2663 DEFUN ("functionp", Ffunctionp, Sfunctionp, 1, 1, 0,
2664 doc: /* Non-nil if OBJECT is a function. */)
2665 (Lisp_Object object)
2667 if (FUNCTIONP (object))
2668 return Qt;
2669 return Qnil;
2672 bool
2673 FUNCTIONP (Lisp_Object object)
2675 if (SYMBOLP (object) && !NILP (Ffboundp (object)))
2677 object = Findirect_function (object, Qt);
2679 if (CONSP (object) && EQ (XCAR (object), Qautoload))
2681 /* Autoloaded symbols are functions, except if they load
2682 macros or keymaps. */
2683 for (int i = 0; i < 4 && CONSP (object); i++)
2684 object = XCDR (object);
2686 return ! (CONSP (object) && !NILP (XCAR (object)));
2690 if (SUBRP (object))
2691 return XSUBR (object)->max_args != UNEVALLED;
2692 else if (COMPILEDP (object))
2693 return true;
2694 else if (CONSP (object))
2696 Lisp_Object car = XCAR (object);
2697 return EQ (car, Qlambda) || EQ (car, Qclosure);
2699 else
2700 return false;
2703 DEFUN ("funcall", Ffuncall, Sfuncall, 1, MANY, 0,
2704 doc: /* Call first argument as a function, passing remaining arguments to it.
2705 Return the value that function returns.
2706 Thus, (funcall \\='cons \\='x \\='y) returns (x . y).
2707 usage: (funcall FUNCTION &rest ARGUMENTS) */)
2708 (ptrdiff_t nargs, Lisp_Object *args)
2710 Lisp_Object fun, original_fun;
2711 Lisp_Object funcar;
2712 ptrdiff_t numargs = nargs - 1;
2713 Lisp_Object val;
2714 ptrdiff_t count;
2716 QUIT;
2718 if (++lisp_eval_depth > max_lisp_eval_depth)
2720 if (max_lisp_eval_depth < 100)
2721 max_lisp_eval_depth = 100;
2722 if (lisp_eval_depth > max_lisp_eval_depth)
2723 error ("Lisp nesting exceeds `max-lisp-eval-depth'");
2726 count = record_in_backtrace (args[0], &args[1], nargs - 1);
2728 maybe_gc ();
2730 if (debug_on_next_call)
2731 do_debug_on_call (Qlambda, count);
2733 check_cons_list ();
2735 original_fun = args[0];
2737 retry:
2739 /* Optimize for no indirection. */
2740 fun = original_fun;
2741 if (SYMBOLP (fun) && !NILP (fun)
2742 && (fun = XSYMBOL (fun)->function, SYMBOLP (fun)))
2743 fun = indirect_function (fun);
2745 if (SUBRP (fun))
2746 val = funcall_subr (XSUBR (fun), numargs, args + 1);
2747 else if (COMPILEDP (fun))
2748 val = funcall_lambda (fun, numargs, args + 1);
2749 else
2751 if (NILP (fun))
2752 xsignal1 (Qvoid_function, original_fun);
2753 if (!CONSP (fun))
2754 xsignal1 (Qinvalid_function, original_fun);
2755 funcar = XCAR (fun);
2756 if (!SYMBOLP (funcar))
2757 xsignal1 (Qinvalid_function, original_fun);
2758 if (EQ (funcar, Qlambda)
2759 || EQ (funcar, Qclosure))
2760 val = funcall_lambda (fun, numargs, args + 1);
2761 else if (EQ (funcar, Qautoload))
2763 Fautoload_do_load (fun, original_fun, Qnil);
2764 check_cons_list ();
2765 goto retry;
2767 else
2768 xsignal1 (Qinvalid_function, original_fun);
2770 check_cons_list ();
2771 lisp_eval_depth--;
2772 if (backtrace_debug_on_exit (specpdl + count))
2773 val = call_debugger (list2 (Qexit, val));
2774 specpdl_ptr--;
2775 return val;
2779 /* Apply a C subroutine SUBR to the NUMARGS evaluated arguments in ARG_VECTOR
2780 and return the result of evaluation. */
2782 Lisp_Object
2783 funcall_subr (struct Lisp_Subr *subr, ptrdiff_t numargs, Lisp_Object *args)
2785 if (numargs < subr->min_args
2786 || (subr->max_args >= 0 && subr->max_args < numargs))
2788 Lisp_Object fun;
2789 XSETSUBR (fun, subr);
2790 xsignal2 (Qwrong_number_of_arguments, fun, make_number (numargs));
2793 else if (subr->max_args == UNEVALLED)
2795 Lisp_Object fun;
2796 XSETSUBR (fun, subr);
2797 xsignal1 (Qinvalid_function, fun);
2800 else if (subr->max_args == MANY)
2801 return (subr->function.aMANY) (numargs, args);
2802 else
2804 Lisp_Object internal_argbuf[8];
2805 Lisp_Object *internal_args;
2806 if (subr->max_args > numargs)
2808 eassert (subr->max_args <= ARRAYELTS (internal_argbuf));
2809 internal_args = internal_argbuf;
2810 memcpy (internal_args, args, numargs * word_size);
2811 memclear (internal_args + numargs,
2812 (subr->max_args - numargs) * word_size);
2814 else
2815 internal_args = args;
2816 switch (subr->max_args)
2818 case 0:
2819 return (subr->function.a0 ());
2820 case 1:
2821 return (subr->function.a1 (internal_args[0]));
2822 case 2:
2823 return (subr->function.a2
2824 (internal_args[0], internal_args[1]));
2825 case 3:
2826 return (subr->function.a3
2827 (internal_args[0], internal_args[1], internal_args[2]));
2828 case 4:
2829 return (subr->function.a4
2830 (internal_args[0], internal_args[1], internal_args[2],
2831 internal_args[3]));
2832 case 5:
2833 return (subr->function.a5
2834 (internal_args[0], internal_args[1], internal_args[2],
2835 internal_args[3], internal_args[4]));
2836 case 6:
2837 return (subr->function.a6
2838 (internal_args[0], internal_args[1], internal_args[2],
2839 internal_args[3], internal_args[4], internal_args[5]));
2840 case 7:
2841 return (subr->function.a7
2842 (internal_args[0], internal_args[1], internal_args[2],
2843 internal_args[3], internal_args[4], internal_args[5],
2844 internal_args[6]));
2845 case 8:
2846 return (subr->function.a8
2847 (internal_args[0], internal_args[1], internal_args[2],
2848 internal_args[3], internal_args[4], internal_args[5],
2849 internal_args[6], internal_args[7]));
2851 default:
2853 /* If a subr takes more than 8 arguments without using MANY
2854 or UNEVALLED, we need to extend this function to support it.
2855 Until this is done, there is no way to call the function. */
2856 emacs_abort ();
2861 static Lisp_Object
2862 apply_lambda (Lisp_Object fun, Lisp_Object args, ptrdiff_t count)
2864 Lisp_Object args_left;
2865 ptrdiff_t i;
2866 EMACS_INT numargs;
2867 Lisp_Object *arg_vector;
2868 Lisp_Object tem;
2869 USE_SAFE_ALLOCA;
2871 numargs = XFASTINT (Flength (args));
2872 SAFE_ALLOCA_LISP (arg_vector, numargs);
2873 args_left = args;
2875 for (i = 0; i < numargs; )
2877 tem = Fcar (args_left), args_left = Fcdr (args_left);
2878 tem = eval_sub (tem);
2879 arg_vector[i++] = tem;
2882 set_backtrace_args (specpdl + count, arg_vector, i);
2883 tem = funcall_lambda (fun, numargs, arg_vector);
2885 check_cons_list ();
2886 lisp_eval_depth--;
2887 /* Do the debug-on-exit now, while arg_vector still exists. */
2888 if (backtrace_debug_on_exit (specpdl + count))
2889 tem = call_debugger (list2 (Qexit, tem));
2890 SAFE_FREE ();
2891 specpdl_ptr--;
2892 return tem;
2895 /* Apply a Lisp function FUN to the NARGS evaluated arguments in ARG_VECTOR
2896 and return the result of evaluation.
2897 FUN must be either a lambda-expression or a compiled-code object. */
2899 static Lisp_Object
2900 funcall_lambda (Lisp_Object fun, ptrdiff_t nargs,
2901 register Lisp_Object *arg_vector)
2903 Lisp_Object val, syms_left, next, lexenv;
2904 ptrdiff_t count = SPECPDL_INDEX ();
2905 ptrdiff_t i;
2906 bool optional, rest;
2908 if (CONSP (fun))
2910 if (EQ (XCAR (fun), Qclosure))
2912 Lisp_Object cdr = XCDR (fun); /* Drop `closure'. */
2913 if (! CONSP (cdr))
2914 xsignal1 (Qinvalid_function, fun);
2915 fun = cdr;
2916 lexenv = XCAR (fun);
2918 else
2919 lexenv = Qnil;
2920 syms_left = XCDR (fun);
2921 if (CONSP (syms_left))
2922 syms_left = XCAR (syms_left);
2923 else
2924 xsignal1 (Qinvalid_function, fun);
2926 else if (COMPILEDP (fun))
2928 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
2929 if (size <= COMPILED_STACK_DEPTH)
2930 xsignal1 (Qinvalid_function, fun);
2931 syms_left = AREF (fun, COMPILED_ARGLIST);
2932 if (INTEGERP (syms_left))
2933 /* A byte-code object with an integer args template means we
2934 shouldn't bind any arguments, instead just call the byte-code
2935 interpreter directly; it will push arguments as necessary.
2937 Byte-code objects with a nil args template (the default)
2938 have dynamically-bound arguments, and use the
2939 argument-binding code below instead (as do all interpreted
2940 functions, even lexically bound ones). */
2942 /* If we have not actually read the bytecode string
2943 and constants vector yet, fetch them from the file. */
2944 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
2945 Ffetch_bytecode (fun);
2946 return exec_byte_code (AREF (fun, COMPILED_BYTECODE),
2947 AREF (fun, COMPILED_CONSTANTS),
2948 AREF (fun, COMPILED_STACK_DEPTH),
2949 syms_left,
2950 nargs, arg_vector);
2952 lexenv = Qnil;
2954 else
2955 emacs_abort ();
2957 i = optional = rest = 0;
2958 bool previous_optional_or_rest = false;
2959 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
2961 QUIT;
2963 next = XCAR (syms_left);
2964 if (!SYMBOLP (next))
2965 xsignal1 (Qinvalid_function, fun);
2967 if (EQ (next, Qand_rest))
2969 if (rest || previous_optional_or_rest)
2970 xsignal1 (Qinvalid_function, fun);
2971 rest = 1;
2972 previous_optional_or_rest = true;
2974 else if (EQ (next, Qand_optional))
2976 if (optional || rest || previous_optional_or_rest)
2977 xsignal1 (Qinvalid_function, fun);
2978 optional = 1;
2979 previous_optional_or_rest = true;
2981 else
2983 Lisp_Object arg;
2984 if (rest)
2986 arg = Flist (nargs - i, &arg_vector[i]);
2987 i = nargs;
2989 else if (i < nargs)
2990 arg = arg_vector[i++];
2991 else if (!optional)
2992 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
2993 else
2994 arg = Qnil;
2996 /* Bind the argument. */
2997 if (!NILP (lexenv) && SYMBOLP (next))
2998 /* Lexically bind NEXT by adding it to the lexenv alist. */
2999 lexenv = Fcons (Fcons (next, arg), lexenv);
3000 else
3001 /* Dynamically bind NEXT. */
3002 specbind (next, arg);
3003 previous_optional_or_rest = false;
3007 if (!NILP (syms_left) || previous_optional_or_rest)
3008 xsignal1 (Qinvalid_function, fun);
3009 else if (i < nargs)
3010 xsignal2 (Qwrong_number_of_arguments, fun, make_number (nargs));
3012 if (!EQ (lexenv, Vinternal_interpreter_environment))
3013 /* Instantiate a new lexical environment. */
3014 specbind (Qinternal_interpreter_environment, lexenv);
3016 if (CONSP (fun))
3017 val = Fprogn (XCDR (XCDR (fun)));
3018 else
3020 /* If we have not actually read the bytecode string
3021 and constants vector yet, fetch them from the file. */
3022 if (CONSP (AREF (fun, COMPILED_BYTECODE)))
3023 Ffetch_bytecode (fun);
3024 val = exec_byte_code (AREF (fun, COMPILED_BYTECODE),
3025 AREF (fun, COMPILED_CONSTANTS),
3026 AREF (fun, COMPILED_STACK_DEPTH),
3027 Qnil, 0, 0);
3030 return unbind_to (count, val);
3033 DEFUN ("func-arity", Ffunc_arity, Sfunc_arity, 1, 1, 0,
3034 doc: /* Return minimum and maximum number of args allowed for FUNCTION.
3035 FUNCTION must be a function of some kind.
3036 The returned value is a cons cell (MIN . MAX). MIN is the minimum number
3037 of args. MAX is the maximum number, or the symbol `many', for a
3038 function with `&rest' args, or `unevalled' for a special form. */)
3039 (Lisp_Object function)
3041 Lisp_Object original;
3042 Lisp_Object funcar;
3043 Lisp_Object result;
3045 original = function;
3047 retry:
3049 /* Optimize for no indirection. */
3050 function = original;
3051 if (SYMBOLP (function) && !NILP (function))
3053 function = XSYMBOL (function)->function;
3054 if (SYMBOLP (function))
3055 function = indirect_function (function);
3058 if (CONSP (function) && EQ (XCAR (function), Qmacro))
3059 function = XCDR (function);
3061 if (SUBRP (function))
3062 result = Fsubr_arity (function);
3063 else if (COMPILEDP (function))
3064 result = lambda_arity (function);
3065 else
3067 if (NILP (function))
3068 xsignal1 (Qvoid_function, original);
3069 if (!CONSP (function))
3070 xsignal1 (Qinvalid_function, original);
3071 funcar = XCAR (function);
3072 if (!SYMBOLP (funcar))
3073 xsignal1 (Qinvalid_function, original);
3074 if (EQ (funcar, Qlambda)
3075 || EQ (funcar, Qclosure))
3076 result = lambda_arity (function);
3077 else if (EQ (funcar, Qautoload))
3079 Fautoload_do_load (function, original, Qnil);
3080 goto retry;
3082 else
3083 xsignal1 (Qinvalid_function, original);
3085 return result;
3088 /* FUN must be either a lambda-expression or a compiled-code object. */
3089 static Lisp_Object
3090 lambda_arity (Lisp_Object fun)
3092 Lisp_Object syms_left;
3094 if (CONSP (fun))
3096 if (EQ (XCAR (fun), Qclosure))
3098 fun = XCDR (fun); /* Drop `closure'. */
3099 CHECK_LIST_CONS (fun, fun);
3101 syms_left = XCDR (fun);
3102 if (CONSP (syms_left))
3103 syms_left = XCAR (syms_left);
3104 else
3105 xsignal1 (Qinvalid_function, fun);
3107 else if (COMPILEDP (fun))
3109 ptrdiff_t size = ASIZE (fun) & PSEUDOVECTOR_SIZE_MASK;
3110 if (size <= COMPILED_STACK_DEPTH)
3111 xsignal1 (Qinvalid_function, fun);
3112 syms_left = AREF (fun, COMPILED_ARGLIST);
3113 if (INTEGERP (syms_left))
3114 return get_byte_code_arity (syms_left);
3116 else
3117 emacs_abort ();
3119 EMACS_INT minargs = 0, maxargs = 0;
3120 bool optional = false;
3121 for (; CONSP (syms_left); syms_left = XCDR (syms_left))
3123 Lisp_Object next = XCAR (syms_left);
3124 if (!SYMBOLP (next))
3125 xsignal1 (Qinvalid_function, fun);
3127 if (EQ (next, Qand_rest))
3128 return Fcons (make_number (minargs), Qmany);
3129 else if (EQ (next, Qand_optional))
3130 optional = true;
3131 else
3133 if (!optional)
3134 minargs++;
3135 maxargs++;
3139 if (!NILP (syms_left))
3140 xsignal1 (Qinvalid_function, fun);
3142 return Fcons (make_number (minargs), make_number (maxargs));
3145 DEFUN ("fetch-bytecode", Ffetch_bytecode, Sfetch_bytecode,
3146 1, 1, 0,
3147 doc: /* If byte-compiled OBJECT is lazy-loaded, fetch it now. */)
3148 (Lisp_Object object)
3150 Lisp_Object tem;
3152 if (COMPILEDP (object))
3154 ptrdiff_t size = ASIZE (object) & PSEUDOVECTOR_SIZE_MASK;
3155 if (size <= COMPILED_STACK_DEPTH)
3156 xsignal1 (Qinvalid_function, object);
3157 if (CONSP (AREF (object, COMPILED_BYTECODE)))
3159 tem = read_doc_string (AREF (object, COMPILED_BYTECODE));
3160 if (!CONSP (tem))
3162 tem = AREF (object, COMPILED_BYTECODE);
3163 if (CONSP (tem) && STRINGP (XCAR (tem)))
3164 error ("Invalid byte code in %s", SDATA (XCAR (tem)));
3165 else
3166 error ("Invalid byte code");
3168 ASET (object, COMPILED_BYTECODE, XCAR (tem));
3169 ASET (object, COMPILED_CONSTANTS, XCDR (tem));
3172 return object;
3175 /* Return true if SYMBOL currently has a let-binding
3176 which was made in the buffer that is now current. */
3178 bool
3179 let_shadows_buffer_binding_p (struct Lisp_Symbol *symbol)
3181 union specbinding *p;
3182 Lisp_Object buf = Fcurrent_buffer ();
3184 for (p = specpdl_ptr; p > specpdl; )
3185 if ((--p)->kind > SPECPDL_LET)
3187 struct Lisp_Symbol *let_bound_symbol = XSYMBOL (specpdl_symbol (p));
3188 eassert (let_bound_symbol->redirect != SYMBOL_VARALIAS);
3189 if (symbol == let_bound_symbol
3190 && EQ (specpdl_where (p), buf))
3191 return 1;
3194 return 0;
3197 bool
3198 let_shadows_global_binding_p (Lisp_Object symbol)
3200 union specbinding *p;
3202 for (p = specpdl_ptr; p > specpdl; )
3203 if ((--p)->kind >= SPECPDL_LET && EQ (specpdl_symbol (p), symbol))
3204 return 1;
3206 return 0;
3209 static void
3210 do_specbind (struct Lisp_Symbol *sym, union specbinding *bind,
3211 Lisp_Object value, enum Set_Internal_Bind bindflag)
3213 switch (sym->redirect)
3215 case SYMBOL_PLAINVAL:
3216 if (!sym->trapped_write)
3217 SET_SYMBOL_VAL (sym, value);
3218 else
3219 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3220 break;
3222 case SYMBOL_FORWARDED:
3223 if (BUFFER_OBJFWDP (SYMBOL_FWD (sym))
3224 && specpdl_kind (bind) == SPECPDL_LET_DEFAULT)
3226 set_default_internal (specpdl_symbol (bind), value, bindflag);
3227 return;
3229 /* FALLTHROUGH */
3230 case SYMBOL_LOCALIZED:
3231 set_internal (specpdl_symbol (bind), value, Qnil, bindflag);
3232 break;
3234 default:
3235 emacs_abort ();
3239 /* `specpdl_ptr' describes which variable is
3240 let-bound, so it can be properly undone when we unbind_to.
3241 It can be either a plain SPECPDL_LET or a SPECPDL_LET_LOCAL/DEFAULT.
3242 - SYMBOL is the variable being bound. Note that it should not be
3243 aliased (i.e. when let-binding V1 that's aliased to V2, we want
3244 to record V2 here).
3245 - WHERE tells us in which buffer the binding took place.
3246 This is used for SPECPDL_LET_LOCAL bindings (i.e. bindings to a
3247 buffer-local variable) as well as for SPECPDL_LET_DEFAULT bindings,
3248 i.e. bindings to the default value of a variable which can be
3249 buffer-local. */
3251 void
3252 specbind (Lisp_Object symbol, Lisp_Object value)
3254 struct Lisp_Symbol *sym;
3256 CHECK_SYMBOL (symbol);
3257 sym = XSYMBOL (symbol);
3259 start:
3260 switch (sym->redirect)
3262 case SYMBOL_VARALIAS:
3263 sym = indirect_variable (sym); XSETSYMBOL (symbol, sym); goto start;
3264 case SYMBOL_PLAINVAL:
3265 /* The most common case is that of a non-constant symbol with a
3266 trivial value. Make that as fast as we can. */
3267 specpdl_ptr->let.kind = SPECPDL_LET;
3268 specpdl_ptr->let.symbol = symbol;
3269 specpdl_ptr->let.old_value = SYMBOL_VAL (sym);
3270 specpdl_ptr->let.saved_value = Qnil;
3271 grow_specpdl ();
3272 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3273 break;
3274 case SYMBOL_LOCALIZED:
3275 case SYMBOL_FORWARDED:
3277 Lisp_Object ovalue = find_symbol_value (symbol);
3278 specpdl_ptr->let.kind = SPECPDL_LET_LOCAL;
3279 specpdl_ptr->let.symbol = symbol;
3280 specpdl_ptr->let.old_value = ovalue;
3281 specpdl_ptr->let.where = Fcurrent_buffer ();
3282 specpdl_ptr->let.saved_value = Qnil;
3284 eassert (sym->redirect != SYMBOL_LOCALIZED
3285 || (EQ (SYMBOL_BLV (sym)->where, Fcurrent_buffer ())));
3287 if (sym->redirect == SYMBOL_LOCALIZED)
3289 if (!blv_found (SYMBOL_BLV (sym)))
3290 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3292 else if (BUFFER_OBJFWDP (SYMBOL_FWD (sym)))
3294 /* If SYMBOL is a per-buffer variable which doesn't have a
3295 buffer-local value here, make the `let' change the global
3296 value by changing the value of SYMBOL in all buffers not
3297 having their own value. This is consistent with what
3298 happens with other buffer-local variables. */
3299 if (NILP (Flocal_variable_p (symbol, Qnil)))
3301 specpdl_ptr->let.kind = SPECPDL_LET_DEFAULT;
3302 grow_specpdl ();
3303 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3304 return;
3307 else
3308 specpdl_ptr->let.kind = SPECPDL_LET;
3310 grow_specpdl ();
3311 do_specbind (sym, specpdl_ptr - 1, value, SET_INTERNAL_BIND);
3312 break;
3314 default: emacs_abort ();
3318 /* Push unwind-protect entries of various types. */
3320 void
3321 record_unwind_protect (void (*function) (Lisp_Object), Lisp_Object arg)
3323 specpdl_ptr->unwind.kind = SPECPDL_UNWIND;
3324 specpdl_ptr->unwind.func = function;
3325 specpdl_ptr->unwind.arg = arg;
3326 grow_specpdl ();
3329 void
3330 record_unwind_protect_ptr (void (*function) (void *), void *arg)
3332 specpdl_ptr->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3333 specpdl_ptr->unwind_ptr.func = function;
3334 specpdl_ptr->unwind_ptr.arg = arg;
3335 grow_specpdl ();
3338 void
3339 record_unwind_protect_int (void (*function) (int), int arg)
3341 specpdl_ptr->unwind_int.kind = SPECPDL_UNWIND_INT;
3342 specpdl_ptr->unwind_int.func = function;
3343 specpdl_ptr->unwind_int.arg = arg;
3344 grow_specpdl ();
3347 void
3348 record_unwind_protect_void (void (*function) (void))
3350 specpdl_ptr->unwind_void.kind = SPECPDL_UNWIND_VOID;
3351 specpdl_ptr->unwind_void.func = function;
3352 grow_specpdl ();
3355 void
3356 rebind_for_thread_switch (void)
3358 union specbinding *bind;
3360 for (bind = specpdl; bind != specpdl_ptr; ++bind)
3362 if (bind->kind >= SPECPDL_LET)
3364 Lisp_Object value = specpdl_saved_value (bind);
3365 Lisp_Object sym = specpdl_symbol (bind);
3366 bind->let.saved_value = Qnil;
3367 do_specbind (XSYMBOL (sym), bind, value,
3368 SET_INTERNAL_THREAD_SWITCH);
3373 static void
3374 do_one_unbind (union specbinding *this_binding, bool unwinding,
3375 enum Set_Internal_Bind bindflag)
3377 eassert (unwinding || this_binding->kind >= SPECPDL_LET);
3378 switch (this_binding->kind)
3380 case SPECPDL_UNWIND:
3381 this_binding->unwind.func (this_binding->unwind.arg);
3382 break;
3383 case SPECPDL_UNWIND_PTR:
3384 this_binding->unwind_ptr.func (this_binding->unwind_ptr.arg);
3385 break;
3386 case SPECPDL_UNWIND_INT:
3387 this_binding->unwind_int.func (this_binding->unwind_int.arg);
3388 break;
3389 case SPECPDL_UNWIND_VOID:
3390 this_binding->unwind_void.func ();
3391 break;
3392 case SPECPDL_BACKTRACE:
3393 break;
3394 case SPECPDL_LET:
3395 { /* If variable has a trivial value (no forwarding), and isn't
3396 trapped, we can just set it. */
3397 Lisp_Object sym = specpdl_symbol (this_binding);
3398 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3400 if (XSYMBOL (sym)->trapped_write == SYMBOL_UNTRAPPED_WRITE)
3401 SET_SYMBOL_VAL (XSYMBOL (sym), specpdl_old_value (this_binding));
3402 else
3403 set_internal (sym, specpdl_old_value (this_binding),
3404 Qnil, bindflag);
3405 break;
3407 else
3408 { /* FALLTHROUGH!!
3409 NOTE: we only ever come here if make_local_foo was used for
3410 the first time on this var within this let. */
3413 case SPECPDL_LET_DEFAULT:
3414 set_default_internal (specpdl_symbol (this_binding),
3415 specpdl_old_value (this_binding),
3416 bindflag);
3417 break;
3418 case SPECPDL_LET_LOCAL:
3420 Lisp_Object symbol = specpdl_symbol (this_binding);
3421 Lisp_Object where = specpdl_where (this_binding);
3422 Lisp_Object old_value = specpdl_old_value (this_binding);
3423 eassert (BUFFERP (where));
3425 /* If this was a local binding, reset the value in the appropriate
3426 buffer, but only if that buffer's binding still exists. */
3427 if (!NILP (Flocal_variable_p (symbol, where)))
3428 set_internal (symbol, old_value, where, bindflag);
3430 break;
3434 static void
3435 do_nothing (void)
3438 /* Push an unwind-protect entry that does nothing, so that
3439 set_unwind_protect_ptr can overwrite it later. */
3441 void
3442 record_unwind_protect_nothing (void)
3444 record_unwind_protect_void (do_nothing);
3447 /* Clear the unwind-protect entry COUNT, so that it does nothing.
3448 It need not be at the top of the stack. */
3450 void
3451 clear_unwind_protect (ptrdiff_t count)
3453 union specbinding *p = specpdl + count;
3454 p->unwind_void.kind = SPECPDL_UNWIND_VOID;
3455 p->unwind_void.func = do_nothing;
3458 /* Set the unwind-protect entry COUNT so that it invokes FUNC (ARG).
3459 It need not be at the top of the stack. Discard the entry's
3460 previous value without invoking it. */
3462 void
3463 set_unwind_protect (ptrdiff_t count, void (*func) (Lisp_Object),
3464 Lisp_Object arg)
3466 union specbinding *p = specpdl + count;
3467 p->unwind.kind = SPECPDL_UNWIND;
3468 p->unwind.func = func;
3469 p->unwind.arg = arg;
3472 void
3473 set_unwind_protect_ptr (ptrdiff_t count, void (*func) (void *), void *arg)
3475 union specbinding *p = specpdl + count;
3476 p->unwind_ptr.kind = SPECPDL_UNWIND_PTR;
3477 p->unwind_ptr.func = func;
3478 p->unwind_ptr.arg = arg;
3481 /* Pop and execute entries from the unwind-protect stack until the
3482 depth COUNT is reached. Return VALUE. */
3484 Lisp_Object
3485 unbind_to (ptrdiff_t count, Lisp_Object value)
3487 Lisp_Object quitf = Vquit_flag;
3489 Vquit_flag = Qnil;
3491 while (specpdl_ptr != specpdl + count)
3493 /* Copy the binding, and decrement specpdl_ptr, before we do
3494 the work to unbind it. We decrement first
3495 so that an error in unbinding won't try to unbind
3496 the same entry again, and we copy the binding first
3497 in case more bindings are made during some of the code we run. */
3499 union specbinding this_binding;
3500 this_binding = *--specpdl_ptr;
3502 do_one_unbind (&this_binding, true, SET_INTERNAL_UNBIND);
3505 if (NILP (Vquit_flag) && !NILP (quitf))
3506 Vquit_flag = quitf;
3508 return value;
3511 void
3512 unbind_for_thread_switch (struct thread_state *thr)
3514 union specbinding *bind;
3516 for (bind = thr->m_specpdl_ptr; bind > thr->m_specpdl;)
3518 if ((--bind)->kind >= SPECPDL_LET)
3520 Lisp_Object sym = specpdl_symbol (bind);
3521 bind->let.saved_value = find_symbol_value (sym);
3522 do_one_unbind (bind, false, SET_INTERNAL_THREAD_SWITCH);
3527 DEFUN ("special-variable-p", Fspecial_variable_p, Sspecial_variable_p, 1, 1, 0,
3528 doc: /* Return non-nil if SYMBOL's global binding has been declared special.
3529 A special variable is one that will be bound dynamically, even in a
3530 context where binding is lexical by default. */)
3531 (Lisp_Object symbol)
3533 CHECK_SYMBOL (symbol);
3534 return XSYMBOL (symbol)->declared_special ? Qt : Qnil;
3538 static union specbinding *
3539 get_backtrace_starting_at (Lisp_Object base)
3541 union specbinding *pdl = backtrace_top ();
3543 if (!NILP (base))
3544 { /* Skip up to `base'. */
3545 base = Findirect_function (base, Qt);
3546 while (backtrace_p (pdl)
3547 && !EQ (base, Findirect_function (backtrace_function (pdl), Qt)))
3548 pdl = backtrace_next (pdl);
3551 return pdl;
3554 static union specbinding *
3555 get_backtrace_frame (Lisp_Object nframes, Lisp_Object base)
3557 register EMACS_INT i;
3559 CHECK_NATNUM (nframes);
3560 union specbinding *pdl = get_backtrace_starting_at (base);
3562 /* Find the frame requested. */
3563 for (i = XFASTINT (nframes); i > 0 && backtrace_p (pdl); i--)
3564 pdl = backtrace_next (pdl);
3566 return pdl;
3569 static Lisp_Object
3570 backtrace_frame_apply (Lisp_Object function, union specbinding *pdl)
3572 if (!backtrace_p (pdl))
3573 return Qnil;
3575 Lisp_Object flags = Qnil;
3576 if (backtrace_debug_on_exit (pdl))
3577 flags = Fcons (QCdebug_on_exit, Fcons (Qt, Qnil));
3579 if (backtrace_nargs (pdl) == UNEVALLED)
3580 return call4 (function, Qnil, backtrace_function (pdl), *backtrace_args (pdl), flags);
3581 else
3583 Lisp_Object tem = Flist (backtrace_nargs (pdl), backtrace_args (pdl));
3584 return call4 (function, Qt, backtrace_function (pdl), tem, flags);
3588 DEFUN ("backtrace-debug", Fbacktrace_debug, Sbacktrace_debug, 2, 2, 0,
3589 doc: /* Set the debug-on-exit flag of eval frame LEVEL levels down to FLAG.
3590 The debugger is entered when that frame exits, if the flag is non-nil. */)
3591 (Lisp_Object level, Lisp_Object flag)
3593 CHECK_NUMBER (level);
3594 union specbinding *pdl = get_backtrace_frame(level, Qnil);
3596 if (backtrace_p (pdl))
3597 set_backtrace_debug_on_exit (pdl, !NILP (flag));
3599 return flag;
3602 DEFUN ("mapbacktrace", Fmapbacktrace, Smapbacktrace, 1, 2, 0,
3603 doc: /* Call FUNCTION for each frame in backtrace.
3604 If BASE is non-nil, it should be a function and iteration will start
3605 from its nearest activation frame.
3606 FUNCTION is called with 4 arguments: EVALD, FUNC, ARGS, and FLAGS. If
3607 a frame has not evaluated its arguments yet or is a special form,
3608 EVALD is nil and ARGS is a list of forms. If a frame has evaluated
3609 its arguments and called its function already, EVALD is t and ARGS is
3610 a list of values.
3611 FLAGS is a plist of properties of the current frame: currently, the
3612 only supported property is :debug-on-exit. `mapbacktrace' always
3613 returns nil. */)
3614 (Lisp_Object function, Lisp_Object base)
3616 union specbinding *pdl = get_backtrace_starting_at (base);
3618 while (backtrace_p (pdl))
3620 backtrace_frame_apply (function, pdl);
3621 pdl = backtrace_next (pdl);
3624 return Qnil;
3627 DEFUN ("backtrace-frame--internal", Fbacktrace_frame_internal,
3628 Sbacktrace_frame_internal, 3, 3, NULL,
3629 doc: /* Call FUNCTION on stack frame NFRAMES away from BASE.
3630 Return the result of FUNCTION, or nil if no matching frame could be found. */)
3631 (Lisp_Object function, Lisp_Object nframes, Lisp_Object base)
3633 return backtrace_frame_apply (function, get_backtrace_frame (nframes, base));
3636 /* For backtrace-eval, we want to temporarily unwind the last few elements of
3637 the specpdl stack, and then rewind them. We store the pre-unwind values
3638 directly in the pre-existing specpdl elements (i.e. we swap the current
3639 value and the old value stored in the specpdl), kind of like the inplace
3640 pointer-reversal trick. As it turns out, the rewind does the same as the
3641 unwind, except it starts from the other end of the specpdl stack, so we use
3642 the same function for both unwind and rewind. */
3643 static void
3644 backtrace_eval_unrewind (int distance)
3646 union specbinding *tmp = specpdl_ptr;
3647 int step = -1;
3648 if (distance < 0)
3649 { /* It's a rewind rather than unwind. */
3650 tmp += distance - 1;
3651 step = 1;
3652 distance = -distance;
3655 for (; distance > 0; distance--)
3657 tmp += step;
3658 switch (tmp->kind)
3660 /* FIXME: Ideally we'd like to "temporarily unwind" (some of) those
3661 unwind_protect, but the problem is that we don't know how to
3662 rewind them afterwards. */
3663 case SPECPDL_UNWIND:
3665 Lisp_Object oldarg = tmp->unwind.arg;
3666 if (tmp->unwind.func == set_buffer_if_live)
3667 tmp->unwind.arg = Fcurrent_buffer ();
3668 else if (tmp->unwind.func == save_excursion_restore)
3669 tmp->unwind.arg = save_excursion_save ();
3670 else
3671 break;
3672 tmp->unwind.func (oldarg);
3673 break;
3676 case SPECPDL_UNWIND_PTR:
3677 case SPECPDL_UNWIND_INT:
3678 case SPECPDL_UNWIND_VOID:
3679 case SPECPDL_BACKTRACE:
3680 break;
3681 case SPECPDL_LET:
3682 { /* If variable has a trivial value (no forwarding), we can
3683 just set it. No need to check for constant symbols here,
3684 since that was already done by specbind. */
3685 Lisp_Object sym = specpdl_symbol (tmp);
3686 if (SYMBOLP (sym) && XSYMBOL (sym)->redirect == SYMBOL_PLAINVAL)
3688 Lisp_Object old_value = specpdl_old_value (tmp);
3689 set_specpdl_old_value (tmp, SYMBOL_VAL (XSYMBOL (sym)));
3690 SET_SYMBOL_VAL (XSYMBOL (sym), old_value);
3691 break;
3693 else
3694 { /* FALLTHROUGH!!
3695 NOTE: we only ever come here if make_local_foo was used for
3696 the first time on this var within this let. */
3699 case SPECPDL_LET_DEFAULT:
3701 Lisp_Object sym = specpdl_symbol (tmp);
3702 Lisp_Object old_value = specpdl_old_value (tmp);
3703 set_specpdl_old_value (tmp, Fdefault_value (sym));
3704 Fset_default (sym, old_value);
3706 break;
3707 case SPECPDL_LET_LOCAL:
3709 Lisp_Object symbol = specpdl_symbol (tmp);
3710 Lisp_Object where = specpdl_where (tmp);
3711 Lisp_Object old_value = specpdl_old_value (tmp);
3712 eassert (BUFFERP (where));
3714 /* If this was a local binding, reset the value in the appropriate
3715 buffer, but only if that buffer's binding still exists. */
3716 if (!NILP (Flocal_variable_p (symbol, where)))
3718 set_specpdl_old_value
3719 (tmp, Fbuffer_local_value (symbol, where));
3720 set_internal (symbol, old_value, where, SET_INTERNAL_UNBIND);
3723 break;
3728 DEFUN ("backtrace-eval", Fbacktrace_eval, Sbacktrace_eval, 2, 3, NULL,
3729 doc: /* Evaluate EXP in the context of some activation frame.
3730 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3731 (Lisp_Object exp, Lisp_Object nframes, Lisp_Object base)
3733 union specbinding *pdl = get_backtrace_frame (nframes, base);
3734 ptrdiff_t count = SPECPDL_INDEX ();
3735 ptrdiff_t distance = specpdl_ptr - pdl;
3736 eassert (distance >= 0);
3738 if (!backtrace_p (pdl))
3739 error ("Activation frame not found!");
3741 backtrace_eval_unrewind (distance);
3742 record_unwind_protect_int (backtrace_eval_unrewind, -distance);
3744 /* Use eval_sub rather than Feval since the main motivation behind
3745 backtrace-eval is to be able to get/set the value of lexical variables
3746 from the debugger. */
3747 return unbind_to (count, eval_sub (exp));
3750 DEFUN ("backtrace--locals", Fbacktrace__locals, Sbacktrace__locals, 1, 2, NULL,
3751 doc: /* Return names and values of local variables of a stack frame.
3752 NFRAMES and BASE specify the activation frame to use, as in `backtrace-frame'. */)
3753 (Lisp_Object nframes, Lisp_Object base)
3755 union specbinding *frame = get_backtrace_frame (nframes, base);
3756 union specbinding *prevframe
3757 = get_backtrace_frame (make_number (XFASTINT (nframes) - 1), base);
3758 ptrdiff_t distance = specpdl_ptr - frame;
3759 Lisp_Object result = Qnil;
3760 eassert (distance >= 0);
3762 if (!backtrace_p (prevframe))
3763 error ("Activation frame not found!");
3764 if (!backtrace_p (frame))
3765 error ("Activation frame not found!");
3767 /* The specpdl entries normally contain the symbol being bound along with its
3768 `old_value', so it can be restored. The new value to which it is bound is
3769 available in one of two places: either in the current value of the
3770 variable (if it hasn't been rebound yet) or in the `old_value' slot of the
3771 next specpdl entry for it.
3772 `backtrace_eval_unrewind' happens to swap the role of `old_value'
3773 and "new value", so we abuse it here, to fetch the new value.
3774 It's ugly (we'd rather not modify global data) and a bit inefficient,
3775 but it does the job for now. */
3776 backtrace_eval_unrewind (distance);
3778 /* Grab values. */
3780 union specbinding *tmp = prevframe;
3781 for (; tmp > frame; tmp--)
3783 switch (tmp->kind)
3785 case SPECPDL_LET:
3786 case SPECPDL_LET_DEFAULT:
3787 case SPECPDL_LET_LOCAL:
3789 Lisp_Object sym = specpdl_symbol (tmp);
3790 Lisp_Object val = specpdl_old_value (tmp);
3791 if (EQ (sym, Qinternal_interpreter_environment))
3793 Lisp_Object env = val;
3794 for (; CONSP (env); env = XCDR (env))
3796 Lisp_Object binding = XCAR (env);
3797 if (CONSP (binding))
3798 result = Fcons (Fcons (XCAR (binding),
3799 XCDR (binding)),
3800 result);
3803 else
3804 result = Fcons (Fcons (sym, val), result);
3806 break;
3808 case SPECPDL_UNWIND:
3809 case SPECPDL_UNWIND_PTR:
3810 case SPECPDL_UNWIND_INT:
3811 case SPECPDL_UNWIND_VOID:
3812 case SPECPDL_BACKTRACE:
3813 break;
3815 default:
3816 emacs_abort ();
3821 /* Restore values from specpdl to original place. */
3822 backtrace_eval_unrewind (-distance);
3824 return result;
3828 void
3829 mark_specpdl (union specbinding *first, union specbinding *ptr)
3831 union specbinding *pdl;
3832 for (pdl = first; pdl != ptr; pdl++)
3834 switch (pdl->kind)
3836 case SPECPDL_UNWIND:
3837 mark_object (specpdl_arg (pdl));
3838 break;
3840 case SPECPDL_BACKTRACE:
3842 ptrdiff_t nargs = backtrace_nargs (pdl);
3843 mark_object (backtrace_function (pdl));
3844 if (nargs == UNEVALLED)
3845 nargs = 1;
3846 while (nargs--)
3847 mark_object (backtrace_args (pdl)[nargs]);
3849 break;
3851 case SPECPDL_LET_DEFAULT:
3852 case SPECPDL_LET_LOCAL:
3853 mark_object (specpdl_where (pdl));
3854 /* Fall through. */
3855 case SPECPDL_LET:
3856 mark_object (specpdl_symbol (pdl));
3857 mark_object (specpdl_old_value (pdl));
3858 mark_object (specpdl_saved_value (pdl));
3859 break;
3861 case SPECPDL_UNWIND_PTR:
3862 case SPECPDL_UNWIND_INT:
3863 case SPECPDL_UNWIND_VOID:
3864 break;
3866 default:
3867 emacs_abort ();
3872 void
3873 get_backtrace (Lisp_Object array)
3875 union specbinding *pdl = backtrace_next (backtrace_top ());
3876 ptrdiff_t i = 0, asize = ASIZE (array);
3878 /* Copy the backtrace contents into working memory. */
3879 for (; i < asize; i++)
3881 if (backtrace_p (pdl))
3883 ASET (array, i, backtrace_function (pdl));
3884 pdl = backtrace_next (pdl);
3886 else
3887 ASET (array, i, Qnil);
3891 Lisp_Object backtrace_top_function (void)
3893 union specbinding *pdl = backtrace_top ();
3894 return (backtrace_p (pdl) ? backtrace_function (pdl) : Qnil);
3897 void
3898 syms_of_eval (void)
3900 DEFVAR_INT ("max-specpdl-size", max_specpdl_size,
3901 doc: /* Limit on number of Lisp variable bindings and `unwind-protect's.
3902 If Lisp code tries to increase the total number past this amount,
3903 an error is signaled.
3904 You can safely use a value considerably larger than the default value,
3905 if that proves inconveniently small. However, if you increase it too far,
3906 Emacs could run out of memory trying to make the stack bigger.
3907 Note that this limit may be silently increased by the debugger
3908 if `debug-on-error' or `debug-on-quit' is set. */);
3910 DEFVAR_INT ("max-lisp-eval-depth", max_lisp_eval_depth,
3911 doc: /* Limit on depth in `eval', `apply' and `funcall' before error.
3913 This limit serves to catch infinite recursions for you before they cause
3914 actual stack overflow in C, which would be fatal for Emacs.
3915 You can safely make it considerably larger than its default value,
3916 if that proves inconveniently small. However, if you increase it too far,
3917 Emacs could overflow the real C stack, and crash. */);
3919 DEFVAR_LISP ("quit-flag", Vquit_flag,
3920 doc: /* Non-nil causes `eval' to abort, unless `inhibit-quit' is non-nil.
3921 If the value is t, that means do an ordinary quit.
3922 If the value equals `throw-on-input', that means quit by throwing
3923 to the tag specified in `throw-on-input'; it's for handling `while-no-input'.
3924 Typing C-g sets `quit-flag' to t, regardless of `inhibit-quit',
3925 but `inhibit-quit' non-nil prevents anything from taking notice of that. */);
3926 Vquit_flag = Qnil;
3928 DEFVAR_LISP ("inhibit-quit", Vinhibit_quit,
3929 doc: /* Non-nil inhibits C-g quitting from happening immediately.
3930 Note that `quit-flag' will still be set by typing C-g,
3931 so a quit will be signaled as soon as `inhibit-quit' is nil.
3932 To prevent this happening, set `quit-flag' to nil
3933 before making `inhibit-quit' nil. */);
3934 Vinhibit_quit = Qnil;
3936 DEFSYM (Qsetq, "setq");
3937 DEFSYM (Qinhibit_quit, "inhibit-quit");
3938 DEFSYM (Qautoload, "autoload");
3939 DEFSYM (Qinhibit_debugger, "inhibit-debugger");
3940 DEFSYM (Qmacro, "macro");
3942 /* Note that the process handling also uses Qexit, but we don't want
3943 to staticpro it twice, so we just do it here. */
3944 DEFSYM (Qexit, "exit");
3946 DEFSYM (Qinteractive, "interactive");
3947 DEFSYM (Qcommandp, "commandp");
3948 DEFSYM (Qand_rest, "&rest");
3949 DEFSYM (Qand_optional, "&optional");
3950 DEFSYM (Qclosure, "closure");
3951 DEFSYM (QCdocumentation, ":documentation");
3952 DEFSYM (Qdebug, "debug");
3954 DEFVAR_LISP ("inhibit-debugger", Vinhibit_debugger,
3955 doc: /* Non-nil means never enter the debugger.
3956 Normally set while the debugger is already active, to avoid recursive
3957 invocations. */);
3958 Vinhibit_debugger = Qnil;
3960 DEFVAR_LISP ("debug-on-error", Vdebug_on_error,
3961 doc: /* Non-nil means enter debugger if an error is signaled.
3962 Does not apply to errors handled by `condition-case' or those
3963 matched by `debug-ignored-errors'.
3964 If the value is a list, an error only means to enter the debugger
3965 if one of its condition symbols appears in the list.
3966 When you evaluate an expression interactively, this variable
3967 is temporarily non-nil if `eval-expression-debug-on-error' is non-nil.
3968 The command `toggle-debug-on-error' toggles this.
3969 See also the variable `debug-on-quit' and `inhibit-debugger'. */);
3970 Vdebug_on_error = Qnil;
3972 DEFVAR_LISP ("debug-ignored-errors", Vdebug_ignored_errors,
3973 doc: /* List of errors for which the debugger should not be called.
3974 Each element may be a condition-name or a regexp that matches error messages.
3975 If any element applies to a given error, that error skips the debugger
3976 and just returns to top level.
3977 This overrides the variable `debug-on-error'.
3978 It does not apply to errors handled by `condition-case'. */);
3979 Vdebug_ignored_errors = Qnil;
3981 DEFVAR_BOOL ("debug-on-quit", debug_on_quit,
3982 doc: /* Non-nil means enter debugger if quit is signaled (C-g, for example).
3983 Does not apply if quit is handled by a `condition-case'. */);
3984 debug_on_quit = 0;
3986 DEFVAR_BOOL ("debug-on-next-call", debug_on_next_call,
3987 doc: /* Non-nil means enter debugger before next `eval', `apply' or `funcall'. */);
3989 DEFVAR_BOOL ("debugger-may-continue", debugger_may_continue,
3990 doc: /* Non-nil means debugger may continue execution.
3991 This is nil when the debugger is called under circumstances where it
3992 might not be safe to continue. */);
3993 debugger_may_continue = 1;
3995 DEFVAR_BOOL ("debugger-stack-frame-as-list", debugger_stack_frame_as_list,
3996 doc: /* Non-nil means display call stack frames as lists. */);
3997 debugger_stack_frame_as_list = 0;
3999 DEFVAR_LISP ("debugger", Vdebugger,
4000 doc: /* Function to call to invoke debugger.
4001 If due to frame exit, args are `exit' and the value being returned;
4002 this function's value will be returned instead of that.
4003 If due to error, args are `error' and a list of the args to `signal'.
4004 If due to `apply' or `funcall' entry, one arg, `lambda'.
4005 If due to `eval' entry, one arg, t. */);
4006 Vdebugger = Qnil;
4008 DEFVAR_LISP ("signal-hook-function", Vsignal_hook_function,
4009 doc: /* If non-nil, this is a function for `signal' to call.
4010 It receives the same arguments that `signal' was given.
4011 The Edebug package uses this to regain control. */);
4012 Vsignal_hook_function = Qnil;
4014 DEFVAR_LISP ("debug-on-signal", Vdebug_on_signal,
4015 doc: /* Non-nil means call the debugger regardless of condition handlers.
4016 Note that `debug-on-error', `debug-on-quit' and friends
4017 still determine whether to handle the particular condition. */);
4018 Vdebug_on_signal = Qnil;
4020 /* When lexical binding is being used,
4021 Vinternal_interpreter_environment is non-nil, and contains an alist
4022 of lexically-bound variable, or (t), indicating an empty
4023 environment. The lisp name of this variable would be
4024 `internal-interpreter-environment' if it weren't hidden.
4025 Every element of this list can be either a cons (VAR . VAL)
4026 specifying a lexical binding, or a single symbol VAR indicating
4027 that this variable should use dynamic scoping. */
4028 DEFSYM (Qinternal_interpreter_environment,
4029 "internal-interpreter-environment");
4030 DEFVAR_LISP ("internal-interpreter-environment",
4031 Vinternal_interpreter_environment,
4032 doc: /* If non-nil, the current lexical environment of the lisp interpreter.
4033 When lexical binding is not being used, this variable is nil.
4034 A value of `(t)' indicates an empty environment, otherwise it is an
4035 alist of active lexical bindings. */);
4036 Vinternal_interpreter_environment = Qnil;
4037 /* Don't export this variable to Elisp, so no one can mess with it
4038 (Just imagine if someone makes it buffer-local). */
4039 Funintern (Qinternal_interpreter_environment, Qnil);
4041 Vrun_hooks = intern_c_string ("run-hooks");
4042 staticpro (&Vrun_hooks);
4044 staticpro (&Vautoload_queue);
4045 Vautoload_queue = Qnil;
4046 staticpro (&Vsignaling_function);
4047 Vsignaling_function = Qnil;
4049 inhibit_lisp_code = Qnil;
4051 defsubr (&Sor);
4052 defsubr (&Sand);
4053 defsubr (&Sif);
4054 defsubr (&Scond);
4055 defsubr (&Sprogn);
4056 defsubr (&Sprog1);
4057 defsubr (&Sprog2);
4058 defsubr (&Ssetq);
4059 defsubr (&Squote);
4060 defsubr (&Sfunction);
4061 defsubr (&Sdefault_toplevel_value);
4062 defsubr (&Sset_default_toplevel_value);
4063 defsubr (&Sdefvar);
4064 defsubr (&Sdefvaralias);
4065 DEFSYM (Qdefvaralias, "defvaralias");
4066 defsubr (&Sdefconst);
4067 defsubr (&Smake_var_non_special);
4068 defsubr (&Slet);
4069 defsubr (&SletX);
4070 defsubr (&Swhile);
4071 defsubr (&Smacroexpand);
4072 defsubr (&Scatch);
4073 defsubr (&Sthrow);
4074 defsubr (&Sunwind_protect);
4075 defsubr (&Scondition_case);
4076 defsubr (&Ssignal);
4077 defsubr (&Scommandp);
4078 defsubr (&Sautoload);
4079 defsubr (&Sautoload_do_load);
4080 defsubr (&Seval);
4081 defsubr (&Sapply);
4082 defsubr (&Sfuncall);
4083 defsubr (&Sfunc_arity);
4084 defsubr (&Srun_hooks);
4085 defsubr (&Srun_hook_with_args);
4086 defsubr (&Srun_hook_with_args_until_success);
4087 defsubr (&Srun_hook_with_args_until_failure);
4088 defsubr (&Srun_hook_wrapped);
4089 defsubr (&Sfetch_bytecode);
4090 defsubr (&Sbacktrace_debug);
4091 DEFSYM (QCdebug_on_exit, ":debug-on-exit");
4092 defsubr (&Smapbacktrace);
4093 defsubr (&Sbacktrace_frame_internal);
4094 defsubr (&Sbacktrace_eval);
4095 defsubr (&Sbacktrace__locals);
4096 defsubr (&Sspecial_variable_p);
4097 defsubr (&Sfunctionp);